C++ Help Creating Pyramid of Xs

Appletax

Well-Known Member
Reaction score
396
Location
Northern Michigan
I have a C++ assignment that requires me to make a pyramid of Xs that's 20 lines high.
I need to use a loop or multiple loops to create the pyramid.

My issues are figuring out how to create a loop that will generate the 1st line, display 19 spaces, display 1 X,
then move to a second line with 1 less space and 2 additional Xs.

Please keep in mind that this is an introduction course, so don't write any crazy code :)
Keep it simple and easy to understand. Thanks :)

I'd like the get some hints 1st and instruction to try to mostly figure it out on my own.

Here's what I have so far:

 
Last edited:
Spoiler alert!!!

SPOILER ALERT!!!

Tips:
1. Your going to need some variables that don't get destroyed when you exit the loop that created them. Declare some variables outside of the loops.
2. Your ENDL needs to happen outside of the "X"-Writing loop. This is why you are getting one X per line (Among other issues with not having the variables declared outside of loop).
3. Your missing a set of curly-brackets.










A bit of code is worth a thousand words... I tried to "write" how to fix what you had but that ended up being kinda hard to convey with english, so here it is, one of many ways to do this, I'm sure. :)
Notice that the variables "spaceholder" and "xcount" only change when the "for" loops are exited, they are contained within the first "for" loop only.

78SBe.jpg
 
Last edited:
I didn't think this was a coding forum and should we really be giving you answers to your assignments?:D

My issues are figuring out how to create a loop that will generate the 1st line, display 19 spaces, display 1 X,
then move to a second line with 1 less space and 2 additional Xs.
My code is not pretty and it doesn't print out like you were asking for but it will print out a true pyramid.

Code:
#include <iostream>

using namespace std;

int main()
{

int line, spaces, xs, s, x;

for ( line = 0, spaces = 20, xs = 1; line < 20; line++, xs+=2, spaces-- )
{

// Prints line number and tab at start of line.
cout << line+1 << ". \t";

// Prints spaces
for ( s = 0; s < spaces; s++ )
cout << " ";

// Prints X's
for ( x = 0; x < xs; x++ )
cout << "X";

// Prints new line character at end of x's.
cout << "\n";
}

return 0;
}
 
Phased's solution is a very good one.

Take special notice of how he comments each line / block of code very carefully and concisely. This is A GOLDEN RULE OF CODING.

It will help incredibly when you go to debug/troubleshoot code that "isn't working".

Also note the style, how things are nested and code blocks are indented. You do not want every single line of code slammed up against the left side of the screen. Not only does this make it difficult if not impossible to trace, it's just not in good style/technique.

First off, where is your algorithm at? You need to get from a problem to a solution implemented in code. In this case you have a good understanding of the problem. Now you need to get the solution written down step by step (algorithm) and then convey that to code.

I don't know how much you do or do not know about writing algorithms, but basically the best way I can explain it is as follows:

Your going to teach someone how to bake a cake. They have no idea how to bake, no idea of what a cake is, they never used an oven nor do they even know they have to use an oven. They don't know what the ingredients are, how you combine them. They now nothing of the situation. Since you have other appointments, you cannot be there in person to walk them through it. You need to type out a series of steps (algorithm) that covers everything from start to finish in baking said cake.

Once you have a good understanding of the problem, you can being to write out the steps. Once your series of steps is thorough and correct then you start writing code.

You cannot solve the problem (programming exercise) until you can define and understand the problem.
 
Below is the code the teacher gave me. She gave me the answer and full credit :) My problem is that I have no idea how the multiple for loops are processed.

Will someone please explain each step of the process to create the first and 2nd lines?

My incorrect understanding is that the for loop's 1st line will be one space and no X; each subsequent line, up to line 20, would have one space and one X.
- FIRST LINE:
1st for: x is 1 and add 1 to x ... go to 2nd for: y=19 and add 1 to y ... output a single space and go to 3rd: z = 0 and z must be > 0, so do not process the following code, which is to display an X.

 
I use Visual Studio 2012 Ultimate. The teacher always tell us to run the program using run without debugging under the debug menu.

Lots of courses seem to hesitate on teaching how to debug i'd recommend playing with it. Its the best way to figure out whats happening in your application.
 
From the comments in your code "start a loop that runs 20 -x times" and the other one, I think you may be misunderstanding which part is which.

for loops are as follows:

for (initialization; condition; increase/decrease)

...so your loops aren't running "20-x" times or "2*x-1" times, they are running based on the middle section ("x <= 20", "y > 0", "z > 0"), the condition. The initialization simply sets the variable for each iteration of the loop, not each time time it cycles.

sV8i.jpg


LOL, this solution is sooo much cleaner than what I came up with. It always amazes me how many solutions there are to a problem and how elegant a solution can be reduced to. I tend to over-think the problem and think more linearly.. which tends to suck for programming, lol :D

EDIT: I second using the debugger, it's not cheating and I don't believe it hurts your learning and memorization.. I find it mostly helps when I have forgot a bracket or fat-finger something. If your dead set against the debugger, I usually output variables right in the program... so like "cout << "X" << z;" to see the value of z each time the loop goes by.
 
Last edited:
Below is the code the teacher gave me. She gave me the answer and full credit :) My problem is that I have no idea how the multiple for loops are processed.

Will someone please explain each step of the process to create the first and 2nd lines?

My incorrect understanding is that the for loop's 1st line will be one space and no X; each subsequent line, up to line 20, would have one space and one X.
- FIRST LINE:
1st for: x is 1 and add 1 to x ... go to 2nd for: y=19 and add 1 to y ... output a single space and go to 3rd: z = 0 and z must be > 0, so do not process the following code, which is to display an X.

One main thing that might help you to understand what is going on would be to replace the spaces with something you can actually see like maybe S's, for example instead of:
cout << " "; //print spaces
change it to some like
cout << "S"; //print spaces



When you have a for loop inside of another for it is called a nested for loop, in this little program you have two nested for loops inside one main loop.


for (int x=1; x <= 20; x++)
Starts the first main for loop, this for loop will be use to count the lines in this case there will be 20 lines.
It creates an integer variable named x and initializes that variable to 1 // int x=1;
It then checks the condition of x if x is less than or equal to 20 then the condition is true and it will run one loop of code in the { } brackets below it. // x <=20;
Once the for loop runs that code in its { } brackets only one time it comes back to the top of the for loop and increments x and that changes x from 1 to 2 and it will continue this looping until x is equal to 20 // x++

The code under the first for loop (The line for loop) is two nested for loops and a cout. During the first iteration of the line for loop the variable x is equal to 1. The first nested for loop begins (the spaces for loop).
for (int y = 20-x; y > 0; y--)
It creates an integer variable named y and initializes that y variable to 20-x, you know that x is equal to 1 from the line for loop above, so this means 20-x is the same as 20-1 or 19. // int y = 20-x;
It checks the condition of y if y is greater than 0 then the condition is true and it will run one loop of the code in the { } brackets below it.
Once it runs that code in the { } brackets only one time it comes back to the top of the spaces for loop and decrements y and that changes y from 19 to 18 and it will continue this looping as long as y is greater than 0. // y--
The first time through this spaces loop since y is initialized to 19 it will print 19 spaces, the next time this spaces loop is run y will be initialized at 18 because x will be 19 and 18 spaces will be printed, then the next time will 17 spaces and then 16 spaces and so on.

After the first nested loop (The spaces for loop) has completed printing 19 spaces then the next nested for loop is run (The X's for loop, the loop that prints the X's).
Once this last nested loop has completed a end line is printed then the program goes back to the top of the line for loop and increments the variable x from 1 to 2 and check the condition of x if x is less than or equal to 20 then the condition is true and it will run one loop of code in the { } brackets below it, in this second loop of the line for loop x will be 2 and the next time through x will be 3 until x is equal to 20.
 
One main thing that might help you to understand what is going on would be to replace the spaces with something you can actually see like maybe S's, for example instead of:
cout << " "; //print spaces
change it to some like
cout << "S"; //print spaces



When you have a for loop inside of another for it is called a nested for loop, in this little program you have two nested for loops inside one main loop.

Great explanation : )

For further clarification:

The first loop is essentially a counter loop that keeps track oh how many times the entire loop runs. It will allow the whole loop to run a total of 20 times.

The 2nd and 3rd loops are where instructions are processed. The second loop initializes at value 19, runs until the value is no longer true (compared to condition) before moving to loop 3. It starts at 19, prints a space, decrements the value to 18, prints a space, and does this process until the value of 19 falls to 0. This creates 19 spaces.

The interesting part here is that the first loop increments 1 time during the entire loop, and the other loops decrement several times before the entire loop completes one cycle.
 
The interesting part here is that the first loop increments 1 time during the entire loop, and the other loops decrement several times before the entire loop completes one cycle.
Think of nested loops like this, today a teacher will tell a student to do a writing task 20 different times during the day and the students task will be to write something down 10 times.
Here is a even better way to explain it using a car's odometer: http://mathbits.com/MathBits/CompSci/looping/nested.htm



The first loop is essentially a counter loop that keeps track oh how many times the entire loop runs.
It really doesn't keep track, it just loops for 20 times (lines).
You could add a variable, an increment and a cout to keep track of how many times a for loop is looped, for example:

Code:
#include <iostream>

using namespace std;

int main()
{
    //Variable to keep track of the iteration times.
    int iTimes=0;
    
    // Loops for 10 times
    for ( int iI=1; iI<11; iI++ )
    {
        // Prints line number and tab at start of line and number of loop.
        cout << iI << ". \t" << "Loop number " << iI << endl;
        
        // Adds one to iTimes variable each iteration of the for loop
        iTimes++;
    }
    
    // This prints out the total count of loops.
    cout << "\n\tThere was a total of " <<  iTimes << " loops or lines\n\n" << endl;
    
    // Pauses the program
    system("pause");
    
return 0;
}
Also note the style, how things are nested and code blocks are indented. You do not want every single line of code slammed up against the left side of the screen. Not only does this make it difficult if not impossible to trace, it's just not in good style/technique.
I coded the above program in an IDE so that the style would be good unlike my earlier program in post #3.:p
 
Again, where is the algorithm.

These are habits you NEED TO HAVE, if your going to program anything of "value". I don't know why your taking the course but if it is your goal to be able to code anything of any significance then there are steps you need to take.

Debugging is a must. You can do it either way mentioned here, during my software engineering studies I did it with output statements like cout so that you can see how variables are changing and essentially make sure that your logic is correct and working as you intend.

Later on you might learn about Big-O notations, basically how to rate the efficiency of certain segments of code. To figure out how much "work" the code takes to solve a problem written one way and then to try to refine it so that the same answers can be produced with less work.
 
I forgot to say....

props to whatever college you're going to thats still teaching c++ the degree programs around here are java and c#.


At the job fairs that I attended post graduation, the majority of the students there couldn't explain basic data structures. Most had no experience writing procedural code. C++ was the bulk of what we used when I was studying for software engineering. We also used Ada, Java, C#, Visual Basic (.net) and cold fusion. Most schools go straight to high level stuff and tend to pass on data structs, discrete math topics, files and file applications, higher level object oriented stuff, and command line programming.

I don't know how you can even learn to be a software developer without that stuff! Not knowing what a linked list was !
 
Again, where is the algorithm.

These are habits you NEED TO HAVE, if your going to program anything of "value". I don't know why your taking the course but if it is your goal to be able to code anything of any significance then there are steps you need to take.

Debugging is a must. You can do it either way mentioned here, during my software engineering studies I did it with output statements like cout so that you can see how variables are changing and essentially make sure that your logic is correct and working as you intend.

Later on you might learn about Big-O notations, basically how to rate the efficiency of certain segments of code. To figure out how much "work" the code takes to solve a problem written one way and then to try to refine it so that the same answers can be produced with less work.

Algorithms are the instructions. We learned about them in the beginning and they are used throughout the book. We can write the instructions using pseudo-code (write what the computer will do using regular English and no actual code) or visually depict what's going on using a flow chart. I haven't been using either since the first few weeks of class.

The degree I'm pursuing is a BS in computer networking. I never had any intention on being a programmer, which is why I stayed far away from computer science (and because the higher-level math would make me extremely miserable.) Maybe I could do coding as a part of my job, but it can't be what the whole job is about. I have no desire to be a full-time programmer.

Why is it surprising that the class teaches C++? The title of the class is Intro to Computer Science 1. For the 3+1 articulation agreement (3/4 of degree at the community college & 1/4 of degree at the university) we can either take intro to comp. or visual basic (1 year basic is offered and the other is intro to comp). I have to take Comp Science 2 next semester.

At the university I'll be going to next Fall, I'll be taking Java, javascript and maybe one other programming class.

The classes needed for the degree are listed here:
http://www.baycollege.edu/Academics...portunities/Computer-Networking-2012-Apr.aspx
 
Why is it surprising that the class teaches C++? The title of the class is Intro to Computer Science 1. For the 3+1 articulation agreement (3/4 of degree at the community college & 1/4 of degree at the university) we can either take intro to comp. or visual basic (1 year basic is offered and the other is intro to comp). I have to take Comp Science 2 next semester.

At the university I'll be going to next Fall, I'll be taking Java, javascript and maybe one other programming class.

The classes needed for the degree are listed here:
http://www.baycollege.edu/Academics...portunities/Computer-Networking-2012-Apr.aspx

Ever play with legos as a kid? Lets say you wanted to build a custom castle. C++ would be like building a castle out of regular legos you know the little squares and rectangles. c#/java would be like buying lego sets designed for castle building...perhaps not the best analogy

c#/java is easier and far more popular these days, c++ is harder, performs faster, and is lower level (think my bad lego analogy).

I generally have more faith in the coding abilities of a c++ programmer than on the coding abilities of a c#/java coder. c++ is what most video games are written in.

Edit: I can't think of a reason someone going into computer networking would need c++ but it doesnt matter moving what you learn in c++ to java would be a walk in the park.
 
Last edited:
Back
Top