C (programming language)

C Program to Print Numbers Till 5 using do-while Loop

Understanding the do-while Loop

  • Exit-controlled loop: The do-while loop first executes the code block within the loop, and then checks the condition.
  • Guaranteed execution: This means the code block will always execute at least once, even if the condition is initially false.

Code Structure and Explanation

C

#include <stdio.h>

int main() {
    int i = 1;  // Initialize the counter variable

    do {
        printf("%d ", i);  // Print the current value of i
        i++;  // Increment the counter for the next iteration
    } while (i <= 5);  // Check the condition (loop continues if i is less than or equal to 5)

    return 0;
}

Explanation:

  1. Header Inclusion: #include <stdio.h> provides input/output functions like printf.
  2. Main Function: The program execution begins in the main function.
  3. Variable Declaration: int i = 1; declares and initializes the counter variable i to 1.
  4. do-while Loop:
    • The do block executes first, printing the current value of i and then incrementing it.
    • The while condition i <= 5 checks if i is still within the range (less than or equal to 5).
    • If the condition is true, the loop repeats, printing the next number.
  5. Loop Termination: The loop continues as long as i is less than or equal to 5. Once i becomes 6, the condition becomes false and the loop terminates.
  6. Return Statement: return 0; indicates successful program termination.

Output:

1 2 3 4 5

Key Points:

  • The do-while loop is useful when you need the code block to execute at least once, regardless of the condition.
  • The condition is checked at the end of the loop, ensuring at least one iteration.
  • Other loop types like for and while may be more suitable in different scenarios, depending on the specific requirements.

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button