Home > Software engineering >  Why is the output for x=5 not 2 3 4 5 6
Why is the output for x=5 not 2 3 4 5 6

Time:01-08

int x;
printf("enter number >");
scanf("%d",&x);
for(int i=1;i<=x;i  )
{
i=i 1;                          
printf("%d ",i);
}

Doesn't it operate like this in C language? for x=5

i=1 2=1 1

i=2 3=2 1

i=3 4=3 1 i=4 5=4 1

i=5 6=5 1 output should be 2 3 4 5 6 then but the output is 2 4 6 why ?

CodePudding user response:

i increments the variable i to fix your code

int x;
printf("enter number >");
scanf("%d",&x);
for(int i=1;i<=x;)
{
   i  ;
   printf("%d ",i);
}

CodePudding user response:

for(int i=1;i<=x;i  )
{
i=i 1; /* This statement increments i, now i = 2 */
printf("%d ",i); /* This, then prints 2. 
}

The third part of the for loop then increments i again.

On the second iteration, i = i 1 increments i to 4.... and so on.

Remove this statement from your code:

i = i   1;

And then it should work as expected.

CodePudding user response:

You are increasing the value of 'i' two times per iteration:

  • first time inside the code block of the loop;
  • second time the already increased value is being incremented as last step of the loop (i );

So, if x=5, here what's happening:

first iteration:

i = 1

Loop enters it's body, where: i = i 1 = 1 1 = 2

printf prints the current value of 'i' which is 2, and then loop goes to incrementation step:

i  ;

there you additionally increment the value of 'i' wit 1 (via postfix operator for incrementation), so:

i   = i 1 = 2 1 = 3
i = 3;

Then the loop goes back to the condition check, to see if 'i' is still <= 5. 3<=5 = true, so the loop will execute it's code block once more:

second interation:

i = 3;

Loop enters it's body, where:

i = i   1 = 3 1 = 4

printf prints the current value of 'i' which is 4, and then loop goes to incrementation step:

i   = i 1 = 4 1 = 5
i = 5;

Then the loop goes back to the condition check, to see if i is still <= 5. 5<=5 = true, so the loop will execute it's code block once more:

Third interation:

i = 5;

Loop enters it's body, where:

i = i   1 = 5 1 = 6

printf prints the current value of 'i' which is 6, and then loop goes to incrementation step:

i   = i 1 = 6 1 = 7
i = 7;

Then the loop goes back to the condition check, to see if 'i' is still <= 5. 7<=5 = false, so loop will end it's execution and program will proceed forward with next instructions.

  • Related