retagged by
651 views
1 votes
1 votes

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).

 

retagged by

2 Answers

Best answer
2 votes
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 votes
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.

Related questions

122
views
1 answers
1 votes
shivamSK asked Jun 15
122 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; } ... int i = k/2; a[i] = a[i] - 1; } printf ("%d",i+a[i]); }Numerical Answer ______________________________
2.2k
views
2 answers
4 votes
Gangani_Son asked Dec 14, 2018
2,204 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 ... it checks whether a given number is perfect square. Any one can explain output of above program?