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

In summary, this is a code that uses nested for loops to print a pattern of asterisks in decreasing size and increasing number of spaces for a total of 9 lines. There is also a syntax error in the code.
  • #1
chmate
37
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
  • #2
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:
  • #3
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.
 
  • #4
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:
 
  • #5
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.
 

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

What is the purpose of the "for" loop in this code?

The "for" loop is used to iterate through a block of code for a specified number of times. In this case, the loop will run 10 times since the value of "i" starts at 0 and increments by 1 each time until it reaches 9.

What does the "int i=0" mean?

The "int i=0" is the initialization statement in the "for" loop. It declares and initializes the variable "i" to 0, which will be used as the starting point for the loop.

What is the significance of the condition "i<=9"?

The condition "i<=9" determines when the loop will stop iterating. As long as the value of "i" is less than or equal to 9, the loop will continue to run. Once it reaches 10, the condition will evaluate to false and the loop will end.

What happens inside the loop?

The code inside the loop will be executed repeatedly until the loop ends. This could include performing calculations, manipulating data, or calling other functions.

What is the purpose of "i++" in the "for" loop?

The "i++" is the increment statement in the "for" loop. It increases the value of "i" by 1 each time the loop runs, ensuring that the condition will eventually be false and the loop will end.

Back
Top