Why this loop runs only once?

Debojit Acharjee 435 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.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,851 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,602 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,625 questions
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