+ 5
//Can any one solve this with explaination ?
for(int i=1; i<=2; i++){ for(int j=1; j<=i; j++ ){ cout<<"*"; } cout<<"_"; } //what is the output ?
10 Answers
+ 7
*_**_
If I'm not mistaken. Outer loop runs twice, in which the first loop causes the inner loop to run once, and the second loop causes the inner loop to run twice.
+ 5
yes it is correct but I need explaination , I tried to understand the output , but it somewhat confusing
+ 4
iteration 1 :
i=1 (1 <= 2)
you enter the 2nd for loop :
j=1 <= i=1
so you print one time *
then you print _
iteration 2:
i=2 (2<=2)
you enter the 2nd for loop
j=1 <= i=2
so you print * two times
then you print _
there is no iteration 3 :
i=3 > 2 so you go out of the loop.
When you don't understand a code (not too long) do it manually with a paper and a pencil.
+ 4
@Glozi30 . thank you for your explaination .
+ 4
@sabrina , thank you so much .
+ 4
that's the half of the output .nice try : ]
+ 3
First it will run the first for loop where the value of i is 1 (based on the for loo int i=1), what it says is it will go to the next for loop which it will print *.
The next for loop says that j=1; j<=i (which i means 1) so it will only print 1 * and not continue the loop because if it increments j will become 2 which is not intended to execute because 2 is greater than 1 (where j must be <=1). Then it will to the next process which is the printing of _.
(We have now printed *_)
then it will loop again because the first loop is i<=2. From i=1, it will increment to 2. Still executing because 2 is ok from i<=2. We have now i = 2. Then we go to the next process.
The next process is the for loop where i = 2. First the value of j is 1, that's why it printed *. Then j will be incremented, it will become 2. It is still true because we now have i = 2. Since it's true, it printed another *. That's why there's two *. Then we head to the next process which is printing of _.
We now have, *_**_
Why did it stop? Because if i=2 incremented, it will be i=3 which is false on the first loop statement which is i<=2.
Thank you, bow. HAHA
+ 2
I run your code, here is the output:
*_**_
Is it correct?
+ 1
// Output
*_
0
I also ran your code and got the same result as the top results, my one question is why?