• edited by
974 views
1 1 vote

In the picture below:

Can anyone explain to me why ‘while’ loop starting from 2 but in the case of ‘for’ loop it is starting from 1 (although i++ is available for both in Program 1 and Program 2) and also in the case of ‘while’ loop the outputs are different in Program 1 and Program 3  but in case of ‘for’ loop the outputs are same although in Program 2 it is post increment (i++) and in Program 4 it is pre increment (++i).

 

2 Answers

Best answer
2 2 votes
In for loop, ++i or i++ is executed after entire loop body is executed. After ++i/i++,  condition is checked if it is true it will execute the loop body else will exit the loop. So it won’t make any diff in program 2 and 4.

But in case of while ++i/i++ is done in the condition itself, so it will follow the pre increment (++i) and post increment (i++)/

Pre increment – ++i → i value will be incremented first then will be used in the expression. So in program 3 it will iterate from 2 to 10 and values printed will be 2 to 10.

Post increment – ++ → i value will be used in the expression then it will be incremented. So in program 4 it will iterate from 1 to 10 but values printed will be 2 to 11.
• selected by
0 0 votes
The property of for loop is that it will execute the i++ part after the execution of the body. But in the while loop i++ part is executing before the body. That’s why you are getting these output.
Position:
Show:

Related questions

2 2 votes
1 1 answer
811
811 views
shivamSK asked Jun 15, 2024
811 views
#include <stdio.h int main () { int i, k; int a [8] = {33,34,35,36,37,40,50,38}; for(i = 0; i < 3; i++) { a[i] = a[i] + 1; i=i+1; } i=i-1; for (k = 7; k 4; k ) { int i =...
4 4 votes
2 answers 2 answers
3.1k
3.1k views
Gangani_Son asked Dec 14, 2018
3,137 views
What is the return value of following function for 484? What does it to in general?bool fun(int n){ int sum = 0; for (int odd = 1; n sum; odd = odd+2) sum = ...
12 12 votes
1 1 answer
371
371 views
GO Classes asked Jun 3
371 views
What is the output of the following code?#include <stdio.h int main() { int i, j, sum = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { if (j == i) continue; if ...