Explaining Code Reading Problem: for (int i=0; i<=9; i++)

  • Thread starter Thread starter chmate
  • Start date Start date
  • Tags Tags
    Code Reading
Click For Summary
The discussion revolves around a piece of C++ code that generates a right-aligned triangle of asterisks. The code uses nested for loops to print spaces and asterisks, creating a pattern where each line has an increasing number of leading spaces and a decreasing number of asterisks. Participants point out a syntax error in the code, specifically the missing semicolon after the "cout << "*"" statement. They also suggest that the output will depend on the font used, recommending the use of graph paper to visualize the pattern accurately. Overall, the code is intended to produce a visual representation of a right-aligned triangle with asterisks, but it requires some corrections for proper execution.
chmate
Messages
37
Reaction score
0
Hi!

Code:
for (int i=0; i<=9; i++)
{
   for (int j=0; j<i; j++)
       cout << " ";
   for (int j=i; j<=9; j++)
        cout << "*"
   cout << endl;
}

Can anyone explain me what these lines are doing?

Thank you!
 
Technology news on Phys.org
what do you think the are doing?
Do you know how to trace through code like that?
...write it all out on bpaper.

If you don't know what a for loop does then i can't help ya.
the "cout<<endl" is just a new line.

EDIT: oh yeah you also hav ean error in your j-for loops
 
Last edited:
I don't know. It seems like it's printing 9 lines, each line having an increasing number of spaces and decreasing number of stars. But i can't figure out what something like that can possibly look like.
 
It does this:
**********
*********
********
*******
******
*****
****
***
**
*
Press any key to continue
When you don't try to redfine j in:
for (int j=i; j<=9; j++).. (I used x)
and correct the syntax error by adding a semi-colon to:
cout << "*"
Sorry for butting in...:blushing:
 
What it will look like depends on the font you use.
But, most things like this are ment for a fixed spacing font.
So take some graph paper and plot it out.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

Replies
12
Views
3K
  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 6 ·
Replies
6
Views
12K
Replies
10
Views
2K
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 23 ·
Replies
23
Views
3K