Mastering Loops in C and C++: 20 Solved Practice Problems (Lab 3)

Lab 3 – Programming Practice

C Programming – 10 Unique Tasks

C Task 1: Rocket Launch Countdown Timer

Question: Write a C program that simulates a space rocket launch countdown. Prompt the user to enter a starting countdown time in seconds (integer N). Use an entry-controlled while loop to count down from N to 1, displaying each second followed by an ellipsis. After the loop finishes, print “Liftoff!”.

Solution:

#include <stdio.h>

int main() {
    int seconds;

    printf("Enter starting countdown time (seconds): ");
    scanf("%d", &seconds);

    printf("
=== ROCKET LAUNCH COUNTDOWN ===
");
    while (seconds > 0) {
        printf("T-minus %d second(s)...
", seconds);
        seconds--;
    }

    printf("LIFTOFF! Rocket launched successfully.
");

    return 0;
}

Concept Explanation:

This beginner program demonstrates the entry-controlled while loop from Lab 3. It checks the condition (seconds > 0) prior to each iteration, executing the countdown body and decrementing the timer variable until the condition evaluates to false.

C Task 2: Sum of First N Natural Numbers

Question: Write a C program that calculates the sum of the first N positive natural integers. Prompt the user for an integer N. Use a for loop to iterate from 1 to N, accumulating the running sum into a dedicated total variable, and display the final sum.

Solution:

#include <stdio.h>

int main() {
    int n, sum = 0;

    printf("Enter a positive integer (N): ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        sum += i;
    }

    printf("
Sum of first %d natural numbers = %d
", n, sum);

    return 0;
}

Concept Explanation:

This beginner task practices fixed-iteration count for loops and running sum accumulators as taught in Lab 3. The loop counter variable i steps from 1 to N, adding each sequential integer to the sum accumulator variable.

C Task 3: Print Even Numbers in a Range

Question: Write a C program that outputs all even numbers between a starting bound and an ending bound. Prompt the user for start and end integer values. Use a for loop to iterate through the range and print only numbers that are divisible by 2.

Solution:

#include <stdio.h>

int main() {
    int start, end;

    printf("Enter starting integer bound: ");
    scanf("%d", &start);

    printf("Enter ending integer bound: ");
    scanf("%d", &end);

    printf("
Even numbers between %d and %d:
", start, end);
    for (int i = start; i <= end; i++) {
        if (i % 2 == 0) {
            printf("%d ", i);
        }
    }
    printf("
");

    return 0;
}

Concept Explanation:

This beginner program combines a for loop with an internal conditional modulo check (% 2 == 0) from Lab 3 concepts. It traverses a bounded numerical sequence and filters even numbers for console display.

C Task 4: Student Grade Input Validator

Question: Write a C program that enforces input validation for student grades. Use an exit-controlled do-while loop to repeatedly prompt the user to enter a test score between 0 and 100. If the entered value is out of bounds, display an error message and continue asking until valid input is received.

Solution:

#include <stdio.h>

int main() {
    int grade;

    do {
        printf("Enter valid student test grade (0-100): ");
        scanf("%d", &grade);

        if (grade < 0 || grade > 100) {
            printf("Invalid grade! Grade must be between 0 and 100.
");
        }
    } while (grade < 0 || grade > 100);

    printf("
Valid Grade Accepted: %d
", grade);

    return 0;
}

Concept Explanation:

This beginner program demonstrates the exit-controlled do-while loop for input validation from Lab 3. It guarantees that the input prompt executes at least once and continues looping while the invalid input condition evaluates to true.

C Task 5: Multiplication Table Generator

Question: Write a C program that displays the multiplication table for a given integer N from 1 to 10. Prompt the user for an integer N, and use a simple for loop to iterate from 1 to 10, printing each multiplication statement (N x i = product).

Solution:

#include <stdio.h>

int main() {
    int n;

    printf("Enter integer for multiplication table: ");
    scanf("%d", &n);

    printf("
--- Multiplication Table of %d ---
", n);
    for (int i = 1; i <= 10; i++) {
        printf("%d x %2d = %d
", n, i, n * i);
    }

    return 0;
}

Concept Explanation:

This beginner task demonstrates simple fixed iteration using a for loop from Lab 3. It multiplies the input integer N by the loop counter variable i from 1 through 10 to render a multiplication table.

C Task 6: Reverse an Integer Number

Question: Write a C program that reverses the digits of a given positive integer. Prompt the user for an integer number (e.g., 12345). Use a while loop with modulo division (% 10) and integer division (/ 10) to extract digits and construct the reversed integer.

Solution:

#include <stdio.h>

int main() {
    int num, reversedNum = 0, remainder;

    printf("Enter a positive integer: ");
    scanf("%d", &num);

    int originalNum = num;

    while (num > 0) {
        remainder = num % 10;
        reversedNum = (reversedNum * 10) + remainder;
        num /= 10;
    }

    printf("
Original Number: %d
", originalNum);
    printf("Reversed Number: %d
", reversedNum);

    return 0;
}

Concept Explanation:

This medium task applies digit manipulation using a while loop as covered in Lab 3. It repeatedly extracts the last digit using modulo % 10, shifts the accumulated reversed value, and reduces the original number by factor of 10.

C Task 7: Power Calculator (Base^Exponent)

Question: Write a C program that calculates the power of a number without using math functions. Prompt the user for an integer base and a non-negative integer exponent. Use a for loop to multiply the base by itself exponent times, and print the calculated result.

Solution:

#include <stdio.h>

int main() {
    int base, exponent;
    long long result = 1;

    printf("Enter base integer: ");
    scanf("%d", &base);

    printf("Enter exponent (non-negative integer): ");
    scanf("%d", &exponent);

    for (int i = 1; i <= exponent; i++) {
        result *= base;
    }

    printf("
Result: %d^%d = %lld
", base, exponent, result);

    return 0;
}

Concept Explanation:

This medium program demonstrates iterative multiplication using a for loop from Lab 3. It initializes an accumulator variable to 1 and performs exponent iterations to calculate powers using basic arithmetic loops.

C Task 8: Harmonic Series Sum

Question: Write a C program to calculate the sum of the Harmonic Series up to N terms: 1 + 1/2 + 1/3 + … + 1/N. Prompt the user for positive integer N. Use a for loop with double precision division to accumulate the sum and display the output formatted to 4 decimal places.

Solution:

#include <stdio.h>

int main() {
    int n;
    double sum = 0.0;

    printf("Enter number of terms N for Harmonic Series: ");
    scanf("%d", &n);

    for (int i = 1; i <= n; i++) {
        sum += 1.0 / i;
    }

    printf("
Sum of Harmonic Series up to %d terms = %.4lf
", n, sum);

    return 0;
}

Concept Explanation:

This medium program practices floating-point series summation in a for loop from Lab 3. By using floating-point division (1.0 / i), it prevents integer truncation and accurately accumulates the harmonic terms.

C Task 9: Prime Number Checker

Question: Write a C program to check whether a given integer is a prime number. Prompt the user for an integer greater than 1. Use a for loop to test divisibility from 2 up to N/2. Set a boolean flag variable to determine if the number is prime and display the outcome.

Solution:

#include <stdio.h>

int main() {
    int n, isPrime = 1;

    printf("Enter an integer greater than 1: ");
    scanf("%d", &n);

    if (n <= 1) {
        isPrime = 0;
    } else {
        for (int i = 2; i <= n / 2; i++) {
            if (n % i == 0) {
                isPrime = 0;
                break;
            }
        }
    }

    if (isPrime == 1) {
        printf("%d is a PRIME number.
", n);
    } else {
        printf("%d is NOT a prime number.
", n);
    }

    return 0;
}

Concept Explanation:

This challenging program utilizes a for loop with a break statement and flag variable logic as taught in Lab 3. It tests for factor existence between 2 and N/2, terminating early if a dividing factor is detected.

C Task 10: Digital Savings Bank Management System

Question: Write a C program that simulates an interactive digital savings account menu. Use a do-while loop to display options: 1. Deposit, 2. Withdraw, 3. Check Balance, 4. Exit. Track the account balance and process transaction choices repeatedly until the user selects option 4 to exit.

Solution:

#include <stdio.h>

int main() {
    int choice;
    double balance = 1000.0, amount;

    do {
        printf("
=== SAVINGS BANK MANAGEMENT MENU ===
");
        printf("1. Deposit Money
");
        printf("2. Withdraw Money
");
        printf("3. Check Account Balance
");
        printf("4. Exit System
");
        printf("Enter your choice (1-4): ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter deposit amount ($): ");
                scanf("%lf", &amount);
                if (amount > 0) {
                    balance += amount;
                    printf("Deposit successful! New Balance: $%.2lf
", balance);
                } else {
                    printf("Invalid deposit amount!
");
                }
                break;
            case 2:
                printf("Enter withdrawal amount ($): ");
                scanf("%lf", &amount);
                if (amount > 0 && amount <= balance) {
                    balance -= amount;
                    printf("Withdrawal successful! New Balance: $%.2lf
", balance);
                } else {
                    printf("Insufficient funds or invalid amount!
");
                }
                break;
            case 3:
                printf("Current Account Balance: $%.2lf
", balance);
                break;
            case 4:
                printf("Exiting Bank System. Goodbye!
");
                break;
            default:
                printf("Invalid selection! Please enter option 1-4.
");
        }
    } while (choice != 4);

    return 0;
}

Concept Explanation:

This challenging problem demonstrates a complete menu-driven program combining a do-while loop and switch statement from Lab 3. It maintains persistent balance state across multiple user interaction steps until exit is chosen.

C++ Programming – 10 Unique Tasks

C++ Task 1: Elevator Floor Counter

Question: Write a C++ program that simulates an elevator ascending to a requested floor. Prompt the user for target floor number N (integer). Use an entry-controlled while loop starting from floor 1 up to floor N, printing “Elevator at Floor X” during each step until arrival.

Solution:

#include <iostream>
using namespace std;

int main() {
    int targetFloor;
    int currentFloor = 1;

    cout << "Enter destination floor number (integer): ";
    cin >> targetFloor;

    cout << "
=== ELEVATOR ASCENT STARTED ===" << endl;
    while (currentFloor <= targetFloor) {
        cout << "Elevator at Floor " << currentFloor << endl;
        currentFloor++;
    }

    cout << "Elevator arrived at destination floor " << targetFloor << "." << endl;

    return 0;
}

Concept Explanation:

This beginner program demonstrates entry-controlled while loops in C++ from Lab 3. It evaluates currentFloor <= targetFloor before each pass, incrementing currentFloor until the destination floor is reached.

C++ Task 2: Sum of Squares of First N Integers

Question: Write a C++ program to compute the sum of squares of the first N positive integers: 1^2 + 2^2 + 3^2 + … + N^2. Prompt the user for positive integer N. Use a for loop to accumulate the sum of squares into a total variable and output the result.

Solution:

#include <iostream>
using namespace std;

int main() {
    int n;
    int sumOfSquares = 0;

    cout << "Enter a positive integer (N): ";
    cin >> n;

    for (int i = 1; i <= n; i++) {
        sumOfSquares += (i * i);
    }

    cout << "
Sum of squares of first " << n << " numbers = " << sumOfSquares << endl;

    return 0;
}

Concept Explanation:

This beginner program practices fixed iteration for loops and mathematical summation in C++ based on Lab 3 concepts. It computes i * i during each loop pass and adds it to sumOfSquares.

C++ Task 3: Print Multiples of 7 in a Range

Question: Write a C++ program that displays all numbers divisible by 7 up to a user-specified limit N. Prompt for positive integer N, use a for loop from 1 to N, and check divisibility using (i % 7 == 0) to print matching numbers.

Solution:

#include <iostream>
using namespace std;

int main() {
    int limit;

    cout << "Enter upper limit number (N): ";
    cin >> limit;

    cout << "
Multiples of 7 from 1 to " << limit << ":" << endl;
    for (int i = 1; i <= limit; i++) {
        if (i % 7 == 0) {
            cout << i << " ";
        }
    }
    cout << endl;

    return 0;
}

Concept Explanation:

This beginner task reinforces range scanning using for loops and conditional filter checks in C++ from Lab 3. It checks remainder equality against zero to isolate multiples of 7.

C++ Task 4: Positive Age Input Enforcer

Question: Write a C++ program that enforces valid age input for a medical form. Use an exit-controlled do-while loop to repeatedly ask the user to enter an age greater than 0. If a user enters 0 or a negative number, display an error and repeat until a positive age is entered.

Solution:

#include <iostream>
using namespace std;

int main() {
    int age;

    do {
        cout << "Enter patient age (must be > 0): ";
        cin >> age;

        if (age <= 0) {
            cout << "Invalid entry! Age must be a positive integer." << endl;
        }
    } while (age <= 0);

    cout << "
Patient Age Recorded: " << age << " years." << endl;

    return 0;
}

Concept Explanation:

This beginner program practices do-while input validation loops in C++ from Lab 3. The loop guarantees initial execution and continues asking for user input until the age <= 0 condition becomes false.

C++ Task 5: Number Counting Up to N

Question: Write a C++ program that counts up from 1 to N. Prompt the user to enter a positive integer N. Use a simple for loop to display each integer value separated by spaces.

Solution:

#include <iostream>
using namespace std;

int main() {
    int n;

    cout << "Enter upper count limit N: ";
    cin >> n;

    cout << "
Counting numbers 1 to " << n << ":" << endl;
    for (int i = 1; i <= n; i++) {
        cout << i << " ";
    }
    cout << endl;

    return 0;
}

Concept Explanation:

This beginner task demonstrates basic for loop iteration and stream insertion in C++ from Lab 3. The loop counter variable i steps from 1 up to N to output the numerical sequence.

C++ Task 6: Count Digits in an Integer

Question: Write a C++ program to count the total number of digits in a given positive integer. Prompt the user for an integer number (e.g., 84729). Use a while loop with integer division (/ 10) to reduce the number until it becomes 0, incrementing a digit count variable.

Solution:

#include <iostream>
using namespace std;

int main() {
    int num, count = 0;

    cout << "Enter a positive integer: ";
    cin >> num;

    int temp = num;

    while (temp > 0) {
        count++;
        temp /= 10;
    }

    cout << "
The number " << num << " contains " << count << " digit(s)." << endl;

    return 0;
}

Concept Explanation:

This medium task demonstrates iterative digit processing using a while loop in C++ based on Lab 3. Dividing temp by 10 truncates the rightmost digit until the integer value reaches 0.

C++ Task 7: Compound Interest Investment Accumulator

Question: Write a C++ program that projects investment compound growth over N years. Prompt for initial principal deposit ($), annual interest rate (%), and investment duration N (years). Use a for loop to calculate and display the total balance at the end of each year.

Solution:

#include <iostream>
using namespace std;

int main() {
    double principal, rate;
    int years;

    cout << "Enter initial principal investment ($): ";
    cin >> principal;

    cout << "Enter annual interest rate (%): ";
    cin >> rate;

    cout << "Enter duration in years: ";
    cin >> years;

    double balance = principal;

    cout << "
Year	Account Balance" << endl;
    cout << "-------------------------" << endl;
    for (int year = 1; year <= years; year++) {
        balance += balance * (rate / 100.0);
        cout << year << "	$" << balance << endl;
    }

    return 0;
}

Concept Explanation:

This medium problem practices compound growth accumulation inside a for loop in C++ following Lab 3 principles. It updates balance iteratively and outputs a year-by-year financial schedule table.

C++ Task 8: Alternating Series Sum

Question: Write a C++ program that computes the sum of an alternating series up to N terms: 1 – 2 + 3 – 4 + 5 – 6 + … N. Prompt the user for positive integer N. Use a for loop with conditional parity checks (odd i adds, even i subtracts) to compute total sum.

Solution:

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0;

    cout << "Enter number of terms N for Alternating Series: ";
    cin >> n;

    for (int i = 1; i <= n; i++) {
        if (i % 2 != 0) {
            sum += i;
        } else {
            sum -= i;
        }
    }

    cout << "
Sum of Alternating Series up to " << n << " terms = " << sum << endl;

    return 0;
}

Concept Explanation:

This medium program demonstrates conditional accumulator logic inside a C++ for loop from Lab 3. It checks counter parity using (i % 2 != 0) to alternate between addition and subtraction operations.

C++ Task 9: Greatest Common Divisor (GCD) Finder

Question: Write a C++ program to find the Greatest Common Divisor (GCD) of two positive integers using Euclidean subtraction/modulo algorithm. Prompt the user for two integers a and b. Use a while loop (while b != 0) to update values until GCD is calculated.

Solution:

#include <iostream>
using namespace std;

int main() {
    int a, b;

    cout << "Enter first positive integer (a): ";
    cin >> a;

    cout << "Enter second positive integer (b): ";
    cin >> b;

    int num1 = a, num2 = b;

    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }

    cout << "
Greatest Common Divisor (GCD) of " << num1 << " and " << num2 << " = " << a << endl;

    return 0;
}

Concept Explanation:

This challenging program implements Euclidean algorithm logic using a while loop in C++ as taught in Lab 3. It repeatedly replaces (a, b) with (b, a % b) until b becomes 0, leaving the GCD in variable a.

C++ Task 10: Point-of-Sale Store Cart System

Question: Write a C++ program for a retail Point-of-Sale shopping cart. Use a do-while loop to show menu: 1. Add Standard Item ($5), 2. Add Premium Item ($15), 3. View Current Total, 4. Checkout and Exit. Accumulate cart total and repeat until option 4 is selected.

Solution:

#include <iostream>
using namespace std;

int main() {
    int choice;
    double cartTotal = 0.0;

    do {
        cout << "
=== POINT-OF-SALE CART MENU ===" << endl;
        cout << "1. Add Standard Item ($5.00)" << endl;
        cout << "2. Add Premium Item ($15.00)" << endl;
        cout << "3. View Current Cart Total" << endl;
        cout << "4. Checkout & Exit" << endl;
        cout << "Enter option (1-4): ";
        cin >> choice;

        switch (choice) {
            case 1:
                cartTotal += 5.00;
                cout << "Standard Item added! Cart Total: $" << cartTotal << endl;
                break;
            case 2:
                cartTotal += 15.00;
                cout << "Premium Item added! Cart Total: $" << cartTotal << endl;
                break;
            case 3:
                cout << "Current Cart Total: $" << cartTotal << endl;
                break;
            case 4:
                cout << "Checking out... Final Total Due: $" << cartTotal << endl;
                break;
            default:
                cout << "Invalid choice! Please select 1-4." << endl;
        }
    } while (choice != 4);

    return 0;
}

Concept Explanation:

This challenging problem integrates interactive C++ do-while loops and switch menu logic from Lab 3. It accumulates cart item purchases over multiple menu passes until the user triggers checkout.

Leave a Comment