M. Dhiyanesh
PRO
last month
M.country asked

I set a limit in my while loop, but it keeps running way more times than expected. Is the online interpreter bugged, or am I missing something?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

It’s not a bug. Your count never changes, so count <= 3 stays true forever.

Buggy code:

#include 

int main() {
    int count = 1;

    while (count <= 3) {
        printf("I am inside a loop.\n");
        printf("Looping is interesting.\n");
    }

    return 0;
}

Output (repeats forever):

I am inside a loop.
Looping is interesting.
...

Fix:

#include 

int main() {
    int count = 1;

    while (count <= 3) {
        printf("I am inside a loop.\n");
        printf("Looping is interesting.\n");
        count = count + 1;
    }

    return 0;
}

Output:

I am inside a loop.
Looping is interesting.
I am inside a loop.
Looping is interesting.
I am inside a loop.
Looping is interesting.

If you have more questions, I am here to help.

C
This question was asked as part of the Learn C Programming course.