boomchickawawa
boomchickawawa

Reputation: 556

C language for loop iteration

I have started learning the C language and I am trying out various codes and experimenting with it. I have written the below code and expected the output to be 6, but the output is 13. Can someone please explain the logic behind this? Thanks

#include <stdio.h>

void main() {
    int i;

    for (i = 0; i <= 3; i++) {
        i = i + 1;
        printf("%d", i);
    }
}

Upvotes: 2

Views: 239

Answers (4)

Rohit Potter
Rohit Potter

Reputation: 145

The answer will never be 6.

If you want to get answer 6, printf should be outside the loop.

And the loop will be

for(i=0;i<=3;i++)
{
  a=a+i;
}

You have to print a for the answer.

Explanation of your program

Firstly 1 will print because i=0 and then the value of i is increased by 1 two times(1. in the loop condition. 2. in the loop's statement), therefore i will be 2. So the next output is 3, then again i is increased by 1 two times and then i=4 and the loop will stop.

So the output of this program is 13.

Upvotes: 1

Joy Allen
Joy Allen

Reputation: 402

It is not '13' at all, it is '1' and '3'.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    for (i = 0; i <= 3; i++)
    {
        i = i + 1;
        //printf("%d", i);
        printf("i = %d\n", i);
    }

    return 0;
}

The output of the code is:

i = 1
i = 3

If you remove "i = ", and combine two lines, it just is a char '1' and '3'.

Please read the code in detail. If you are still confused, maybe nobody can help you.

Upvotes: 2

mlibby
mlibby

Reputation: 6724

It is printing a 1, then a 3.

The first time through the loop i is set to 0. Then you add one to it and print that out.

Then the loop increments i to 2 (i++). Then you add one to that (i = 3) and print it out.

Then the loop increments i to 4 and tests for i <= 3 and quits because the condition is no longer true.

Upvotes: 2

pm100
pm100

Reputation: 50110

I think you are trying to sum 1,2,3. Your problem is that you are using i as both the loop index and as the total. Also you add 1 too, dont know why

You need

#include <stdio.h>
void main()
{
  int sum = 0;
  for(i=0;i<=3;i++)
  {
    sum = sum +i;
  }
  printf("%d\n",sum);
}

Upvotes: 1

Related Questions