Why this loop runs only once?

Debojit Acharjee 455 Reputation points
2023-05-27T12:43:39.77+00:00

I have used the continue and break statements using the if condition inside a for loop. And the condition is to print the variables only when the loop iteration is less than 5.

#include <stdio.h>

int main()
{
    int i;

    for (i=0;i<10;i++)
    {
        if (i<5)
        {
            continue;
        }
        
        if (i>5)
        {
            break;
        }
        
        printf("%d is less than 5\n", i);
    }
   
    return 0;
}

Why this program prints only once but it should print 5 times.

Developer technologies C++
Developer technologies Visual Studio Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Dr. Volker Milbrandt 80 Reputation points
    2023-05-27T12:59:03.1933333+00:00

    For i<5 your continue jumps to the next iteration before the print.
    For i>5, i.e. i==6, you'll exit the loop.
    Thus only for i==5 the print statement will be executed.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.