How many times is the comparison i >= n performed in the following program?int i = 300, n = 150;main(){ while (i >= n){ i = i-2; n = n+1; }}
Question
How many times is the comparison i >= n performed in the following program?int i = 300, n = 150;main(){ while (i >= n){ i = i-2; n = n+1; }}
Solution
The comparison i >= n is performed in each iteration of the while loop. The loop continues as long as i is greater than or equal to n.
Initially, i is 300 and n is 150. In each iteration of the loop, i is decreased by 2 and n is increased by 1.
So, the loop will continue until i is less than n.
To find out how many times the comparison is performed, we need to calculate the number of iterations.
The difference between i and n is 150. In each iteration, this difference is decreased by 3 (because i is decreased by 2 and n is increased by 1).
So, the number of iterations is 150 / 3 = 50.
Therefore, the comparison i >= n is performed 50 times.
Similar Questions
How many times i value is checked in the following C program? #include <stdio.h> int main() { int i = 0; while (i < 3) i++; printf("In while loop\n"); }4321
The time complexity of the following code snippet isc=0; while (n>=1) {for(i=1;i<=n;i++){ c++;}n=n/2;}
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
What is the time complexity of the following code : int a = 0, i = N; while (i > 0) { a += i; i /= 2; }
How many times will the loop run?i=2while(i>0): i=i-1
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.