Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Creating patterns using C++

  1. Oct 9, 2011 #1
    How to create patterns using C++? I am new to programming and would really appreciate some help in creating patterns. For example, how will you create this pattern using two for-loops?

    *
    **
    ***
    ****
    *****


    And btw, this is not a homework question. Was just curious. Thanks. And please also explain the algorithm for creating such patterns. Thanks!
     
  2. jcsd
  3. Oct 9, 2011 #2

    Borek

    User Avatar

    Staff: Mentor

    External loop is responsible for the number of lines printed, internal loop is responsible for printing stars in each line.
     
  4. Oct 9, 2011 #3
    I tried, but all I get is a horizontal line of asterisks. what can be wrong?
     
  5. Oct 9, 2011 #4

    robphy

    User Avatar
    Science Advisor
    Homework Helper
    Gold Member

    cout<<endl;
     
  6. Oct 9, 2011 #5
    I included endl in the same cout statement, like this:

    cout <<"*"<<endl;

    does that make any difference?
     
  7. Oct 9, 2011 #6

    Borek

    User Avatar

    Staff: Mentor

    endl ends the line - if there is no endl added, all asterisks will land in one line:

    Code (Text):

    cout << "*";
    cout << "*";
    cout << "*";
    cout << "*";
     
    yields

    ****

    while

    Code (Text):

    cout << "*";
    cout << "*";
    cout << endl;
    cout << "*";
    cout << "*";
     
    yields

    **
    **

    Code (Text):
    cout << "*" << endl;
    and

    Code (Text):
    cout << "*";
    cout << endl;
    are equivalent.
     
  8. Oct 9, 2011 #7

    phinds

    User Avatar
    Gold Member
    2016 Award

    RoughRoad, when you are trying to do something with a program is is best to follow the old adage "if you don't know how to do it without a computer, then you don't know how to do it WITH a computer". The implication of this is that you should lay out a set of clearly defined, logical steps that do what you want. Then implementing those steps in a computer language should be trivial.

    For example:

    step 1: set n=1
    step 2: start a new line
    step 3: print n asterisks in a row
    step 4: increment n
    step 5: if n > 10 then stop
    step 5: go back to step 1

    EDIT: these steps, by the way, are called "pseudo code", which basically just means "I'm not really computer code but I'm a consistent, logical, set of steps written in English so I'm pretending to be computer code until somebody decides on a language and turns me into REAL computer code"
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook