Simple c programming

vivekgupta's Avatar, Join Date: Jun 2012
Light Poster
Given two programmes are same ???

if yes then try both with these inputs 4 2 3 -1 4 -1 -2 4
i am getting different answers :/

don't know why??
plz help
Code:
#include<stdio.h>
 int main()
 {
 int x,i=1,sum=0;
 /*printf("no. of numbers");*/
 /*scanf("%d",&n);*/
 for(i=0;i<5;i++)
 {
 printf("enter the values");
 scanf("%d",&x);
 if(x<0)
 {
 continue;
 }
 sum+=x;

 }
 printf("%d",sum);
 }

----------------------------------------------------------------------------------------------------------------


#include<stdio.h>
 int main()
 {
 int x,i=1,sum=0;
 /*printf("no. of numbers");*/
 /*scanf("%d",&n);*/
 for(i=0;i<5;)
 {
 printf("enter the values");
 scanf("%d",&x);
 if(x<0)
 {
 continue;
 }
 sum+=x;
i+=1;
 }
 printf("%d",sum);
 }

Last edited by shabbir; 26Oct2012 at 10:30.. Reason: Code blocks
vivekgupta's Avatar, Join Date: Jun 2012
Light Poster
here = ; )
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
They are not the same. In one, the for loop is:
Code:
for(i=0;i<5;i++)
{
...
  continue; // clearly you don't understand what this statement does
...
}
and in the other it is:
Code:
for(i=0;i<5;)
{
...
  continue; // clearly you don't understand what this statement does
...
i+=1;
}
Go and RTFM on "continue" and you will see why the programs behave differently.
Rajesh M. Kanojia's Avatar, Join Date: Dec 2012
Go4Expert Member
continue keyword is used to send the control back to the loop without executing remaing code.
now comes to ur problem:-
when u enter any -ve number then only continue statement get execute.
in ur program increment of variable i is also play a important role how:-
in ur first program i value get incremented as contol come back to the loop that's why u get answer 13
but in second program the value of i will incremented only when if condition get false.

try one more thing enter all number -ve u find that every time u get a message on console
Enter the value:-
the reason is i value doesn't change.
smp's Avatar, Join Date: Jul 2012
smp
Go4Expert Member
The only problem here is 'continue' statement. In your code, calling the 'continue' statement will result the execution to go back to the for loop for the next iteration. In the first case, calling the continue statement returns to the 'for' loop in which the value of 'i' is incremented. In the latter case the value of i is incremented after the continue statement. So if the continue statement is called in the second program, then the pointer returns to for loop without incrementing the value of i which makes the programs differ.

In first case, even if continue statement is called, value of i increases.
In second case, if continue statement is called, value of i remains the same.
iranjit's Avatar, Join Date: Jan 2013
Newbie Member
When continue statement is executed, i+=1; is not executed in the second program. That's why you are getting different result.