Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For Loops in c. Showing Final Result only

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading