Skip to content

C_While_Loop.c

ani9977 edited this page Sep 11, 2024 · 1 revision

Here’s the updated C code with added documentation and an explanation:

#include <stdio.h>

/**
 * @brief The main function demonstrates the use of a while loop in C.
 * 
 * This function uses a while loop to print the value of the integer variable 'i' from 0 to 4.
 * The loop continues until the condition `i < 5` is no longer true.
 * 
 * @return int Returns 0 to indicate successful execution.
 */
int main() {
    int i = 0;  /**< Integer variable initialized to 0. */

    // While loop to print the value of 'i' as long as 'i' is less than 5
    while (i < 5) {
        printf("i: %d\n", i);  /**< Print the current value of 'i'. */
        i++;                   /**< Increment 'i' by 1 after each iteration. */
    }

    return 0;   /**< Return 0 to indicate successful execution. */
}

Explanation

  1. Variable Initialization:

    • int i = 0; declares an integer variable i and initializes it with the value 0.
  2. While Loop:

    • while (i < 5) sets up a loop that will continue executing as long as the condition i < 5 is true.
    • Inside the loop:
      • printf("i: %d\n", i); prints the current value of i.
      • i++; increments the value of i by 1 after each iteration.
  3. Termination:

    • The loop stops when i reaches 5, as i < 5 becomes false.
  4. Return Statement:

    • return 0; indicates that the program has executed successfully. The value 0 is returned to the operating system.

Clone this wiki locally