[Help] Nested for loop

Sep 27, 2014 at 9:41am
Can someone please explain to me the logic of nested for loop statement?
Im just a newbie.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 #include<iostream>
using namespace std;
int main()
{
	for (int x=1;x<=5;x++)
	{
		for(int y=1;y<=x;y++)
		{
			cout<<x;
		}
		cout<<endl;
		
	}

}
Sep 27, 2014 at 9:46am
closed account (48T7M4Gy)
Try changing y<=x to y< x in line 7 and the loops might make more sense to you.
Sep 28, 2014 at 12:45am
Of course.

So the first for-loop says int x=1;x<=5;x++
This means that we start with x=1
We then do whatever is inside the brackets of the for-loop (These --> { } )
After we do whatever is inside the bracket, we will increase the value of x by 1... x++
Finally the program will check to see if x is bigger than 5 ... x<=5
If it is greater than five, then we will not do the for-loop and go onto the next part of the code.

So the process will go as such...
x=1 , do the inside part, increase x by 1 (2), check to see if x is larger than 5 (no)
x=2 , do the inside part, increase x by 1 (3), check to see if x is larger than 5 (no)
x=3 , do the inside part, increase x by 1 (4), check to see if x is larger than 5 (no)
x=4 , do the inside part, increase x by 1 (5), check to see if x is larger than 5 (no)
x=5 , do the inside part, increase x by 1 (6), check to see if x is larger than 5 (yes)

Now count how many times we "do the inside part". We have 5. So we will do the inside part 5 times.

Now we can apply the same process to the inside for-loop.
Last edited on Sep 28, 2014 at 12:45am
Sep 28, 2014 at 1:05am
closed account (48T7M4Gy)
Exactly, that's how it goes. Just as you did, you labouriosly follow the steps as tedious as it is tyo find out what the program is doing at super speed and why it is not doing what you want.

Make sure you get the idea of changing "<=" to just "=". :-)

PS the check of x>5 in the for statement is done before the i++. There's no point in incrementing i if it doesn't satisfy the test. Also if it did i++ first it wouldn't do i =1, it would start at i=2.
Last edited on Sep 28, 2014 at 1:08am
Sep 28, 2014 at 2:35am
PS the check of x>5 in the for statement is done before the i++. There's no point in incrementing i if it doesn't satisfy the test. Also if it did i++ first it wouldn't do i =1, it would start at i=2.


Ahh... I actually did not know that! Thanks
Sep 28, 2014 at 2:46am
closed account (48T7M4Gy)
Does your program do what you want now? :-)
Sep 28, 2014 at 3:04am
lol I hope you aren't talking to me. I'm a different person
Sep 28, 2014 at 4:18am
closed account (48T7M4Gy)
oops
Topic archived. No new replies allowed.