Snippet
/*
* Printing triangles on the console
* Various methods, including recursion
* Author: Danny Battison
* Contact: gabehabe@hotmail.com
*/
#include <iostream>
#include <string>
/* The simplest method, using nested loops */
void triangle (int x)
{
for (int i = 1; i <= x; i++)
{
for (int j = 1; j <= i; j++)
std::cout << '*';
std::cout << std::endl;
}
}
/* A recursive method, prints the triangle upside down */
void recursiveTriangle (int y)
{
if (y == 0) return;
for (int i = 0; i < y; i++)
std::cout << '*';
std::cout << std::endl;
y--;
recursiveTriangle(y);
}
/* Another recursive method, prints the triangle the right way up, but takes 2 params */
void recursiveTriangle2 (int x, int y)
{ /* x is the starting value, y is the ending value (when to return) */
if (x > y) return;
for (int i = 1; i <= x; i++)
std::cout << '*';
std::cout << std::endl;
x++;
recursiveTriangle2 (x, y);
}
/** EXAMPLE USAGE **/
int main ()
{
triangle(4);
std::cout << std::endl;
recursiveTriangle(4);
std::cout << std::endl;
recursiveTriangle2(1,4);
std::cin.get();
return EXIT_SUCCESS;
}
Copy & Paste
|