I don't understand how to solve this? And also i don't understand about can we use int j or define j two time in for loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

I don't understand how to solve this? And also i don't understand about can we use int j or define j two time in for loop?

What is the output of this code? int sum = 0; for(int j= 0; j<3; j++) for(int j = 0; j<2; j++) ++sum; cout<<sum;

21st Sep 2017, 6:18 AM
Kumar Amit
Kumar Amit - avatar
3 Answers
+ 6
Actually, the increment happens 6 times so it prints a 6. Despite the fact there are two j's this will compile and run fine. The outer loop executes 3 times each of which cause the inner loop to execute twice. You can't access the outer loop j within the inner loop so it is a poor coding practice. It is allowable due to name overloading capabilities with c++.
21st Sep 2017, 7:06 AM
John Wells
John Wells - avatar
+ 2
If your trying to solve the output of the formula, take it one section at a time. int sum = 0; //Defined integer to hold sum value. for(int j=0; j<3;j++) //This for loop is going to iterate only the next line. for(int j=0;j<2;j++) //This loop will iterate the next line under it two times. ++sum; //This will be iterated 2 times because it's under the second for loop. **Basically, the loop will iterate 2 times (break out of that loop) and add one to the first for loop. Because it broke out of the second loop, j will again be 0 in this loop and iterate another 2 times (at this point sum is 4). The first four loop will add 1 to the first, move to the second for loop again, and add another two. This will make your sum = 6. It will be something like 2+2+2. The answer to your second question, is that it can get confusing: especially if you have multiple for loops. You want clean, easily understood code. This will help yourself in the future understand what you did, and also any other individual that might work on your code in the future. hope that helped!
21st Sep 2017, 7:27 AM
Jared Alwyn
Jared Alwyn - avatar
+ 2
Thanks to increase my some strength....next time tha level of question is high as per myside☺
25th Nov 2017, 7:42 AM
Kumar Amit
Kumar Amit - avatar