How many times will the following loop execute? What will be the final value?int a=1,x=0;do{x=a++ *a,}while(a<=5),System out.println(x);}
Question
How many times will the following loop execute? What will be the final value?int a=1,x=0;do{x=a++ *a,}while(a<=5),System out.println(x);}
Solution
The loop will execute 5 times. Here's how it works:
- Initially,
ais 1 andxis 0. - In the first iteration,
xis assigned the value ofa(which is 1) timesa(which is incremented to 2 after the multiplication). So,xbecomes 1*2 = 2. - In the second iteration,
ais 2 and it's incremented to 3 after the multiplication. So,xbecomes 2*3 = 6. - In the third iteration,
ais 3 and it's incremented to 4 after the multiplication. So,xbecomes 3*4 = 12. - In the fourth iteration,
ais 4 and it's incremented to 5 after the multiplication. So,xbecomes 4*5 = 20. - In the fifth iteration,
ais 5 and it's incremented to 6 after the multiplication. So,xbecomes 5*6 = 30.
After the fifth iteration, a is 6 which is more than 5, so the loop condition a<=5 is not satisfied and the loop stops executing.
Therefore, the loop executes 5 times and the final value of x is 30.
Similar Questions
How many times will the following code print "Welcome to Instacks"?int count = 0;do { System.out.println("Welcome to Instacks"); count++;} while (count < 10);891011
In the following program, how many times will the for loop execute?#include<stdio.h> int main() { int i=5; for(;scanf("%d", &i); printf("%d", i)); return 0; }Select one:The for loop will execute only onceThe for loop will execute infinite timesThe for loop will not execute at allThe for loop will execute 5 times
Consider the program below: public static void main(String[] args) { int numThings = 0; for (int i = 0; i <= 10; i+=3) { numThings++; } }How many times does the body of the for loop run? 9 10 Correct! 4 0
What is the output of the following code snippet?int i = 0;do { if (i == 3) continue; System.out.print(i + " "); i++;} while (i < 5);
How many times following loop will be executed?void main(){ int i = 32766; while (i<= 32767) { printf("%d\n",i); i = i + 1; }}a.2 timesb.1 timesc.infinite timesd.loop will not be executed
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.