//Can any one solve this with explaination ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 ?

30th May 2017, 10:36 AM
Enas Emad
Enas Emad - avatar
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.
30th May 2017, 11:45 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
yes it is correct but I need explaination , I tried to understand the output , but it somewhat confusing
30th May 2017, 10:42 AM
Enas Emad
Enas Emad - avatar
+ 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.
30th May 2017, 10:50 AM
Glozi30
Glozi30 - avatar
+ 4
@Glozi30 . thank you for your explaination .
30th May 2017, 10:59 AM
Enas Emad
Enas Emad - avatar
+ 4
@sabrina , thank you so much .
30th May 2017, 11:18 AM
Enas Emad
Enas Emad - avatar
+ 4
that's the half of the output .nice try : ]
31st May 2017, 5:06 AM
Enas Emad
Enas Emad - avatar
+ 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
30th May 2017, 11:10 AM
Sabrina Aviles
+ 2
I run your code, here is the output: *_**_ Is it correct?
30th May 2017, 10:40 AM
Sabrina Aviles
+ 1
// Output *_
31st May 2017, 2:43 AM
BaNaNa
BaNaNa - avatar
0
I also ran your code and got the same result as the top results, my one question is why?
3rd Jun 2017, 8:32 AM
S3T_N4ME
S3T_N4ME - avatar