Home > Back-end >  For Loops in c. Showing Final Result only
For Loops in c. Showing Final Result only

Time:09-01

I wrote a simple C Program =>

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, i;

    printf("Enter a Number: ");
    scanf("%d", &num);

    for (i = 1; i <= num; i  );
    printf("%d", i);

    return 0;
}

But I am getting OUTPUT as 6. why isn't it is printing command I gave in each iteration. it is Printing final results.

CodePudding user response:

for (i = 1; i <= num; i  );
                          ^

Here you have accidentally left a semicolon at the end of the for loop. The for loop effectively does nothing aside from incrementing i. By removing the semicolon, the for loop would work as expected. Additionally I recommend always using brackets on for loops or any construct that allows you to skip brackets (if, while, etc) for one-liners.

  •  Tags:  
  • c
  • Related