C Programming

Unit 5: Control Statements

Branching, looping, exit, break, continue, and goto statements in C.

Branching statements

Branching statements transfer the flow of execution based on a condition.

if statement

if (condition)
{
    /* executes when condition is true */
}
int n = 5;
if (n > 0)
    printf("Positive number\n");

if-else statement

if (condition)
    statement1;
else
    statement2;
int n = -3;
if (n >= 0)
    printf("Non-negative\n");
else
    printf("Negative\n");

if-else-if ladder

int marks = 75;
if (marks >= 80)
    printf("A\n");
else if (marks >= 60)
    printf("B\n");
else if (marks >= 40)
    printf("C\n");
else
    printf("Fail\n");

Nested if

if (a > 0) {
    if (a % 2 == 0)
        printf("Positive even\n");
    else
        printf("Positive odd\n");
}

switch statement

The switch statement allows multi-way branching based on the value of an integer or character expression.

#include <stdio.h>

int main(void)
{
    int day = 3;
    switch (day) {
        case 1: printf("Sunday\n");    break;
        case 2: printf("Monday\n");    break;
        case 3: printf("Tuesday\n");   break;
        default: printf("Other day\n"); break;
    }
    return 0;
}

Looping statements

Looping statements repeat a block of code as long as a condition is true.

for loop

for (initialization; condition; update)
{
    /* loop body */
}
for (int i = 1; i <= 5; i++)
    printf("%d ", i);   /* 1 2 3 4 5 */

while loop

int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}

do-while loop

The loop body is executed at least once because the condition is checked after the body.

int i = 1;
do {
    printf("%d ", i);
    i++;
} while (i <= 5);

Exit function

The exit() function terminates a program immediately. It is declared in <stdlib.h>.

  • exit(0) indicates successful termination.
  • exit(1) (or any non-zero value) indicates abnormal termination.
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n;
    printf("Enter a positive number: ");
    scanf("%d", &n);

    if (n < 0) {
        printf("Invalid input\n");
        exit(1);
    }

    printf("You entered %d\n", n);
    return 0;
}

break statement

The break statement terminates the nearest enclosing loop or switch block.

for (int i = 1; i <= 10; i++) {
    if (i == 5) break;
    printf("%d ", i);     /* 1 2 3 4 */
}

continue statement

The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration of the loop.

for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    printf("%d ", i);     /* 1 2 4 5 */
}

goto statement

The goto statement transfers control to a labeled statement within the same function.

#include <stdio.h>

int main(void)
{
    int n;
    printf("Enter a positive number: ");
    scanf("%d", &n);

    if (n < 0)
        goto error;

    printf("Square = %d\n", n * n);
    return 0;

error:
    printf("Negative number is not allowed.\n");
    return 1;
}