Skip to content Skip to main navigation Skip to footer

C Flow Control Statements

c flow control statement

Programs in the C programming language are executed sequentially, i.e., the preceding statements are executed first and then the following ones. Developers who want to control the flow of program execution must use flow-controlled syntactic structures, mainly conditional and loop statements.

If Statement

The if statement is used for conditional evaluation. When the condition matches, the specified statement is executed.

if (expression) statement

In the above statement, the statement is executed when the expression is true (the value is not 0).

The if keyword must be followed by a test condition expression with parentheses outside, otherwise an error will be reported. The body of the statement can be a single statement or a compound statement placed inside curly braces. Here is an example.

if (x == 20) printf("x is 20");

In the above example, a line of text is output when the variable x is 20. For statement bodies with only one statement, the statement section is usually on a separate line.

if (x == 10)
    printf("x is 10\n");

If there are multiple statements, you need to put them in curly brackets to form a compound statement.

if (lines== 100) 
{

    lineNum= 0;
    pageNum++;

}

The if statement can have an else branch that specifies the code to be executed when the condition is false (the value of the expression is 0).

if (expression) statement
else statement

Here is an example.

if (i > j)
    max = i;

else
    max = j;

If the else statement has multiple lines, again, you can put them in curly brackets.

The else keyword can be used in conjunction with another if statement to form multiple conditions.

if (expression)
    statement

else if (expression)
   statement

...

else if (expression)
   statement

else
   statement

If there is more than one if statement and else statement, you can remember the rule that the else statement always matches the closest if statement.

if (number > 10)
    if (number < 20)

        printf("the given number is less than 20 and greater than 10.\n");

    else
        printf("no number found.\n");

  In the above example, the else statement matches the nearest if statement (i.e. number < 20), so if number is equal to or less than 10, the else statement will not be executed.

This is error-prone, and to provide readability of the code, it is recommended to use curly brackets to clarify which if matches the else.

if (number > 10)
{
    if (number < 20) {
            printf("the given number is less than 20 and greater than 10.\n");
    }

} else {
    printf("no number found.\n");
}

In the above example, the use of curly braces clearly shows that the else statement matches the outer if statement.

The ? : Operator

The C language has a conditional expression ? :, which can be used as an if...else as a shorthand format.

<expression1> ? <expression2> : <expression3>

The meaning of this operator is that expression2 is executed if expression1 is true (non-zero value), otherwise expression3 is executed.

The following is an example that returns the greater of two values.

(i > j) ? i : j;

The above code is equivalent to the following if statement.

if (i > j)
    return i;

else
   return j;

switch Statement

The switch statement is a special form of the if...else structure, used to determine conditions with multiple results. It turns multiple else if statements into an easier to use and more readable form.

switch (A) {
    case value1: statement
    case value2: statement
    default: statement
}

In the above code, depending on the value of expression A, the corresponding case branch is executed. If the corresponding value is not found, the default branch is executed.

Below is an example.

switch (grade) {
    case 'A':
        printf("Excellent");
        break;
    case 'B':
        printf("Well Done");
        break;
    default:
        printf("Invalid grade");
}

In the above example, different case branches are executed depending on the value of the variable grade.  If it is equal to 'A', the case 'A' is executed; if it is equal to 'B', the case 'B' is executed; otherwise, the case 'default' is executed.

At the end of each case statement body, there should be a break statement, which serves to jump out of the entire switch structure and not continue execution. The absence of a break statement will cause execution to continue to the next case or default branch.

switch (grade) {
    case 'A':
        printf("Excellent");
    case 'B':
        printf("Well Done");
        break;
    default:
        printf("Invalid grade");
}

In the above example, there is no break statement in the case 'A' part, so after this branch is executed, it will not jump out of the switch structure and continue to execute the case 'B' branch.

Using this feature, if multiple case branches correspond to the same statement body, they can be written like the following.

switch (grade) {
    case 'A':
    case 'B':
        printf("Well Done");
        break;
    default:
        printf("Invalid grade");
}

In the above example, the case 'A' branch does not have any statements, resulting in the same statement body being executed for both case 'A' and case 'B'.

The default branch is used to handle cases where all previous cases do not match, and is best placed after all cases so that you don’t have to write a break statement. This branch is optional; without it, the entire switch block will be skipped if all cases do not match.

while Statement

The while statement is used in a loop structure to keep executing the loop body when the given condition is true.

while (A)
    B

In the above code, if the expression A is a non-zero value (indicating true), the B statement will be executed, and then it will be determined again whether A is zero; if A is zero (indicating false), the loop will be jumped out and the loop body will no longer be executed.

while (i < n)
    i = i + 2;

In the above example, i keeps increasing by 2 as long as the i variable is less than n.

If the loop body has more than one statement, you need to use curly brackets to group these statements together.

while (expression) {
    statement;
    statement;
}

Here is an example.

i = 0;
while (i < 10) {

    printf("i is now %d!\n", i);
    i++;
}

printf("All done!\n");

In the code above, the loop executes 10 times, each time increasing i by 1 until it equals 10 before exiting the loop.

While produces an infinite loop as long as the condition is true. Here is a common way to write an infinite loop.

while (1) {
  // ...
}

The above example is an infinite loop, but the loop body can be jumped out of the loop with a break statement.

do…while Statement

do...while statement is a variation of the while statement that executes the loop once and then determines if the condition is met. If the condition is met, it continues to execute the loop body, otherwise it jumps out of the loop.

do A_statement
while (B_expression);

In the above code, the body of the loop statement is executed at least once, regardless of whether the condition B_expression is true or not. Each time A_statement finishes executing, it will evaluate B_expression once and decide whether to end the loop.

i = 10;
do --i;
while (i > 0);

In the above example, the variable i is first subtracted by 1, then it is determined if it is greater than 0. If it is greater than 0, it continues to be subtracted by 1 until variable i equals 0.

If there are multiple statements in the loop section, they need to be enclosed in curly brackets.

i = 10;

do {

  printf("i is %d\n", i);

  i++;

} while (i < 10);

printf("All done!\n");

In the above example, the variable i does not meet the condition of being less than 10, but the loop body is still executed once.

for Statement

The for statement is the most commonly used loop structure and is usually used to precisely control the number of loops.

for (initialization; continuation; action)

  statement;

In the above code, the conditional part of the for statement (i.e., the part inside the parentheses) has three expressions.

  • initialization: the initialization expression, which is used to initialize the loop variables and is executed only once.
  • continuation: a test expression that keeps executing the loop body as long as it is true.
  • action: loop variable handling expression, which is executed at the end of each round of the loop and causes the loop variable to change.

The statement in the body of the loop can be a single statement or a compound statement placed inside curly brackets. Here is an example.

for (int i = 10; i > 0; i--)
    printf("i is %d\n", i);

In the above example, the loop variable i is declared inside the first expression of the for statement, and this variable is used only for this loop. It expires after it leaves the loop body.

Each of the three expressions in the conditional section can have multiple statements, with the statements separated by commas.

int i, j;

for (i = 0, j = 999; i < 10; i++, j--) {

  printf("%d, %d\n", i, j);

}

In the above example, the initialization section has two statements that assign values to variables i and j, respectively.

None of the three expressions of the for statement are needed, or even all of them could be omitted, which would form an infinite loop.

for (;;) {

  printf("loop print\n" );

}

The above example creates an infinite loop because there is no test condition.

break Statement

The break statement has two purposes. One is used in combination with a switch statement to break the execution of a branch, as already explained. The other use is to jump out of the loop inside the loop body without going to the next loop.

for (int i = 0; i < 3; i++) {

  for (int j = 0; j < 3; j++) {

    printf("%d, %d\n", i, j);

    break;

  }

}

In the above example, the break statement causes the loop to jump out of the current loop statement.

while ((ch = getchar()) != EOF) {

    if (ch == '\n') break;
    putchar(ch);
}

In the above example, once the newline character (\n) is read, the break command jumps out of the entire while loop and does not continue reading.

if (n > 1) {

  if (n > 2) break; // invalid

  printf("hello\n");

}

Note: The break command can only jump out of the loop body and switch structure, not the if structure.

continue Statement

The continue statement is used to terminate the current loop inside the loop body and move on to the next loop. Whenever a continue statement is encountered, the subsequent statement inside the loop body is not executed, but returns to the head of the loop body and starts the next round of execution.

for (int i = 0; i < 3; i++) {

    for (int j = 0; j < 3; j++) {

        printf("%d, %d\n", i, j);

        continue;
  }
}

In the above example, there is no continue statement, the effect is the same, both jump to the next j.

while ((ch = getchar()) != '\n') {

    if (ch == '\t') continue;

    putchar(ch);

}

In the above example, whenever the character read is a tab (\t), use the continue statement to skip that character and read the next character.

goto Statement

The goto statement is used to jump to the specified tag name. This can break structured programming and is not recommended. The following is a description of its usage for syntactic completeness.

char ch;

top: ch = getchar();
if (ch == 'q')
    goto top;

In the above example, top is a tag name that can be placed in front of the normal statement, equivalent to the tag of this line. When the program executes to the goto statement, it will jump to the tag name it specifies.

Note: The goto statement can only jump within the same function and cannot jump to other functions.

Was This Article Helpful?

2
Related Articles
0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.