Problem Solving using C Language

0 of 77 lessons complete (0%)

Loops

Lab: do-while Loop

Program 1: Display Menu Until User Enters 0

Objective: Show a menu, take input from the user, and continue until the user enters 0.

#include <stdio.h>

int main() {
    int choice;
    
    do {
        printf("Menu:\n");
        printf("1. Option 1\n");
        printf("2. Option 2\n");
        printf("0. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                printf("You selected Option 1\n");
                break;
            case 2:
                printf("You selected Option 2\n");
                break;
            case 0:
                printf("Exiting...\n");
                break;
            default:
                printf("Invalid choice!\n");
        }
    } while (choice != 0);
    
    return 0;
}

Program 2: Reverse a Number

Objective: Reverse the digits of a number using a do-while loop.

#include <stdio.h>

int main() {
    int num, reverse = 0, remainder;
    
    printf("Enter a number: ");
    scanf("%d", &num);
    
    do {
        remainder = num % 10;
        reverse = reverse * 10 + remainder;
        num /= 10;
    } while (num != 0);
    
    printf("Reversed number = %d\n", reverse);
    
    return 0;
}

Program 3: Sum of Even Numbers between 1 and N

Objective: Input a number N and calculate the sum of all even numbers between 1 and N.

#include <stdio.h>

int main() {
    int i = 2, N, sum = 0;
    
    printf("Enter a number: ");
    scanf("%d", &N);
    
    do {
        sum += i;
        i += 2;
    } while (i <= N);
    
    printf("Sum of even numbers between 1 and %d = %d\n", N, sum);
    
    return 0;
}

Program 4: Find Armstrong Number

Objective: Check whether a given number is an Armstrong number.

#include <stdio.h>

int main() {
    int num, originalNum, remainder, result = 0;
    
    printf("Enter a three-digit number: ");
    scanf("%d", &num);
    
    originalNum = num;
    
    do {
        remainder = num % 10;
        result += remainder * remainder * remainder;
        num /= 10;
    } while (num != 0);
    
    if (result == originalNum) {
        printf("%d is an Armstrong number.\n", originalNum);
    } else {
        printf("%d is not an Armstrong number.\n", originalNum);
    }
    
    return 0;
}