CSE NotesCSE Notes
Simplifying Complexity

While

In C, the while loop is used for repeating a block of code as long as a specified condition is true.

Syntax

while (condition) {
// code to be executed
}

Example

Here’s a simple example that counts from 0 to 4:

#include <stdio.h>

int main() {
int count = 0;

while (count < 5) {
printf(“%d\n”, count);
count++;
}

return 0;
}

Explanation

  1. Initialization: The variable count is initialized to 0.
  2. Condition Check: The while loop checks if count is less than 5.
  3. Code Execution: If the condition is true, it prints the value of count and increments it by 1.
  4. Repeat: The loop continues until the condition is false (i.e., count reaches 5).

Important Notes

  • If the condition is false from the start, the code block will not execute at all.
  • Be careful to modify the loop variable within the loop to avoid infinite loops.

do-While

In C, the do while loop is similar to the while loop, but it guarantees that the block of code will execute at least once, regardless of whether the condition is true or false. The condition is checked after the code block is executed.

Syntax

do {
// code to be executed
} while (condition);

Example

Here’s a simple example that counts from 0 to 4 using a do while loop:

#include <stdio.h>

int main() {
int count = 0;

do {
printf(“%d\n”, count);
count++;
} while (count < 5);

return 0;
}

Explanation

  1. Initialization: The variable count is initialized to 0.
  2. Code Execution: The do block executes first, printing the value of count and incrementing it by 1.
  3. Condition Check: After executing the block, the loop checks if count is less than 5.
  4. Repeat: If the condition is true, the loop will execute again. If false, it will exit.

Important Notes

  • The do while loop is particularly useful when you need the code to run at least once, such as in menu-driven programs where you want to show a menu at least once to the user.
  • Ensure that the loop variable is modified within the loop to prevent infinite loops.

Example: Menu with Exit Option

#include <stdio.h>

int main() {
int choice;

do {
// Display the menu
printf(“Menu:\n”);
printf(“1. Option 1\n”);
printf(“2. Option 2\n”);
printf(“3. Exit\n”);
printf(“Enter your choice: “);
scanf(“%d”, &choice);

// Execute actions based on the choice
switch (choice) {
case 1:
printf(“You selected Option 1.\n”);
break;
case 2:
printf(“You selected Option 2.\n”);
break;
case 3:
printf(“Exiting the program.\n”);
break;
default:
printf(“Invalid choice. Please try again.\n”);
}
} while (choice != 3); // Continue until the user chooses to exit

return 0;
}