About This Project
This interactive showcase demonstrates 5 programs using while loops and 5 programs using do-while loops in C programming language.
Each program includes the complete source code, a brief explanation, and an interactive runner to test the code.
While everyone else is submitting PDFs, I wanted to create something unique and advanced using HTML, CSS, Tailwind CSS, and JavaScript to present my assignment in an interactive format.
While Loop Programs
1. Sum of Natural Numbers
This program calculates the sum of the first N natural numbers using a while loop.
#include <stdio.h>
int main() {
int n, sum = 0, i = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
while (i <= n) {
sum += i;
i++;
}
printf("Sum of first %d natural numbers = %d\n", n, sum);
return 0;
}
Do-While Loop Programs
1. Menu-Driven Calculator
This program implements a simple calculator with a menu using a do-while loop.
#include <stdio.h>
int main() {
int choice;
float num1, num2, result;
do {
printf("\nCalculator Menu:\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice >= 1 && choice <= 4) {
printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);
}
switch (choice) {
case 1:
result = num1 + num2;
printf("Result: %.2f\n", result);
break;
case 2:
result = num1 - num2;
printf("Result: %.2f\n", result);
break;
case 3:
result = num1 * num2;
printf("Result: %.2f\n", result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.2f\n", result);
} else {
printf("Error: Division by zero!\n");
}
break;
case 5:
printf("Exiting calculator. Goodbye!\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 5);
return 0;
}
This program simulates a calculator. Run it and follow the prompts in the output area.
Key Differences Between While and Do-While Loops
While Loop
- Condition is checked before the loop body executes
- If the condition is false initially, the loop body never executes
- Syntax:
while (condition) { ... } - Use when you need to check the condition before executing the loop body
Do-While Loop
- Loop body executes at least once before condition is checked
- Condition is checked after the loop body executes
- Syntax:
do { ... } while (condition); - Use when you need the loop body to execute at least once