Ask Question
21 January, 11:31

Consider the code fragment below (with nested loops). int sum = 0; for (int i = 1; i < 5; i++) for (int j = 1; j < = i; j++) sum++; StdOut. println (sum); Which one of the following is the value printed by the above code? a. 6b. 7c. 8d. 10e. none of these

+3
Answers (1)
  1. 21 January, 11:44
    0
    Option d is the correct answer for the above question.

    Explanation:

    The first loop of the program has a second loop and then the statement. In this scenario, the second loop executes for the value of the first loop and the statement executes for the value of the second loop. The first loop executes 4 times, Then the second loop or inner loop executes n times for the n iteration of the first loop, for example, 1 time for the first iteration of the first loop, 2 times for the second iteration of the first loop and so on. Then the inner loop executes (1+2+3+4) iteration which gives the result 10 iterations. The sum initial value is 0 and the "sum++", increase the value of the sum by 1. So the value of the sum becomes 10 after completing 10 iterations of the inner for loop. Hence the 10 will be the output. So the Option d is the correct answer while the other is not.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Consider the code fragment below (with nested loops). int sum = 0; for (int i = 1; i < 5; i++) for (int j = 1; j < = i; j++) sum++; StdOut. ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers