Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 131,933 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,835 people online right now. Registration is fast and FREE... Join Now!





Printing triangles on the console

uses various methods, including two recursive concepts.

Submitted By: gabehabe
Actions:
Rating:
Views: 417

Language: C++

Last Modified: July 15, 2008

Snippet


  1. /*
  2. * Printing triangles on the console
  3. * Various methods, including recursion
  4. * Author: Danny Battison
  5. * Contact: gabehabe@hotmail.com
  6. */
  7.  
  8. #include <iostream>
  9. #include <string>
  10.  
  11. /* The simplest method, using nested loops */
  12. void triangle (int x)
  13. {
  14.     for (int i = 1; i <= x; i++)
  15.     {
  16.         for (int j = 1; j <= i; j++)
  17.             std::cout << '*';
  18.         std::cout << std::endl;
  19.     }
  20. }
  21.  
  22. /* A recursive method, prints the triangle upside down */
  23. void recursiveTriangle (int y)
  24. {
  25.     if (y == 0) return;
  26.     for (int i = 0; i < y; i++)
  27.         std::cout << '*';
  28.     std::cout << std::endl;
  29.     y--;
  30.     recursiveTriangle(y);
  31. }
  32.  
  33. /* Another recursive method, prints the triangle the right way up, but takes 2 params */
  34. void recursiveTriangle2 (int x, int y)
  35. { /* x is the starting value, y is the ending value (when to return) */
  36.     if (x > y) return;
  37.     for (int i = 1; i <= x; i++)
  38.         std::cout << '*';
  39.     std::cout << std::endl;
  40.     x++;
  41.     recursiveTriangle2 (x, y);
  42. }
  43.  
  44. /** EXAMPLE USAGE **/
  45. int main ()
  46. {
  47.     triangle(4);
  48.     std::cout << std::endl;
  49.     recursiveTriangle(4);
  50.     std::cout << std::endl;
  51.     recursiveTriangle2(1,4);
  52.  
  53.     std::cin.get();
  54.     return EXIT_SUCCESS;
  55. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month