954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

I don't understand the logic

hey guys,I'm soo beginner in C++ :$ .could you please explain logic of the loop

#include <iostream>
using namespace std;
int main()
{

int x = 0, p = 5;
while(x < p)
{
for(int i = 0; i < x; i++)
{
cout << "+";
}
cout << "\n";
x++;
}
}


the output will be

+
++
+++
++++
but I couldn't understand this part

for(int i = 0; i < x; i++)


i

zidane010h
Newbie Poster
3 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

The second loop will not execute the first time.Then x will be incremented at line 14 so when the main loop reinitiates, x will be 1 and so on until it reaches five.

caut_baia
Posting Whiz
387 posts since Apr 2010
Reputation Points: 25
Solved Threads: 49
 

It doesn't run for the first turn through. In general, if the condition on a for loop evaluates to false to begin with, the loop is skipped.

In this case, after the for is skipped, x is incremented to 1, the next cycle of the while loop takes place, and that's when you see the '+' signs start printing.

Edit: beaten to the punch on that one

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

thanks all , but how in the third loop it shows ++ and fourth +++ and ...
how cout distaly the ++ signs in the third loop when I don't see anywhere in the codes that how many + signs it should represent ?

zidane010h
Newbie Poster
3 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

Every "+" character gets printed next to the previous one for i times each time x gets increased.

caut_baia
Posting Whiz
387 posts since Apr 2010
Reputation Points: 25
Solved Threads: 49
 

thanks I got it now

zidane010h
Newbie Poster
3 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: