Scenario-Based Coding Questions on 1D Arrays in C++

Need fun and practical coding problems? This post contains some scenario-based questions on 1D arrays in C++, covering real-world situations like banking systems, movie ratings, inventory management, and even dragon battles! These fun problems can help programmers practice arrays and solve real-world challenges. Ideal for students and coding fans who wish to enhance their C++ skills through practical challenges.

Favorite Movie Ratings

A group watching TV, one person rates the movie 10.
Watching a Movie
You and your friends love watching movies and often rate them after watching. Write a program in C++ that takes ratings (out of 10) for 5 different movies from the user and finds the average rating of all movies.

Test Case
Input
Enter rating of movie 1 (out of 10): 7.5
Enter rating of movie 2 (out of 10): 8.2
Enter rating of movie 3 (out of 10): 6.9
Enter rating of movie 4 (out of 10): 9.0
Enter rating of movie 5 (out of 10): 7.8
Expected Output
Average movie rating: 7.88
  • The program starts by declaring a 1D array ratings to store the ratings of 5 movies.
  • It prompts the user to enter ratings and stores them in the array using a for loop.
  • As the user enters each rating, the program adds it to a sum variable to calculate the total ratings.
  • Once all ratings are entered, the program calculates the average rating by dividing the total sum by 5.
  • Finally, the program displays the calculated average rating.
#include <iostream>
using namespace std;

int main() {
    double ratings[5], sum = 0;
    
    for (int i = 0; i < 5; i++) {
        printf("Enter rating of movie %d (out of 10): ", i + 1);
        cin >> ratings[i];
        sum += ratings[i];
    }
    
    double average = sum / 5;
    printf("Average movie rating: %.2f\n", average);
    
    return 0;
}

Simple Text Editor

 A sequence of numbers is reversed.
Reversing Numbers
Imagine you are creating a simple text editor where users can enter a sequence of numbers, and the system should display them in reverse order. Write a C++ program that takes 5 numbers as input and prints them in reverse order.

Test Case
Input
Enter 5 numbers:
1
2
3
4
5
Expected Output
Numbers in reverse order: 5 4 3 2 1

The program starts by declaring a 1D array, named numbers to store 5 numbers.

It prompts the user to enter 5 numbers and stores them in the array.

The program then prints the numbers in reverse order by iterating the array from the last index to the first.

This ensures the numbers are displayed in the opposite sequence of input.

#include <iostream>
using namespace std;

int main() {
    int numbers[5];
    
    cout << "Enter 5 numbers: \n";
    for (int i = 0; i < 5; i++) {
        cin >> numbers[i];
    }
    
    cout << "Numbers in reverse order: ";
    for (int i = 4; i >= 0; i--) {
        cout << numbers[i] << " ";
    }
    cout << "\n";
    
    return 0;
}

Banking System

A report shows even and odd transactions.
Transaction Report
You are developing a banking system that categorizes transaction amounts into even and odd numbers. Write a C++ program that takes 6 transaction amounts as input and counts how many are even and how many are odd.

Test Case
Input
Enter 6 transaction amounts:
120
135
200
75
60
90
Expected Output
Even transactions: 4
Odd transactions: 2
  • The program starts by declaring a 1D array transactions to store 6 transaction amounts.
  • It prompts the user to enter 6 transaction values and stores them in the transactions array using a loop.
  • As each value is entered, the program checks whether the number is even or odd.
  • If transactions[i] % 2 == 0, it is considered an even number, and the even_count variable is incremented.
  • Otherwise, it is considered an odd number, and the odd_count variable is incremented.
  • Once all the values are processed, the program displays the total count of even and odd transactions.
#include <iostream>
using namespace std;

int main() {
    int transactions[6], even_count = 0, odd_count = 0;
    
    cout << "Enter 6 transaction amounts: \n";
    for (int i = 0; i < 6; i++) {
        cin >> transactions[i];
        if (transactions[i] % 2 == 0) {
            even_count++;
        } else {
            odd_count++;
        }
    }
    
    cout << "Even transactions: " << even_count << "\n";
    cout << "Odd transactions: " << odd_count << "\n";
    
    return 0;
}

Finding the Longest and Shortest Name

A school event.
School Event
You are organizing a school event and need to record the names of participants. To properly allocate name tags, you must determine the longest and shortest name among them. Write a C++ program that takes participants names as input and then finds the longest and shortest name.

Test Case
Input
Enter the number of participants: 6
Enter the names of 6 participants:
Alice
Jonathon
Zoe
Michael
Eve
Christopher
Expected Output
Longest Name: Christopher
Shortest Name: Zoe
  • The program starts by asking the user for the number of participants and stores it in n.
  • It then declares a 1D array names of size n to store the participant names.
  • The program prompts the user to enter each name one by one using a loop.
  • It manually calculates the length of each name using another loop that counts characters until it reaches the null terminator ('\0').
  • The program then initializes four variables:
  • longestName and maxLength store the longest name and its length.
  • shortestName and minLength store the shortest name and its length.
  • The program compares the counted length with maxLength and minLength.
  • If a name is longer than maxLength, it updates longestName.
  • If a name is shorter than minLength, it updates shortestName.
  • After processing all names, the program displays the longest and shortest name.
#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of participants: ";
    cin >> n;
    cin.ignore(); 

    string names[n];

    cout << "Enter the names of " << n << " participants:\n";
    for (int i = 0; i < n; i++) {
        getline(cin, names[i]);
    }

    string longestName = names[0], shortestName = names[0];
    int maxLength = 0, minLength = 0;

    for (int j = 0; names[0][j] != '\0'; j++) {
        maxLength++;
        minLength++;
    }

    for (int i = 1; i < n; i++) {
        int count = 0;
        
        for (int j = 0; names[i][j] != '\0'; j++) {
            count++;
        }

        if (count > maxLength) {
            maxLength = count;
            longestName = names[i];
        }
        if (count < minLength) {
            minLength = count;
            shortestName = names[i];
        }
    }

    cout << "Longest Name: " << longestName << "\n";
    cout << "Shortest Name: " << shortestName << "\n";

    return 0;
}

Sorting Favorite Snacks

A person wonders how to sort snacks alphabetically.
Snack Sorting
Imagine you have a list of your 5 favorite snacks, and you want to arrange them in alphabetical order. Write a program in C++ language that takes the names of 5 snacks from the user and sorts them in alphabetical order.

Test Case
Input
Enter favorite snack 1: Chips
Enter favorite snack 2: Chocolate
Enter favorite snack 3: Popcorn
Enter favorite snack 4: Cookies
Enter favorite snack 5: Nuts
Expected Output
Snacks in alphabetical order:
Chips
Chocolate
Cookies
Nuts
Popcorn
  • The program begins by declaring a 1D array snacks to store 5 favorite snack names.
  • A for loop is used to prompt the user to enter the name of each snack one by one.
  • After collecting all the snack names, the program sorts them manually using a nested loop.
  • The outer loop iterates through the elements of the snacks array, and the inner loop compares the current snack with every other snack that comes after it.
  • Another while loop is used to compare each character of two snack names until a mismatch is found or the end of the shorter name is reached.
  • If a snack should come later in the alphabetical order, their positions are swapped manually using a temporary string variable.
  • After sorting, the program prints the sorted list of snacks in alphabetical order using a loop.
#include <iostream>
#include <string>
using namespace std;

int main() {
    string snacks[5];
    
    for (int i = 0; i < 5; i++) {
        printf("Enter favorite snack %d: ", i + 1);
        cin>>snacks[i];
    }

    for (int i = 0; i < 4; i++) {
        for (int j = i + 1; j < 5; j++) {
            int k = 0;
            while (k < snacks[i].length() && k < snacks[j].length() && snacks[i][k] == snacks[j][k]) {
                k++;
            }
            if (k < snacks[i].length() && k < snacks[j].length() && snacks[i][k] > snacks[j][k]) {
                string temp = snacks[i];
                snacks[i] = snacks[j];
                snacks[j] = temp;
            }
        }
    }
    
    cout << "Snacks in alphabetical order: \n";
    for (int i = 0; i < 5; i++) {
        cout << snacks[i] << "\n";
    }
    
    return 0;
}

Smart Grocery Billing System

A person receives a bag from a cashier at a store
Grocery Shopping
You are developing a billing system for a grocery store. The store allows customers to buy multiple items, and each item has a price. At the checkout counter, the system should calculate the total bill, apply a discount if the total exceeds a certain limit, and display the final amount to be paid. Write a C++ program that takes the number of items and their prices as input, calculates the total bill, applies a 10% discount if the total exceeds $100, and then displays the original bill, discount (if applicable), and the final payable amount.

Test Case
Input
Enter the number of items: 5
Enter price of item 1: 20
Enter price of item 2: 30
Enter price of item 3: 15
Enter price of item 4: 25
Enter price of item 5: 18
Expected Output
Original Bill: $108
Discount: $10.8
Final Payable Amount: $97.2
  • The program starts by asking the user to enter the number of items. This input is stored in the variable n.
  • Next, the program declares an array prices of size n to store the prices of each item.
  • The total variable is initialized to 0 to store the total bill amount.
  • Using a for loop, the program takes input for each item’s price from the user and adds it to the total variable.
  • After collecting all prices, the program checks if the total bill exceeds $100. If so, a 10% discount is applied by multiplying the total by 0.10, and the discount amount is stored in discount.
  • Finally, the program displays the original bill, discount amount, and final payable amount after applying the discount.
#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of items: ";
    cin >> n;

    double prices[n], total = 0;
    
    for (int i = 0; i < n; i++) {
        cout<<"Enter price of item "<<i+1<<": ";
        cin >> prices[i];
        total += prices[i];
    }

    double discount = 0;
    if (total > 100) {
        discount = total * 0.10;
    }

    cout << "\nOriginal Bill: $" << total;
    cout << "\nDiscount: $" << discount;
    cout << "\nFinal Payable Amount: $" << total - discount << endl;

    return 0;
}

Gym Performance Tracker

A trainer helps a person lifting weights.
Goal Achieved
A fitness trainer tracks the daily workout hours of a client for a week using an array. The trainer wants a program to calculate total hours, find the most active day, and check if the client met the weekly goal of 10 hours of workout. Write a C++ program that takes 7 daily workout hours as input, calculates the total hours, identifies the most active day, and determines whether the client has met the weekly goal of 10 hours.

Test Case
Input
Enter workout hours for each day (7 days):
Enter workout hours for day 1: 1.5
Enter workout hours for day 2: 2
Enter workout hours for day 3: 1
Enter workout hours for day 4: 0.5
Enter workout hours for day 5: 2.5
Enter workout hours for day 6: 1.2
Enter workout hours for day 7: 1.8
Expected Output
Total workout hours: 10.5
Most active day: Day 5 with 2.5 hours
Goal Achieved! Well done!
  • The program starts by creating an array workout of size 7 to store workout hours for each day of the week.
  • The total variable is initialized to 0 to keep track of total workout hours.
  • The maxHours variable is initialized to 0 to store the maximum workout hours in a day.
  • The maxDay variable is set to 0 to track which day had the highest workout hours.
  • Using a for loop, the program:
    • Takes input for workout hours of each day.
    • Adds the hours to total.
    • Updates maxHours and maxDay if the current day’s workout is greater than maxHours.
  • After collecting all workout hours, the program checks if the total hours are 10 or more.
  • If yes, it displays “Goal Achieved!” Otherwise, it displays “Goal Not Achieved!”.
  • Finally, the program displays the total workout hours, the most active day and its workout hours and whether the weekly goal was met.
#include <iostream>
using namespace std;

int main() {
    double workout[7], total = 0, maxHours = 0;
    int maxDay = 0;

    cout << "Enter workout hours for each day (7 days):\n";
    for (int i = 0; i < 7; i++) {
        cout<<"Enter workout hours for day "<<i+1<<": ";
        cin >> workout[i];
        total += workout[i];

        if (workout[i] > maxHours) {
            maxHours = workout[i];
            maxDay = i + 1;
        }
    }

    cout << "\nTotal workout hours: " << total;
    cout << "\nMost active day: Day " << maxDay << " with " << maxHours << " hours";

    if (total >= 10) {
        cout << "\nGoal Achieved! Well done!\n";
    } else {
        cout << "\nGoal Not Achieved! Keep pushing!\n";
    }

    return 0;
}

Stock Market Profit Calculator

A trader at a desk says it's a good day to sell stocks
Stock Trader
A stock trader monitors the daily stock prices of a company over 10 days. The trader wants to maximize their profit by buying at the lowest price before selling at the highest price that comes after the buy day. Write a C++ program that takes 10 stock prices as input in a 1D array and finds the best day to buy and sell to maximize profit.

Test Case
Input
Enter stock prices for 10 days: 100 180 260 310 40 535 695 110 120 150
Expected Output
Best day to buy: Day 5 at price 40
Best day to sell: Day 7 at price 695
Maximum Profit: 655
  • The program first prompts the user to enter the stock prices for 10 days, which are stored in an array called prices.
  • To maximize profit, the program uses two nested loops.
  • The outer loop iterates through each price as a potential buy day, while the inner loop iterates through all subsequent days as possible sell days.
  • For every valid buy-sell pair, the program calculates the profit by subtracting the buy price from the sell price.
  • If the calculated profit is greater than the previously recorded maximum profit, the program updates the best buy day and best sell day.
  • Once all buy-sell pairs are examined, the program displays the best day to buy and sell along with the maximum profit.
  • If no profit is possible, the program informs the user.
#include <iostream>
using namespace std;

int main() {
    const int DAYS = 10;
    int prices[DAYS];

    cout << "Enter stock prices for 10 days: ";
    for (int i = 0; i < DAYS; i++) {
        cin >> prices[i];
    }

    int maxProfit = 0, buyDay = 0, sellDay = 0;

    for (int i = 0; i < DAYS; i++) {  
        for (int j = i + 1; j < DAYS; j++) {  
            int profit = prices[j] - prices[i];
            if (profit > maxProfit) {
                maxProfit = profit;
                buyDay = i;
                sellDay = j;
            }
        }
    }

    if (maxProfit > 0) {
        cout << "Best day to buy: Day " << (buyDay + 1) << " at price " << prices[buyDay] << endl;
        cout << "Best day to sell: Day " << (sellDay + 1) << " at price " << prices[sellDay] << endl;
        cout << "Maximum Profit: " << maxProfit << endl;
    } else {
        cout << "No profit can be made.\n";
    }

    return 0;
}

Longest Productive Streak in a Call Center

Four people working at computer desks in a customer support center
Customer Support Center
A customer support center tracks the number of calls handled per day for 15 days. The management wants to find the longest consecutive streak where the number of calls handled was above a user-defined threshold. This will help them identify the most productive periods. Write a C++ program that takes 15 daily call counts as input in a 1D array and finds the longest consecutive streak where the number of calls handled was above a given threshold.

Test Case
Input
Enter the number of calls handled on day 1: 40
Enter the number of calls handled on day 2: 55
Enter the number of calls handled on day 3: 60
Enter the number of calls handled on day 4: 45
Enter the number of calls handled on day 5: 70
Enter the number of calls handled on day 6: 80
Enter the number of calls handled on day 7: 85
Enter the number of calls handled on day 8: 30
Enter the number of calls handled on day 9: 25
Enter the number of calls handled on day 10: 90
Enter the number of calls handled on day 11: 100
Enter the number of calls handled on day 12: 110
Enter the number of calls handled on day 13: 95
Enter the number of calls handled on day 14: 50
Enter the number of calls handled on day 15: 60
Enter the call threshold: 50
Expected Output
Longest productive streak: 4 days (Day 10 to Day 13)
  • The program starts by asking the user to enter the number of calls handled each day for 15 days. These values are stored in an array called calls.
  • The program also prompts the user to enter a threshold value.
  • The goal is to find the longest consecutive sequence where the number of calls is greater than this threshold.
  • To solve this problem, the program uses a loop to iterate through the calls array and track the longest streak of consecutive productive days. It maintains:
    • maxLength – stores the length of the longest streak found so far.
    • maxStart – stores the starting index of the longest streak.
    • currentLength – tracks the length of the current streak.
    • currentStart – tracks the starting index of the current streak.
  • If a day’s call count is above the threshold, it increases the currentLength.
  • If the streak ends (a day has calls below the threshold), it checks if currentLength is the longest so far. If yes, it updates maxLength and maxStart.
  • At the end of the loop, the longest streak is displayed, and the starting and ending days are calculated using the maxStart and maxLength.
#include <iostream>

using namespace std;

int main() {
    const int DAYS = 15;  
    int calls[DAYS];  
    int threshold;  

    for (int i = 0; i < DAYS; i++) {
        printf("Enter the number of calls handled on day %d: ", i + 1);
        cin >> calls[i];
    }

    printf("Enter the call threshold: ");
    cin >> threshold;

    int maxLength = 0, maxStart = -1;  
    int currentLength = 0, currentStart = 0;  

    for (int i = 0; i < DAYS; i++) {
        if (calls[i] > threshold) {  
            if (currentLength == 0) {  
                currentStart = i;  
            }
            currentLength++;  
        } else {  
            if (currentLength > maxLength) {  
                maxLength = currentLength;
                maxStart = currentStart;
            }
            currentLength = 0;  
        }
    }

    if (currentLength > maxLength) {
        maxLength = currentLength;
        maxStart = currentStart;
    }

    if (maxLength > 0) {
        printf("Longest productive streak: %d days (Day %d to Day %d)\n", maxLength, maxStart + 1, maxStart + maxLength);
    } else {
        printf("No productive streak found above the threshold.\n");
    }

    return 0;
}

Maximizing Artifact Value

A young explorer excitedly finds an artifact in the jungle.
Adventurous Treasure Hunt
During an adventurous treasure hunt, a group of explorers must collect valuable artifacts hidden in a dense jungle. Each artifact has a specific value, but the explorers can only carry a limited number of artifacts in their backpacks. The goal is to collect artifacts in such a way that the total value is maximized while staying within the carrying limit. Write a C++ program that takes the number of artifacts as input, followed by their individual values. The program should then allow the user to specify how many artifacts they can carry. It should determine the best selection of artifacts that maximizes the total value and display the selected artifacts along with their total value.

Test Case
Input
Enter the number of artifacts: 5
Enter value for artifact 1: 15
Enter value for artifact 2: 25
Enter value for artifact 3: 50
Enter value for artifact 4: 30
Enter value for artifact 5: 10
Enter the number of artifacts you can carry: 3
Expected Output
Selected artifacts: 50 30 25
Total value of selected artifacts: 105
  • The program starts by asking the user to enter the number of artifacts available. This input is stored in the variable n.
  • Next, an array named artifacts is initialized to store the values of the artifacts. The program then uses a for loop to prompt the user for each artifact’s value.
  • After gathering the artifact values, the program prompts the user to enter how many artifacts they can carry, storing this input in the carryLimit variable.
  • To ensure the explorer selects the most valuable artifacts, the program sorts the artifacts array in descending order.
  • This sorting is done using a selection sort algorithm, which iterates through the array, finding the largest element in the unsorted portion and swapping it with the first element of that portion
  • Once sorted, the program selects the first carryLimit number of artifacts from the sorted array, as they have the highest values.
  • A for loop is used to print the selected artifacts and calculate their total value by adding them to the totalValue variable.
  • Finally, the program displays the selected artifacts and prints the total value of the artifacts collected.
#include <iostream>
using namespace std;

int main() {
    int n; 
    cout << "Enter the number of artifacts: ";
    cin >> n;

    int artifacts[n];
    for (int i = 0; i < n; i++) {
        printf("Enter value for artifact %d: ", i + 1);
        cin >> artifacts[i];
    }

    int carryLimit; 
    cout << "Enter the number of artifacts you can carry: ";
    cin >> carryLimit;

    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (artifacts[j] > artifacts[i]) {
                int temp = artifacts[i];
                artifacts[i] = artifacts[j];
                artifacts[j] = temp;
            }
        }
    }

    int totalValue = 0;
    cout << "Selected artifacts: ";
    for (int i = 0; i < carryLimit; i++) {
        cout << artifacts[i] << " ";
        totalValue += artifacts[i];
    }
    cout << endl;

    cout << "Total value of selected artifacts: " << totalValue << endl;

    return 0;
}

Secure Data Transmission with Parity Encoding

A man using a laptop wonders if his data is being transmitted securely
Secure Data Transmission
A secret intelligence agency is transmitting highly confidential data packets over a secure network. However, due to possible transmission errors, a simple parity check system is used to verify data integrity. Each data packet consists of N numbers entered by the user. A parity check value is then appended to the data based on the sum of these numbers. If the sum of the numbers is even, the parity value is set to 0, ensuring even parity. If the sum is odd, the parity value is set to 1 to maintain the integrity of the transmission. Once the parity value is calculated, the final packet is transmitted over the network. However, network errors might corrupt the data, so the receiver must validate the transmission by recomputing the sum of the received packet. If the sum remains even, the transmission is considered successful, and the data is confirmed as valid. If the sum turns out to be odd, an error is detected in the transmission. To simulate a transmission error, the program allows the user to modify a value in the received data before checking its integrity. This ensures that the parity check mechanism functions correctly and detects any errors. Write a C++ program that takes N data values as input, calculates and appends the correct parity check value, transmits the data, and then verifies its integrity upon reception. The program should also allow the user to modify the received data to test the error detection capability.

Test Case 1
Input
Enter the number of data values: 4
Enter 4 data values: 12 45 23 8
Do you want to modify a received value to simulate an error? (y/n): y
Enter the index (0 to 3) of the value to change: 3
Enter new value: 1
Expected Output
Transmitted Packet (with parity check value): 12 45 23 8 0
Transmission Corrupted: Error detected!

Test Case 2
Input
Enter the number of data values: 4
Enter 4 data values: 10 20 30 40
Do you want to modify a received value to simulate an error? (y/n): y
Enter the index (0 to 3) of the value to change: 2
Enter new value: 4
Expected Output
Transmitted Packet (with parity check value): 10 20 30 40 0
Transmission Successful: Data is valid.
  • The program starts by asking the user to enter the number of data values. This input is stored in the variable N.
  • An array of size N + 1 is declared to store the N data values and one additional element for the parity check value.
  • A for loop takes N user inputs, storing them in the array while simultaneously calculating the sum of the numbers.
  • Once all numbers are entered, the program calculates the parity check value:
    • If the sum is even, the parity check value is 0.
    • If the sum is odd, the parity check value is 1.
  • This computed parity value is stored as the last element of the array, making it part of the transmitted packet.
  • Next, to simulate possible corruption during transmission, the program asks the user if they want to modify one of the received values.
  • If the user chooses to change a value, the modified data will be used for validation.
  • To verify the data integrity, the program recalculates the sum of the received packet (including the parity value).
  • If the sum remains even, the transmission is declared successful.
  • If it is odd, an error is detected.
#include <iostream>
using namespace std;

int main() {
    int N;
    cout << "Enter the number of data values: ";
    cin >> N;

    int data[N + 1];
    int sum = 0;

    cout << "Enter " << N << " data values: ";
    for (int i = 0; i < N; i++) {
        cin >> data[i];
        sum += data[i]; 
    }

    data[N] = (sum % 2 == 0) ? 0 : 1;

    cout << "Transmitted Packet (with parity check value): ";
    for (int i = 0; i <= N; i++) {
        cout << data[i] << " ";
    }
    cout << endl;

    char choice;
    cout << "Do you want to modify a received value to simulate an error? (y/n): ";
    cin >> choice;

    if (choice == 'y' || choice == 'Y') {
        int index, newValue;
        cout << "Enter the index (0 to " << N - 1 << ") of the value to change: ";
        cin >> index;

        if (index >= 0 && index < N) {
            cout << "Enter new value: ";
            cin >> newValue;
            data[index] = newValue;
        } else {
            cout << "Invalid index. No modification was made.\n";
        }
    }

    sum = 0;
    for (int i = 0; i <= N; i++) {
        sum += data[i];
    }

    if (sum % 2 == 0) {
        cout << "Transmission Successful: Data is valid.\n";
    } else {
        cout << "Transmission Corrupted: Error detected!\n";
    }

    return 0;
}

Warehouse Inventory Reallocation

 A worker in a safety vest stands outside a warehouse with stacked boxes.
Warehouse
A company manages multiple warehouses, each storing a different quantity of inventory. The company wants to ensure that all warehouses have a specific target inventory. To achieve this, inventory must be redistributed between warehouses efficiently. If the total inventory is insufficient, the company should be informed of the shortage. Similarly, if the total inventory exceeds the required amount, the company should be advised on how much inventory needs to be discarded. The program will take user input for the current and target inventories of multiple warehouses and determine the necessary transfers or adjustments. Write a C++ program that takes the number of warehouses, their current inventory levels, and their target inventory levels as input, and then determines the required inventory transfers or informs the user of any shortages or excess inventory.

Test Case 1
Input
Enter the number of warehouses: 3
Enter the current inventory for each warehouse:
10 20 30
Enter the target inventory for each warehouse:
20 30 10
Expected Output
Move 10 units from Warehouse 3 to Warehouse 1.
Move 10 units from Warehouse 3 to Warehouse 2.
Total transfers required: 2

Test Case 2
Input
Enter the number of warehouses: 3
Enter the current inventory for each warehouse:
10 20 30
Enter the target inventory for each warehouse:
40 50 60
Expected Output
Insufficient inventory! Additional 90 units are required.
  • The program begins by prompting the user to enter the number of warehouses. This value is stored in the variable n.
  • It then declares three arrays:
    • currentInventory stores the current stock levels of each warehouse.
    • targetInventory stores the desired inventory levels.
    • difference calculates the required adjustments for each warehouse.
  • Next, the program asks the user to input the current and target inventories for each warehouse.
  • It computes the total current inventory (totalCurrent) and the total target inventory (totalTarget).
  • The program then evaluates whether the total current inventory matches the total target inventory.
  • If the total current inventory is less than the total target, the program prints a message informing the user of the shortage and exits.
  • If the total current inventory is greater than the total target, the program informs the user of the excess and exits.If the total inventories match, the program proceeds with redistributing inventory between warehouses.
  • To balance the inventory, the program iterates through warehouses using two variables, i and j.
  • i locates warehouses that need inventory (difference[i] > 0).
  • j locates warehouses that have excess inventory (difference[j] < 0).
  • It transfers inventory in the smallest possible increments, ensuring that no warehouse is oversupplied or undersupplied.
  • Each transfer is printed as Move X units from Warehouse Y to Warehouse Z.
  • The number of transfers is counted and displayed at the end.
#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the number of warehouses: ";
    cin >> n;

    int currentInventory[n], targetInventory[n], difference[n];

    cout << "Enter the current inventory for each warehouse:\n";
    for (int i = 0; i < n; i++)
        cin >> currentInventory[i];

    cout << "Enter the target inventory for each warehouse:\n";
    for (int i = 0; i < n; i++)
        cin >> targetInventory[i];

    int totalCurrent = 0, totalTarget = 0;
    for (int i = 0; i < n; i++) {
        difference[i] = targetInventory[i] - currentInventory[i];
        totalCurrent += currentInventory[i];
        totalTarget += targetInventory[i];
    }

    if (totalCurrent < totalTarget) {
        cout << "Insufficient inventory! Additional " << (totalTarget - totalCurrent) << " units are required.\n";
        return 0;
    }
    
    if (totalCurrent > totalTarget) {
        cout << "Excess inventory! " << (totalCurrent - totalTarget) << " units must be discarded.\n";
        return 0;
    }

    int i = 0, j = 0, transfers = 0;

    while (i < n && j < n) {
        while (i < n && difference[i] <= 0) i++;
        while (j < n && difference[j] >= 0) j++;

        if (i < n && j < n) {
            int moveUnits = min(difference[i], -difference[j]);
            cout << "Move " << moveUnits << " units from Warehouse " << j + 1 << " to Warehouse " << i + 1 << ".\n";
            difference[i] -= moveUnits;
            difference[j] += moveUnits;
            transfers++;
        }
    }

    cout << "Total transfers required: " << transfers << endl;
    return 0;
}

Marathon Race Timing Correction

Marathon Race
Marathon Race
In a well-known marathon event, N runners participate, and their race completion times (in minutes) are recorded in an array. However, due to a timing system malfunction, some race times are incorrect and need to be adjusted to ensure fairness. The event organizers have noticed that a few recorded times are significantly higher than expected. To fix this issue, they decide to replace any race time that is greater than twice the average race time with a corrected value. The corrected value should be the median of all valid times from the other runners. If multiple valid times exist, the median is selected to maintain fairness in correction. Once all necessary corrections are made, the list of completion times should be sorted in ascending order for the final review. This ensures that the ranking remains consistent and reflects the actual race performance. Write a C++ program that takes the number of runners N as input, followed by N race completion times. The program should then correct any error times based on the given rules and print the final corrected list in ascending order.

Test Case
Input
Enter the number of runners: 6
Enter 6 race completion times: 50 55 60 500 65 70
Expected Output
Final corrected race times: 50 55 60 60 65 70
  • The program starts by asking the user to enter the number of runners. This input is saved in the variable N.
  • Next, the program declares an array times[N] to store the race completion times of the runners.
  • It also initializes three variables: validTimes[N] to store valid race times, validCount to keep track of how many valid times are recorded, and sum to store the total of all race times.
  • The program then prompts the user to enter the race times for all N runners using a for loop.
  • As each time is entered, it is stored in the times array, and its value is added to sum to calculate the total race time.
  • Once all the times are collected, the program calculates the average race time by dividing sum by N. This value is stored in the variable avgTime.
  • To filter out incorrect times, the program iterates over the times array and checks if each value is less than or equal to twice the avgTime. If the condition is met, the time is stored in the validTimes array, and validCount is incremented.
  • After identifying valid times, the program sorts the validTimes array using bubble sort. Sorting is necessary to determine the median value correctly.
  • Once the valid times are sorted, the program calculates the median.
  • If validCount is odd, the median is the middle element of the sorted list.
  • If validCount is even, the median is the average of the two middle values.
  • With the median calculated, the program goes back to the times array and replaces any incorrect race time (those greater than twice avgTime) with the median.
  • After replacing the incorrect values, the program sorts the times array again to display the corrected race times in ascending order.
  • Finally, the program prints the corrected race times, ensuring that all race times are valid and properly adjusted.
#include <iostream>

using namespace std;

int main() {
    int N;
    cout << "Enter the number of runners: ";
    cin >> N;

    int times[N], validTimes[N], validCount = 0, sum = 0;

    cout << "Enter " << N << " race completion times: ";
    for (int i = 0; i < N; i++) {
        cin >> times[i];
        sum += times[i]; 
    }

    double avgTime = sum / (double)N;  

    for (int i = 0; i < N; i++) {
        if (times[i] <= 2 * avgTime) {
            validTimes[validCount++] = times[i]; 
        }
    }

    for (int i = 0; i < validCount - 1; i++) {
        for (int j = 0; j < validCount - i - 1; j++) {
            if (validTimes[j] > validTimes[j + 1]) {
                int temp = validTimes[j];
                validTimes[j] = validTimes[j + 1];
                validTimes[j + 1] = temp;
            }
        }
    }

    double median;
    if (validCount % 2 == 1) {
        median = validTimes[validCount / 2];  
    } else {
        median = (validTimes[validCount / 2 - 1] + validTimes[validCount / 2]) / 2.0; 
    }

    for (int i = 0; i < N; i++) {
        if (times[i] > 2 * avgTime) {
            times[i] = median;
        }
    }

    for (int i = 0; i < N - 1; i++) {
        for (int j = 0; j < N - i - 1; j++) {
            if (times[j] > times[j + 1]) {
                int temp = times[j];
                times[j] = times[j + 1];
                times[j + 1] = temp;
            }
        }
    }

    cout << "Final corrected race times: ";
    for (int i = 0; i < N; i++) {
        cout << times[i] << " ";
    }
    cout << endl;

    return 0;
}

The Battle Against the Dragon

A knight and an archer prepare to fight a large dragon.
Battle Against The Dragon
A group of warriors is preparing to fight a powerful dragon that has been attacking their kingdom. Each warrior has a certain attack strength, and they will all attack the dragon one by one. The dragon has a large amount of health and a strong defense that reduces the damage it takes from each attack. The warriors attack first, and their combined attacks will reduce the dragon’s health. If they manage to bring its health to zero or below, they win the battle. However, if the dragon is still alive after all warriors have attacked, it will strike back. The dragon’s counterattack will start from the first warrior and move through the group. Each warrior has a certain amount of health, and if the damage they take is more than their health, they will not survive. The program will calculate how many warriors survive after the dragon’s attack. Write a C++ program that takes the number of warriors, their attack strengths, their health, the dragon’s health, and its defense as input. The program should determine if the warriors defeat the dragon and how many of them survive if the dragon counterattacks.

Test Case 1
Input
Enter the dragon’s initial health: 200
Enter the dragon’s defense percentage (0-100): 20
Enter the number of warriors: 3
Enter attack power of warrior 1: 80
Enter attack power of warrior 2: 90
Enter attack power of warrior 3: 100
Expected Output
The warriors have defeated the dragon!
Total effective damage dealt: 216

Test Case 2
Input
Enter the dragon’s initial health: 2000
Enter the dragon’s defense percentage (0-100): 50
Enter the number of warriors: 4
Enter attack power of warrior 1: 200
Enter attack power of warrior 2: 250
Enter attack power of warrior 3: 300
Enter attack power of warrior 4: 350
Expected Output
The dragon survives with 1450 health left!
The warriors must retreat!
The dragon counterattacks and deals 145 damage to the warriors!
1 warriors have died in the dragon’s counterattack.
  • The program starts by asking the user to enter the dragon’s initial health. This input is saved in the dragonHealth variable.
  • Then, it prompts the user to enter the dragon’s defense percentage, which is stored in dragonDefense. The defense percentage will later be used to reduce the warriors’ attack effectiveness.
  • Next, the program asks for the number of warriors and stores this value in numWarriors.
  • Two arrays are created: attackPower[numWarriors] to store each warrior’s attack strength and warriorHealth[numWarriors] to store their health.
  • Every warrior is initially given a health value of 100.
  • The program then prompts the user to enter the attack power of each warrior one by one using a loop.
  • As each attack power is entered, the program calculates the effective damage the warrior inflicts by reducing it according to the dragon’s defense percentage.
  • The reduced damage is added to totalDamage, which keeps track of the combined attack power of all warriors.
  • After collecting all attacks, the program subtracts totalDamage from dragonHealth.
  • If the dragon’s health becomes zero or less, the warriors win, and the program displays a victory message along with the total effective damage dealt.
  • If the dragon still has health remaining, it counterattacks. The program calculates the strength of the counterattack as 10% of the dragon’s remaining health and stores it in retaliationDamage.
  • This counterattack will be distributed among the warriors, starting from the first warrior in the array.
  • The program then determines how many warriors die from the counterattack. It starts from the first warrior and checks if the warrior’s health is less than or equal to the remaining attack power.
  • If so, the warrior is counted as dead, and the attack continues to the next warrior.
  • If a warrior has enough health to survive the remaining attack, their health is reduced, and the attack stops.
  • Finally, the program prints how many warriors were killed in the counterattack.
#include <iostream>
using namespace std;

int main() {
    int dragonHealth, numWarriors;
    float dragonDefense;

    cout << "Enter the dragon's initial health: ";
    cin >> dragonHealth;
    cout << "Enter the dragon's defense percentage (0-100): ";
    cin >> dragonDefense;

    cout << "Enter the number of warriors: ";
    cin >> numWarriors;

    int attackPower[numWarriors]; 
    int warriorHealth[numWarriors];
    int totalDamage = 0;

    for (int i = 0; i < numWarriors; i++) {
        warriorHealth[i] = 100;
    }

    for (int i = 0; i < numWarriors; i++) {
        printf("Enter attack power of warrior %d: ", i + 1);
        cin >> attackPower[i];
        int effectiveDamage = attackPower[i] - (attackPower[i] * dragonDefense / 100);
        totalDamage += effectiveDamage; 
    }

    dragonHealth -= totalDamage;

    if (dragonHealth <= 0) {
        cout << "The warriors have defeated the dragon!" << endl;
        cout << "Total effective damage dealt: " << totalDamage << endl;
    } else {
        cout << "The dragon survives with " << dragonHealth << " health left!" << endl;
        cout << "The warriors must retreat!" << endl;

        int retaliationDamage = dragonHealth / 10; 
        cout << "The dragon counterattacks and deals " << retaliationDamage << " damage to the warriors!" << endl;

        int warriorsDead = 0;
        for (int i = 0; i < numWarriors; i++) {
            if (retaliationDamage >= warriorHealth[i]) {
                warriorsDead++;
                retaliationDamage -= warriorHealth[i]; 
            } else {
                warriorHealth[i] -= retaliationDamage; 
                break;
            }
        }

        cout << warriorsDead << " warriors have died in the dragon's counterattack." << endl;
    }

    return 0;
}

Car Upgrade Management System

Car Upgrade
Car Upgrade
In a futuristic car modification shop, customers can enhance their vehicles with high-performance upgrades. The shop offers various modifications, each affecting specific aspects of the car, such as speed, acceleration, and fuel efficiency. Customers interact with a system that allows them to apply, remove, and track upgrades efficiently. The system keeps track of available modifications and their effects on the car’s performance. When a customer selects an upgrade, the program records the modification and updates the car’s attributes accordingly. If a modification is removed, the program adjusts the performance values back to their previous state. Additionally, customers can reset the car to its original condition, removing all modifications and restoring default values. At any time, the program can display the applied modifications, their respective costs, and the total performance enhancements. The system ensures that upgrades are applied logically, preventing duplicate selections or invalid modifications. The program runs continuously, allowing customers to experiment with different setups until they decide to exit. Write a C++ program that allows users to modify a car’s performance by applying, tracking, and removing upgrades while ensuring logical constraints. The program should allow users to view their selected modifications, reset all changes, and track the total cost efficiently. It should continue running until the user decides to exit.

Test Case
Input
Car Modification Menu:
1. Apply an Upgrade
2. Remove an Upgrade
3. View Applied Upgrades
4. Reset to Factory Settings
5. View Total Cost
6. Exit
Enter your choice: 1
Enter the number of the upgrade to apply: 1

Enter your choice: 1
Enter the number of the upgrade to apply: 2

Enter your choice: 3

Enter your choice: 2
Enter the number of the upgrade to remove: 2

Enter your choice: 3

Enter your choice: 5

Enter your choice: 3

Enter your choice: 6
Expected Output

Available Upgrades:
Engine Tuning ($500)
Turbocharging ($700)
Weight Reduction ($400)
Aerodynamics ($300)
Tire Upgrade ($350)

Engine Tuning has been applied.

Turbocharging has been applied.

Current Applied Upgrades:
Engine Tuning
Turbocharging

Applied Upgrades:
Engine Tuning ($500)
Turbocharging ($700)

Turbocharging has been removed.

Current Applied Upgrades:
Engine Tuning

Total cost of applied upgrades: $500

Car has been reset to factory settings.

Current Applied Upgrades:
No upgrades applied.

Exiting program. Thank you for using the Car Modification System!
  • The program starts by defining the available modifications in an array called upgrades.
  • Each modification has a corresponding cost, stored in the costs array.
  • A bool array named applied is used to track which upgrades have been selected by the user.
  • The program continuously runs inside a while loop until the user chooses to exit.
  • Inside this loop, a menu is displayed with options to apply upgrade, remove upgrade, reset to factory settings, view upgrades and view total cost.
  • The user is asked to enter a choice, which determines the program’s next action.
  • When the user selects the option to apply an upgrade, the program displays only the upgrades that have not been applied. The user inputs the number of the desired upgrade, and if the selection is valid, the program updates the applied array and adds the cost to totalCost.
  • If the user chooses to remove an upgrade, the program first checks if any upgrades have been applied. If there are applied upgrades, it displays them, allowing the user to remove one. The program then updates the applied array and subtracts the cost from totalCost.
  • The view upgrades option prints the list of currently applied upgrades. If none have been applied, the program informs the user.
  • The reset to factory settings option clears all modifications by setting the applied array to false for all upgrades and resetting totalCost to zero.
  • The total cost option displays the accumulated cost of all applied upgrades.
  • Finally, the exit option terminates the program.
#include <iostream>

using namespace std;

int main() {
    const int MAX_UPGRADES = 5;
    string upgrades[MAX_UPGRADES] = {"Engine Tuning", "Turbocharging", "Weight Reduction", "Aerodynamics", "Tire Upgrade"};
    int costs[MAX_UPGRADES] = {500, 700, 400, 300, 350};
    bool applied[MAX_UPGRADES] = {false};

    int totalCost = 0;
    int choice;

    while (true) {
        cout << "\nCar Modification Menu:\n";
        cout << "1. Apply an Upgrade\n";
        cout << "2. Remove an Upgrade\n";
        cout << "3. View Applied Upgrades\n";
        cout << "4. Reset to Factory Settings\n";
        cout << "5. View Total Cost\n";
        cout << "6. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        if (choice == 1) {
            cout << "\nAvailable Upgrades:\n";
            for (int i = 0; i < MAX_UPGRADES; i++) {
                if (!applied[i]) {
                    cout << i + 1 << ". " << upgrades[i] << " ($" << costs[i] << ")\n";
                }
            }
            cout << "Enter the number of the upgrade to apply: ";
            int upgradeChoice;
            cin >> upgradeChoice;

            if (upgradeChoice >= 1 && upgradeChoice <= MAX_UPGRADES && !applied[upgradeChoice - 1]) {
                applied[upgradeChoice - 1] = true;
                totalCost += costs[upgradeChoice - 1];
                cout << upgrades[upgradeChoice - 1] << " has been applied.\n";
            } else {
                cout << "Invalid choice or upgrade already applied.\n";
            }
        } 
        else if (choice == 2) {
            cout << "\nApplied Upgrades:\n";
            bool hasUpgrade = false;
            for (int i = 0; i < MAX_UPGRADES; i++) {
                if (applied[i]) {
                    cout << i + 1 << ". " << upgrades[i] << " ($" << costs[i] << ")\n";
                    hasUpgrade = true;
                }
            }

            if (!hasUpgrade) {
                cout << "No upgrades applied.\n";
                continue;
            }

            cout << "Enter the number of the upgrade to remove: ";
            int removeChoice;
            cin >> removeChoice;

            if (removeChoice >= 1 && removeChoice <= MAX_UPGRADES && applied[removeChoice - 1]) {
                applied[removeChoice - 1] = false;
                totalCost -= costs[removeChoice - 1];
                cout << upgrades[removeChoice - 1] << " has been removed.\n";
            } else {
                cout << "Invalid choice or upgrade not applied.\n";
            }
        } 
        else if (choice == 3) {
            cout << "\nCurrent Applied Upgrades:\n";
            bool hasUpgrade = false;
            for (int i = 0; i < MAX_UPGRADES; i++) {
                if (applied[i]) {
                    cout << "- " << upgrades[i] << "\n";
                    hasUpgrade = true;
                }
            }
            if (!hasUpgrade) {
                cout << "No upgrades applied.\n";
            }
        } 
        else if (choice == 4) {
            for (int i = 0; i < MAX_UPGRADES; i++) {
                applied[i] = false;
            }
            totalCost = 0;
            cout << "Car has been reset to factory settings.\n";
        } 
        else if (choice == 5) {
            cout << "Total cost of applied upgrades: $" << totalCost << "\n";
        } 
        else if (choice == 6) {
            cout << "Exiting program. Thank you for using the Car Modification System!\n";
            break;
        } 
        else {
            cout << "Invalid choice. Please enter a valid option.\n";
        }
    }
    return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top