The ‘do’ Keyword in C Programming: Loops and Examples

C Programming @ Freshers.in

In C programming, the ‘do’ keyword is an essential component of ‘do-while’ loops. This article provides a comprehensive explanation of the ‘do’ keyword, its role in loop construction, and includes real-world examples to illustrate its significance in creating versatile and efficient loops.

Understanding the ‘do’ Keyword

The ‘do’ keyword in C is used to initiate a ‘do-while’ loop, which is a type of loop that guarantees the execution of the loop body at least once, regardless of the condition. ‘do-while’ loops are particularly useful when you need to ensure that a block of code is executed before checking the loop condition.

Syntax for ‘do-while’ Loop:

do {
    // Code inside the loop body
} while (condition);

Example 1: Using ‘do’ in a ‘do-while’ Loop

#include <stdio.h>
int main() {
    int i = 1;
    do {
        printf("%d ", i);
        i++;
    } while (i <= 5);
    return 0;
}

Output:

1 2 3 4 5

In this example, the ‘do-while’ loop is used to print the values of i from 1 to 5. The loop body is executed first, and then the condition i <= 5 is checked. Because the condition is true, the loop continues to execute until the condition becomes false.

Use Cases for ‘do’ and ‘do-while’ Loops

  1. Input Validation: ‘do-while’ loops are suitable for input validation, ensuring that user input meets certain criteria before proceeding.
  2. Menu-Driven Programs: They are useful in menu-driven programs where the menu should be displayed at least once, and the user can choose to continue or exit.

Example 2: Input Validation using ‘do-while’ Loop

#include <stdio.h>
int main() {
    int number;
    do {
        printf("Enter a positive number: ");
        scanf("%d", &number);
    } while (number <= 0);
    printf("You entered a positive number: %d\n", number);
    return 0;
}

In this example, the ‘do-while’ loop ensures that the user enters a positive number. The loop continues to prompt the user until a positive number is provided.

Author: user