Scenario-Based Coding Questions on Pointers in C++

This set of scenario-based coding questions focuses on using pointers in C++. These questions are designed to help you practice and get better at handling pointers in real-life situations. If you’ve already worked with operators, loops, if-else statements, and arrays, these questions will be a great way to build on that knowledge and challenge yourself with problems like managing inventories, swapping vault codes, and simulating battles. Perfect for anyone looking to improve their skills with pointers in C++

Swapping Bank Vault Codes

Two vaults, A and B, showing before and after number changes.
Vault’s Code Swapping
Imagine that you’re working as a technician for a security company that manages digital vaults for different banks. Each bank vault has a unique numeric access code. Due to a configuration error, the codes for Vault A and Vault B were saved incorrectly and each got the other’s code. Write a C++ program that takes two vault codes as input and swaps them using pointers.

Test Case 
Input
Enter access code for Vault A: 1234
Enter access code for Vault B: 5678
Expected Output
After swapping:
Vault A code: 5678
Vault B code: 1234
  • The program starts by asking the user to enter the access code for Vault A and Vault B. These inputs are saved in the variables vaultA and vaultB respectively.
  • Then, two pointer variables ptrA and ptrB are declared and assigned the addresses of vaultA and vaultB.
  • Next, a temporary variable temp is used to hold the value pointed to by ptrA.
  • The value at ptrA is then updated with the value pointed to by ptrB.
  • After that, the value at ptrB is updated with the value stored in temp.
  • Finally, the updated access codes for both Vault A and Vault B are displayed.
#include <iostream>
using namespace std;

int main() {
    int vaultA, vaultB;

    cout << "Enter access code for Vault A: ";
    cin >> vaultA;

    cout << "Enter access code for Vault B: ";
    cin >> vaultB;

    int* ptrA = &vaultA;
    int* ptrB = &vaultB;

    int temp = *ptrA;
    *ptrA = *ptrB;
    *ptrB = temp;

    cout << "\nAfter swapping:\n";
    cout << "Vault A code: " << vaultA << endl;
    cout << "Vault B code: " << vaultB << endl;

    return 0;
}

Locating Inventory Stock

An  electronics store that displays electronic items.
Electronics Store
Imagine that you’re managing a small electronics store. You have the stock count of two different products saved in memory. Your task is to find the memory address where each product’s stock is stored so you can track changes later on. Write a C++ program that takes the stock of two items and prints their memory addresses.

Test Case 
Input
Enter stock of item 1: 50
Enter stock of item 2: 75
Expected Output
Memory address of item 1 stock: 0x7fffec325d80
Memory address of item 2 stock: 0x7fffec325d84
  • The program starts by asking the user to enter the stock count of two items. These values are stored in variables stock1 and stock2.
  • Two pointers, ptr1 and ptr2, are created and initialized to point to the addresses of stock1 and stock2.
  • The program then uses the pointer variables to print the memory addresses of the two stock variables.
#include <iostream>
using namespace std;

int main() {
    int stock1, stock2;

    cout << "Enter stock of item 1: ";
    cin >> stock1;

    cout << "Enter stock of item 2: ";
    cin >> stock2;

    int* ptr1 = &stock1;
    int* ptr2 = &stock2;

    cout << "\nMemory address of item 1 stock: " << ptr1 << endl;
    cout << "Memory address of item 2 stock: " << ptr2 << endl;

    return 0;
}

Age Group Classification

Community event.
Community Event
Imagine you are organizing a community event and need to classify people into different age groups based on their ages. You need to group individuals into three categories: Children (0-12 years), Teenagers (13-19 years), and Adults (20+ years). Write a C++ program that uses pointers to store the ages of multiple people, classify them into the appropriate age group, and display the number of people in each group.

Test Case 
Input
Enter the number of people: 5
Enter age of person 1: 10
Enter age of person 2: 16
Enter age of person 3: 22
Enter age of person 4: 13
Enter age of person 5: 8
Expected Output
Children: 2
Teenagers: 2
Adults: 1
  • The program starts by asking the user to enter the number of people. This input is saved in the numPeople variable.
  • For each person, the program prompts the user to enter their age using a loop. These inputs are stored in the ages array using pointers to access the elements of the array.
  • The program then classifies each person into one of three groups (Children, Teenagers, or Adults) based on their age. This is done using an if-else statement.
  • The classification is done by dereferencing the pointer to check each person’s age and incrementing the respective group counter (Children, Teenagers, or Adults).
  • After processing all the people, the program displays the number of people in each group.
#include <iostream>
using namespace std;

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

    int ages[numPeople];
    int children = 0, teenagers = 0, adults = 0;
    int* ptr = ages;


    for (int i = 0; i < numPeople; i++) {
        cout << "Enter age of person " << i + 1 << ": ";
        cin >> *(ptr + i);
    }

    for (int i = 0; i < numPeople; i++) {
        if (*(ptr + i) >= 0 && *(ptr + i) <= 12) {
            children++;
        } else if (*(ptr + i) >= 13 && *(ptr + i) <= 19) {
            teenagers++;
        } else {
            adults++;
        }
    }

    cout << "Children: " << children << endl;
    cout << "Teenagers: " << teenagers << endl;
    cout << "Adults: " << adults << endl;

    return 0;
}

The Library Cataloging Challenge

A book cover with the title "The Great Gatsby" and total character count 14.
Book
Imagine you’re a catalog manager at a library. Every time a new book arrives, you’re given the title, and your task is to calculate the number of characters in that title, excluding spaces. You decide to use pointers to count the characters. Write a C++ program that takes the book title as input and calculates its length using pointers, then displays the total number of characters

Test Case 
Input
Enter the title of the book: The Great Gatsby
Expected Output
The length of the book title (excluding spaces) is: 14 characters.
  • The program starts by asking the user to enter the title of the book. This input is saved in the title array using the cin.getline() function, which ensures that the entire line, including spaces, is captured.
  • Next, a pointer ptr is initialized to point to the first character of the array.
  • The program then enters a while loop that continues as long as the pointer hasn’t reached the null terminator ('\0') of the string.
  • Inside the loop, the program checks if the current character pointed to by ptr is not a space. If it is not a space, the program increments the length variable by 1 to count the character.
  • The pointer is then moved to the next character by incrementing ptr. This process continues until all characters in the string are checked.
  • Finally, after the loop ends, the program prints out the total length of the book title, excluding spaces, by displaying the value of length.
#include <iostream>
using namespace std;

int main() {
    char title[100];
    char* ptr = title;
    int length = 0;

    cout << "Enter the title of the book: ";
    cin.getline(title, 100);

    while (*ptr != '\0') {
        if (*ptr != ' ') {
            length++;
        }
        ptr++;
    }

    cout << "The length of the book title (excluding spaces) is: " << length << " characters." << endl;

    return 0;
}

Temperature Converter

Celsius to Fahrenheit conversion
Celsius to Fahrenheit Conversion
Imagine you work at a weather forecasting station, and you’re tasked with converting temperature data from Celsius to Fahrenheit for a week’s weather report. Each day, you need to record the temperature in Celsius and convert it to Fahrenheit for the daily forecast. To make this process efficient, you decide to use pointers to access and manipulate the temperature data. Write a C++ program that takes the temperature in Celsius for 7 days as input, uses pointers to perform the conversion for each day, and displays the result in Fahrenheit for the entire week.

Test Case 
Input
Enter the temperature in Celsius for 7 days of the week:
Day 1: 32
Day 2: 50
Day 3: 68
Day 4: 86
Day 5: 104
Day 6: 122
Day 7: 140
Expected Output
The temperatures in Fahrenheit for the week are:
Day 1: 89.6 °F
Day 2: 122 °F
Day 3: 154.4 °F
Day 4: 186.8 °F
Day 5: 219.2 °F
Day 6: 251.6 °F
Day 7: 284 °F
  • The program starts by asking the user to input the temperature in Celsius for 7 days of the week. This input is saved in the celsius array.
  • The program uses a for loop to prompt the user to enter the temperature in Celsius for each day . These inputs are saved in the celsius array using the pointer ptrCelsius to access each element.
  • The program uses another for loop to traverse through the celsius array and calculates the corresponding Fahrenheit value for each day. The result is stored in the fahrenheit array.
  • The program calculates the temperature in Fahrenheit for each day using the formula: Fahrenheit = (Celsius×9/5)+32.
  • After calculating the Fahrenheit temperature for all 7 days, the program enters a final loop to display the Fahrenheit temperature for each day. It accesses the Fahrenheit values using the pointer ptrFahrenheit and prints the results for each day.
#include <iostream>
using namespace std;

int main() {
    float celsius[7], fahrenheit[7];
    float* ptrCelsius = celsius;
    float* ptrFahrenheit = fahrenheit;

    cout << "Enter the temperature in Celsius for 7 days of the week:\n";
    for (int i = 0; i < 7; i++) {
        cout << "Day " << i+1 << ": ";
        cin >> *(ptrCelsius + i);
    }

    for (int i = 0; i < 7; i++) {
        *(ptrFahrenheit + i) = (*(ptrCelsius + i) * 9 / 5) + 32;
    }

    cout << "\nThe temperatures in Fahrenheit for the week are:\n";
    for (int i = 0; i < 7; i++) {
        cout << "Day " << i+1 << ": " << *(ptrFahrenheit + i) << " °F" << endl;
    }

    return 0;
}

Shopping Cart Price Calculation

 A laptop showing a shopping cart with a message for 10% off on purchases over $100.
Shopping Cart
Imagine you’re developing an e-commerce platform, and you’re tasked with calculating the total cost of items in a user’s shopping cart. Each item has a price and a quantity, and the user can add multiple items to the cart. To make the calculations more efficient, you decide to use pointers to reference each item’s price and quantity directly, allowing for quicker calculations. Additionally, if the total price exceeds 100 units, a 10% discount should be applied. Write a C++ program that calculates the total price of the items in the cart, applies any applicable discount, and displays the final amount to the user.

Test Case 
Input
Enter the number of items in the cart: 3
Enter price for item 1: 50
Enter quantity for item 1: 2
Enter price for item 2: 30
Enter quantity for item 2: 1
Enter price for item 3: 20
Enter quantity for item 3: 3
Expected Output
Discount applied! Total after discount: 171

The program starts by asking the user to enter the number of items in the shopping cart. This input is saved in the n variable, which determines the size of the arrays for prices[] and quantities[].

For each item, the program prompts the user to enter the price and quantity of the item. These inputs are saved in the prices[] and quantities[] arrays, respectively. The program uses pointers (ptrPrices and ptrQuantities) to directly access and store the values for price and quantity.

Next, the program calculates the total price by iterating through each item. For each item, the program multiplies the price by the quantity and adds the result to totalPrice. Pointer arithmetic is used to access each value in the arrays via the pointers ptrPrices and ptrQuantities.

After calculating the total price, the program checks if the total price exceeds 100. If the total is greater than 100, the program applies a 10% discount by multiplying totalPrice by 0.9.

Finally, the program displays the total price.

#include <iostream>
using namespace std;

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

    double prices[n];   
    int quantities[n];  
    double totalPrice = 0.0;

    double* ptrPrices = prices;  
    int* ptrQuantities = quantities;

    for (int i = 0; i < n; i++) {
        cout << "Enter price for item " << i + 1 << ": ";
        cin >> *(ptrPrices + i);  

        cout << "Enter quantity for item " << i + 1 << ": ";
        cin >> *(ptrQuantities + i);
    }

    for (int i = 0; i < n; i++) {
        totalPrice += *(ptrPrices + i) * *(ptrQuantities + i);  
    }

    if (totalPrice > 100) {
        totalPrice *= 0.9;  
        cout << "Discount applied! Total after discount: ";
    } else {
        cout << "Total without discount: ";
    }

    cout << totalPrice << endl;

    return 0;
}

Travel Expense Tracker

A tropical island and airplane image with a message about calculating travel costs.
Travel Cost Calculation
Imagine you’re working as a travel coordinator for a travel agency. You need to track the expenses of customers for each trip they take. Each customer has multiple destinations, and for each destination, you need to record the cost of accommodation, meals, and transportation. You decide to use pointers to manage the expenses for each destination efficiently. Write a C++ program that stores the expenses for each customer. The program should allow the user to input the costs for accommodation, meals, and transportation for each destination and then calculate the total cost for each destination.

Test Case 
Input
Enter the number of destinations: 3
Enter costs for destination 1:
Accommodation: 100
Meals: 50
Transportation: 30
Enter costs for destination 2:
Accommodation: 150
Meals: 70
Transportation: 40
Enter costs for destination 3:
Accommodation: 200
Meals: 80
Transportation: 60
Expected Output
Total cost for destination 1: 180
Total cost for destination 2: 260
Total cost for destination 3: 340
Total travel expenses: 780
  • The program starts by asking the user to enter the number of destinations. This input is saved in the numDestinations variable.
  • For each destination, the program prompts the user to enter the accommodation cost, meals cost, and transportation cost using a for loop. These inputs are saved in the arrays accommodation[], meals[], and transportation[], respectively, using pointers.
  • Next, the program calculates the total cost for each destination by adding the accommodation, meals, and transportation costs. The calculation starts by accessing the values from the arrays using the pointer and adding them together.
  • The program then outputs the total cost for each destination by printing the sum of the three costs for each destination.
  • After calculating the total cost for each destination, the program calculates the total cost of all destinations into the totalCost variable.
  • Finally, the program displays the total travel expenses for all destinations.
#include <iostream>
using namespace std;

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

    float accommodation[numDestinations], meals[numDestinations], transportation[numDestinations];
    float* ptrAccommodation = accommodation;
    float* ptrMeals = meals;
    float* ptrTransportation = transportation;

    for (int i = 0; i < numDestinations; i++) {
        cout << "Enter costs for destination " << i + 1 << ":\n";
        cout << "Accommodation: ";
        cin >> *(ptrAccommodation + i);
        cout << "Meals: ";
        cin >> *(ptrMeals + i);
        cout << "Transportation: ";
        cin >> *(ptrTransportation + i);
    }

    float totalCost = 0;
    for (int i = 0; i < numDestinations; i++) {
        float destinationCost = *(ptrAccommodation + i) + *(ptrMeals + i) + *(ptrTransportation + i);
        cout << "\nTotal cost for destination " << i + 1 << ": " << destinationCost << endl;
        totalCost += destinationCost;
    }

    cout << "\nTotal travel expenses: " << totalCost << endl;

    return 0;
}

Parking Lot Availability Tracker

Parking lot spaces with numbers 2, 4, and 6.
Parking Lot
You’re managing a busy parking lot and need to keep track of which spaces are occupied and which are free. The parking lot has a set number of spaces, and as cars enter and leave, you need to update the status of each space. To make it easier and more efficient to check and update the status of parking spots, you decide to use pointers, allowing you to directly reference and modify each parking space without needing extra operations or memory overhead. Write a C++ program that takes the number of parking spaces as input, allows users to park or remove cars, and efficiently tracks the status of each parking space. The program should display the available spaces and update the parking status based on user input.

Test Case 
Input
Enter the number of parking spaces: 5
1. Parking Lot System
2. Park a car
3. Remove a car
4. Check available spaces
5. Exit
Enter your choice: 1
Enter the parking space number to park (1-5): 2

Enter your choice: 3

Enter your choice: 2
Enter the parking space number to remove the car from (1-5): 2

Enter your choice: 3

Enter your choice: 4
Expected Output
Car parked in space 2

Available spaces: 1 3 4 5

Car removed from space 2

Available spaces: 1 2 3 4 5
  • The program starts by asking the user to enter the number of parking spaces. This input is saved in the n variable, which is used to define the size of the parkingLot[] array.
  • Next, the program initializes all parking spaces as free (represented by false) using a for loop.
  • A pointer ptrParkingLot is then assigned to point to the parkingLot[] array.
  • The program then enters a do-while loop, which repeatedly displays a menu with the following options: park a car, remove a car, check available spaces, or exit the program.
  • When the user selects Park a car, the program asks for a space number. The program checks if the space is valid and free, and if so, it marks the space as occupied by updating the corresponding array element using pointer dereferencing (*(ptrParkingLot + space - 1)).
  • When the user selects Remove a car, the program asks for the space number again. It checks if the space is valid and occupied, and if so, it marks the space as free.
  • When the user selects Check available spaces, the program loops through the parkingLot[] array using pointers to display all free spaces by checking each space’s value.
  • After the user selects to exit, the program ends.
#include <iostream>
using namespace std;

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

    bool parkingLot[n]; 

    bool* ptrParkingLot = parkingLot; 

    for (int i = 0; i < n; i++) {
        *(ptrParkingLot + i) = false; 
    }

    int choice;
    do {
        cout << "\nParking Lot System\n";
        cout << "1. Park a car\n";
        cout << "2. Remove a car\n";
        cout << "3. Check available spaces\n";
        cout << "4. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        if (choice == 1) {
            int space;
            cout << "Enter the parking space number to park (1-" << n << "): ";
            cin >> space;
            if (space > 0 && space <= n && *(ptrParkingLot + space - 1) == false) {
                *(ptrParkingLot + space - 1) = true;  
                cout << "Car parked in space " << space << endl;
            } else {
                cout << "Invalid space or already occupied.\n";
            }
        } else if (choice == 2) {
            int space;
            cout << "Enter the parking space number to remove the car from (1-" << n << "): ";
            cin >> space;
            if (space > 0 && space <= n && *(ptrParkingLot + space - 1) == true) {
                *(ptrParkingLot + space - 1) = false;  
                cout << "Car removed from space " << space << endl;
            } else {
                cout << "Invalid space or empty space.\n";
            }
        } else if (choice == 3) {
            cout << "Available spaces: ";
            for (int i = 0; i < n; i++) {
                if (*(ptrParkingLot + i) == false) {  
                    cout << i + 1 << " ";  
                }
            }
            cout << endl;
        }

    } while (choice != 4);

    return 0;
}

Vehicle Fuel Tracker

A car rental shop with different cars displayed outside.
Rent a Car
You manage a fleet of rental vehicles, and your job is to track their fuel consumption over the course of a week. Each vehicle’s fuel usage can vary depending on factors like weather, traffic, or mechanical issues. The company has set a threshold of 20 liters per day so that if a vehicle exceeds this amount, it triggers a maintenance alert for a checkup. To handle the data efficiently, using pointers is essential. Pointers allow you to quickly access and modify the fuel consumption data for each vehicle, making the tracking process smoother and more efficient, especially when managing a large number of vehicles. Your task is to write a C++ program that tracks the fuel consumption of each vehicle for 7 days. The program should calculate the total fuel used by each vehicle, the average fuel consumption, and the total for the entire fleet. If any vehicle exceeds 20 liters on any day, the program should display a maintenance alert. Moreover, the program should ask the user if they want to input data for another week. If they choose ‘yes’, the program should allow them to enter data for the next week.

Test Case 
Input
Enter the number of vehicles in the fleet: 2
Enter fuel consumption for Vehicle 1:
Day 1: 10
Day 2: 15
Day 3: 30
Day 4: 10
Day 5: 20
Day 6: 12
Day 7: 8
Enter fuel consumption for Vehicle 2:
Day 1: 18
Day 2: 19
Day 3: 16
Day 4: 22
Day 5: 14
Day 6: 17
Day 7: 21
Expected Output
Warning: Vehicle 1 had high fuel consumption on Day 3 (more than 20 liters) – Maintenance Alert!
Total fuel consumed by Vehicle 1: 105 liters
Average fuel consumption for Vehicle 1: 15 liters/day
Max fuel consumed in a single day by Vehicle 1: 30 liters
Warning: Vehicle 2 had high fuel consumption on Day 4 (more than 20 liters) – Maintenance Alert!
Warning: Vehicle 2 had high fuel consumption on Day 7 (more than 20 liters) – Maintenance Alert!
Total fuel consumed by Vehicle 2: 127 liters
Average fuel consumption for Vehicle 2: 18.1429 liters/day
Max fuel consumed in a single day by Vehicle 2: 22 liters
Total fuel consumed by the fleet: 232 liters
Do you want to enter data for another week? (y/n): n

The program starts by asking the user to enter the number of vehicles in the fleet. This input is saved in the numVehicles variable.

For each vehicle, the program prompts the user to input the fuel consumption for each of the 7 days of the week. This is done using a for loop. The fuel consumption for each day is saved in a 2D array fuelConsumed[][], where each row represents a vehicle, and each column represents a day of the week. The pointer ptr is used to access each element of the array.

Next, the program calculates the total fuel consumed for each vehicle. For each vehicle, the program loops through the array and adds up the fuel consumption for all 7 days. The pointer is used to access each day’s fuel consumption, and the result is stored in the vehicleTotal variable.

While calculating the total fuel, the program checks if the fuel consumption for any day exceeds 20 liters. If it does, the program outputs a warning message, indicating that the vehicle may need maintenance.

The program then calculates the average fuel consumption for each vehicle by dividing the vehicleTotal by 7 . It displays the total fuel consumed, the average fuel consumption, and the maximum fuel consumed in a single day for each vehicle.

After processing all vehicles, the program calculates the total fuel consumed by the entire fleet. This is done by summing up the total fuel consumed by each vehicle and storing it in the totalFleetFuel variable.

Finally, the program displays the total fuel consumed by the fleet and asks the user if they want to input data for another week.

If the user chooses ‘y’ or ‘Y’, the program will run again; otherwise, it exits.

#include <iostream>
using namespace std;

int main() {
    int numVehicles;
    char choice;

    do {
        cout << "Enter the number of vehicles in the fleet: ";
        cin >> numVehicles;

        float fuelConsumed[numVehicles][7];
        float* ptr;
        float totalFleetFuel = 0;

        for (int i = 0; i < numVehicles; i++) {
            cout << "\nEnter fuel consumption for Vehicle " << i + 1 << ":\n";
            ptr = fuelConsumed[i];  
            for (int j = 0; j < 7; j++) {
                cout << "Day " << j + 1 << ": ";
                cin >> *(ptr + j);
            }
        }

        for (int i = 0; i < numVehicles; i++) {
            float vehicleTotal = 0;
            float vehicleMax = 0;
            ptr = fuelConsumed[i];  

            for (int j = 0; j < 7; j++) {
                vehicleTotal += *(ptr + j);
                if (*(ptr + j) > vehicleMax) vehicleMax = *(ptr + j);  
                if (*(ptr + j) > 20) {
                    cout << "\nWarning: Vehicle " << i + 1 << " had high fuel consumption on Day " << j + 1 << " (more than 20 liters) - Maintenance Alert!\n";
                }
            }

            float averageConsumption = vehicleTotal / 7;
            cout << "\nTotal fuel consumed by Vehicle " << i + 1 << ": " << vehicleTotal << " liters";
            cout << "\nAverage fuel consumption for Vehicle " << i + 1 << ": " << averageConsumption << " liters/day";
            cout << "\nMax fuel consumed in a single day by Vehicle " << i + 1 << ": " << vehicleMax << " liters\n";

            totalFleetFuel += vehicleTotal;
        }

        cout << "\nTotal fuel consumed by the fleet: " << totalFleetFuel << " liters\n";

        cout << "\nDo you want to enter data for another week? (y/n): ";
        cin >> choice;

    } while (choice == 'y' || choice == 'Y');

    return 0;
}

Word Guessing Game

A word puzzle with the letters "W-O-R-D" and a question mark.
Word Guessing Game
You’re playing a word guessing game. Each time, the word is shown as a series of blanks, and you have to guess one letter at a time. You have a limited number of attempts, and each wrong guess reduces the number of attempts. The game ends when you either guess the word correctly or run out of attempts. Write a C++ program that asks for the hidden word and the maximum number of attempts. For each guess, the program should update the word’s state and display the remaining attempts. The game will let you know if you’ve guessed the word correctly or if you’ve lost after running out of attempts.

Test Case 
Input
Enter the hidden word: programming
Enter the maximum number of attempts: 5

You have 5 attempts to guess the word.
Current word: _ _ _ _ _ _ _ _ _ _ _
Guess a letter: p

Current word: p _ _ _ _ _ _ _ _ _ _
Guess a letter: r

Current word: p r _ _ r _ _ _ _ _ _
Guess a letter: o

Current word: p r o _ r _ _ _ _ _ _
Guess a letter: g

Current word: p r o g r _ _ _ _ _ g
Guess a letter: a

Current word: p r o g r a _ _ _ _ g
Guess a letter: m

Current word: p r o g r a m m _ _ g
Guess a letter: i

Current word: p r o g r a m m i _ g
Guess a letter: b

Current word: p r o g r a m m i _ g
Guess a letter: n

Expected Output
Welcome to the Word Guessing Game!
Good guess!
Good guess!
Good guess!
Good guess!
Good guess!
Good guess!
Good guess!
Incorrect guess! You have 4 attempts left.
Good guess!
Congratulations! You’ve guessed the word: programming
  • The program starts by asking the user to enter the hidden word. This input is saved in the hiddenWord variable.
  • After the hidden word is entered, the program calculates the length of the word using a for loop and pointer arithmetic. It iterates through each character in hiddenWord[] until it reaches the null terminator (\0), and the length of the word is stored in the wordLength variable.
  • Next, the program initializes the guessedWord[] array, which will be used to track the current guessed state of the word. Initially, the array is filled with underscores (_), representing letters that are yet to be guessed.
  • A pointer ptrGuessedWord is used to access and modify the contents of the guessedWord[] array.
  • The program then prompts the user to input the maximum number of attempts the player will have to guess the word. This input is saved in the maxAttempts variable.
  • At this point, the program enters the main game loop, where the player will make guesses. The loop continues as long as the player has remaining attempts and has not yet guessed the word correctly.
  • Inside the loop, the program displays the current state of the guessed word. It uses a pointer to display the guessedWord[] array, where each underscore represents an unguessed letter.
  • After displaying the current guessed word, the program prompts the player to guess a letter.
  • The program checks if the guessed letter is present in the hidden word by iterating through each character of hiddenWord[] using pointer arithmetic.
  • If the guessed letter is found in hiddenWord[] and the corresponding position in guessedWord[] is still an underscore (_), the program updates the guessed word by replacing the underscore with the guessed letter. A boolean flag correctGuess is set to true if the guess is correct.
  • If the guess is correct, the program prints a message saying “Good guess!”. If the guess is incorrect, the program decreases the number of attempts left by 1 and displays a message saying “Incorrect guess! You have X attempts left.”
  • After each guess, the program checks if the word has been completely guessed. It does this by scanning through the guessedWord[] array and looking for any remaining underscores.
  • If no underscores are left, the word is considered completely guessed.
  • Once the game loop ends, the program displays the final result.
  • If the word is guessed correctly, it prints “Congratulations! You’ve guessed the word.”
  • If the player runs out of attempts, the program prints “Game Over! The correct word was: [hidden word].”
  • This process continues until either the word is guessed or the player runs out of attempts.
#include <iostream>
using namespace std;

int main() {
    string hiddenWord;
    cout << "Enter the hidden word: ";
    cin >> hiddenWord;

    int wordLength = 0;
    const char* ptrHiddenWord = &hiddenWord[0]; 
    while (*ptrHiddenWord != '\0') {
        wordLength++;
        ptrHiddenWord++;  
    }

    char guessedWord[wordLength];  
    char* ptrGuessedWord = guessedWord;  

    for (int i = 0; i < wordLength; i++) {
        *(ptrGuessedWord + i) = '_';
    }

    int maxAttempts;  
    cout << "Enter the maximum number of attempts: ";
    cin >> maxAttempts;

    int attemptsLeft = maxAttempts;
    bool wordGuessed = false;

    cout << "Welcome to the Word Guessing Game!" << endl;
    cout << "You have " << attemptsLeft << " attempts to guess the word." << endl;

    ptrHiddenWord = &hiddenWord[0];  

    while (attemptsLeft > 0 && !wordGuessed) {
        cout << "\nCurrent word: ";
        for (int i = 0; i < wordLength; i++) {
            cout << *(ptrGuessedWord + i) << " ";  
        }
        cout << endl;

        cout << "Guess a letter: ";
        char guess;
        cin >> guess;

        bool correctGuess = false;

        for (int i = 0; i < wordLength; i++) {
            if (*(ptrHiddenWord + i) == guess && *(ptrGuessedWord + i) == '_') {
                *(ptrGuessedWord + i) = guess; 
                correctGuess = true;
            }
        }

        if (correctGuess) {
            cout << "Good guess!" << endl;
        } else {
            attemptsLeft--;
            cout << "Incorrect guess! You have " << attemptsLeft << " attempts left." << endl;
        }

        wordGuessed = true;
        for (int i = 0; i < wordLength; i++) {
            if (*(ptrGuessedWord + i) == '_') {
                wordGuessed = false;
                break;
            }
        }
    }

    if (wordGuessed) {
        cout << "\nCongratulations! You've guessed the word: ";
        for (int i = 0; i < wordLength; i++) {
            cout << *(ptrGuessedWord + i);  
        }
        cout << endl;
    } else {
        cout << "\nGame Over! The correct word was: ";
        for (int i = 0; i < wordLength; i++) {
            cout << *(ptrHiddenWord + i); 
        }
        cout << endl;
    }

    return 0;
}

Dragon Battle Simulator

Two dragons with different health, attack, and defense values.
Dragon Battle
Imagine you’re creating a Dragon Battle Simulator for a fantasy game where each dragon has several attributes such as Health Points (HP), Attack Power, and Defense. You need to simulate a battle between two dragons using only pointers for all calculations and updates. The damage dealt by each dragon is calculated based on the difference between the attacking dragon’s attack power and the defending dragon’s defense. The battle continues until one dragon’s HP drops to zero or below, and the program should display the progress of the battle after each attack. Write a C++ program that takes the attributes of the dragons as input (Health Points, Attack Power, and Defense), simulates the battle between the dragons and displays the progress of the battle with each turn, showing the remaining health of each dragon and announcing when a dragon is defeated.

Test Case 
Input
Enter Dragon 1 Health Points: 100
Enter Dragon 1 Attack Power: 40
Enter Dragon 1 Defense: 20
Enter Dragon 2 Health Points: 120
Enter Dragon 2 Attack Power: 50
Enter Dragon 2 Defense: 30
Expected Output
Welcome to the Dragon Battle Simulator!
Dragon 1 attacks Dragon 2 for 10 damage!
Dragon 2 attacks Dragon 1 for 30 damage!
Dragon 1 Health: 70, Dragon 2 Health: 110
Turns remaining: 9
Dragon 1 attacks Dragon 2 for 10 damage!
Dragon 2 attacks Dragon 1 for 30 damage!
Dragon 1 Health: 40, Dragon 2 Health: 100
Turns remaining: 8
Dragon 1 attacks Dragon 2 for 10 damage!
Dragon 2 attacks Dragon 1 for 30 damage!
Dragon 1 Health: 10, Dragon 2 Health: 90
Turns remaining: 7
Dragon 1 attacks Dragon 2 for 10 damage!
Dragon 2 attacks Dragon 1 for 30 damage!
Dragon 1 Health: -20, Dragon 2 Health: 80
Turns remaining: 6
Dragon 1 is defeated!
  • The program starts by asking the user to enter the Health Points (HP), Attack Power, and Defense for Dragon 1. These inputs are saved in the hp1, attack1, and def1 variables, respectively.
  • Similarly, the program prompts the user to enter the Health Points (HP), Attack Power, and Defense for Dragon 2, saving these values in the hp2, attack2, and def2 variables.
  • Next, the program sets up pointers for both dragons to refer to their health, attack power, and defense attributes. These pointers (ptrHp1, ptrAttack1, ptrDef1 for Dragon 1 and ptrHp2, ptrAttack2, ptrDef2 for Dragon 2) allow direct access to modify and track the dragons attributes during the battle.
  • The program then enters the main battle loop, which simulates the battle for a maximum of 10 turns (maxAttempts = 10). The loop continues as long as the dragons are still alive and there are remaining attempts.
  • In each turn, the program calculates the damage dealt by both dragons.
  • The damage dealt by Dragon 1 is calculated as the difference between its attack power (attack1) and Dragon 2’s defense (def2).
  • The damage dealt by Dragon 2 is similarly calculated as the difference between its attack power (attack2) and Dragon 1’s defense (def1).
  • If the calculated damage is greater than 0, it is applied to the opponent’s health. The program updates the dragons’ health using pointer dereferencing (*ptrHp1 and *ptrHp2).
  • After each turn, the program displays the damage dealt by both dragons and updates the remaining health of each dragon. If either dragon’s health drops to zero or below, the battle ends early.
  • At the end of the battle, the program checks the health of both dragons.
  • If Dragon 1’s health is zero or below, it announces Dragon 1 is defeated.
  • If Dragon 2’s health is zero or below, it announces Dragon 2 is defeated.
  • If both dragons are still alive after 10 turns, it announces the battle is a draw.
#include <iostream>
using namespace std;

int main() {
    int hp1, attack1, def1;
    cout << "Enter Dragon 1 Health Points: ";
    cin >> hp1;
    cout << "Enter Dragon 1 Attack Power: ";
    cin >> attack1;
    cout << "Enter Dragon 1 Defense: ";
    cin >> def1;

    int hp2, attack2, def2;
    cout << "Enter Dragon 2 Health Points: ";
    cin >> hp2;
    cout << "Enter Dragon 2 Attack Power: ";
    cin >> attack2;
    cout << "Enter Dragon 2 Defense: ";
    cin >> def2;

    int* ptrHp1 = &hp1;
    int* ptrAttack1 = &attack1;
    int* ptrDef1 = &def1;
    int* ptrHp2 = &hp2;
    int* ptrAttack2 = &attack2;
    int* ptrDef2 = &def2;

    int maxAttempts = 10; 
    int attemptsLeft = maxAttempts;

    cout << "Welcome to the Dragon Battle Simulator!" << endl;

    while (attemptsLeft > 0 && *ptrHp1 > 0 && *ptrHp2 > 0) {
        int damage1 = *ptrAttack1 - *ptrDef2;
        int damage2 = *ptrAttack2 - *ptrDef1;

        if (damage1 > 0) {
            *ptrHp2 -= damage1;  
        } else {
            damage1 = 0; 
        }

        if (damage2 > 0) {
            *ptrHp1 -= damage2; 
        } else {
            damage2 = 0; 
        }

        cout << "Dragon 1 attacks Dragon 2 for " << damage1 << " damage!" << endl;
        cout << "Dragon 2 attacks Dragon 1 for " << damage2 << " damage!" << endl;
        cout << "Dragon 1 Health: " << *ptrHp1 << ", Dragon 2 Health: " << *ptrHp2 << endl;

        attemptsLeft--;
        cout << "Turns remaining: " << attemptsLeft << endl;
    }

    if (*ptrHp1 <= 0) {
        cout << "Dragon 1 is defeated!" << endl;
    } else if (*ptrHp2 <= 0) {
        cout << "Dragon 2 is defeated!" << endl;
    } else {
        cout << "Battle ends with no dragons defeated!" << endl;
    }

    return 0;
}

Zoo Animal Population Tracker

Information about elephants and tigers, including their population, diet, and age group.
Zoo Animals
You are tasked with developing a Zoo Animal Population Tracker for a zoo management system. This system helps track the various species of animals in the zoo, including their species name, population, diet type (e.g., carnivore, herbivore, omnivore), and age group (e.g., juvenile, adult, senior). The system should allow the zoo manager to perform operations such as adding new species, removing species, modifying the diet or age group, and displaying the current species information. Write a C++ program that takes the species name, population, diet type, and age group of a species as input. The program should allow the zoo manager to add animals to an existing species, remove animals from a species, change the diet or age group of a species, and display the current species information, including the species name, population, diet type, and age group, using pointers to manage the data efficiently.

Test Case 
Input
Zoo Animal Population Tracker
1. Add species
2. Remove species
3. Change species diet
4. Change species age group
5. Display species
6. Exit
Enter your choice: 1
Enter species name: Tiger
Enter species population: 10
Enter species diet (Carnivore, Herbivore, Omnivore): Carnivore
Enter species age group (Juvenile, Adult, Senior): Adult

Enter your choice: 1
Enter species name: Elephant
Enter species population: 5
Enter species diet (Carnivore, Herbivore, Omnivore): Herbivore
Enter species age group (Juvenile, Adult, Senior): Adult

Enter your choice: 5

Enter your choice: 2
Enter species name to remove: Elephant

Enter your choice: 5

Enter your choice: 3
Enter species name to change diet: Tiger
Enter new diet type (Carnivore, Herbivore, Omnivore): Omnivore

Enter your choice: 4
Enter species name to change age group: Tiger
Enter new age group (Juvenile, Adult, Senior): Senior

Enter your choice: 5

Enter your choice: 6
Expected Output
Species List:
Species Name: Tiger, Population: 10, Diet: Carnivore, Age Group: Adult
Species Name: Elephant, Population: 5, Diet: Herbivore, Age Group: Adult

Species List:
Species Name: Tiger, Population: 10, Diet: Carnivore, Age Group: Adult

Species List:
Species Name: Tiger, Population: 10, Diet: Omnivore, Age Group: Senior
  • The program begins by displaying a menu with several options, including adding, removing, or modifying species in the zoo. The program starts with no species in the zoo, and the speciesCount variable is initialized to zero.
  • If the user selects the Add species option, the program will prompt the user to input the species name, population, diet type, and age group.
  • These values are then stored in the corresponding arrays (speciesNames[], speciesPopulations[], speciesDietTypes[], and speciesAgeGroups[]). The pointer arithmetic is used to insert the data at the current index of each array.
  • The speciesCount is then incremented.
  • If the user selects the Remove species option, the program will prompt for the name of the species to remove. It will then check if the species exists in the speciesNames[] array.
  • If found, the program will shift all data of subsequent species to the left using pointer indexing to fill the gap left by the removed species.
  • The speciesCount is then decremented.
  • If the user selects the Change diet type option, the program will ask for the species name and the new diet type.
  • The program will locate the species in the speciesNames[] array and update the corresponding index in the speciesDietTypes[] array using pointer dereferencing.
  • Similarly, if the user selects the Change age group option, the program will prompt for the species name and the new age group, and it will update the respective index in the speciesAgeGroups[] array using pointers.
  • If the user selects the Display species option, the program will display the species details, including the name, population, diet type, and age group of all species currently in the zoo. The program uses pointer arithmetic to access and display the data from the arrays. It loops through each array and dereferences the pointer to display the current values.
#include <iostream>
using namespace std;

int main() {
    const int MAX_SPECIES = 5; 
    int speciesCount = 0;  

    string speciesNames[MAX_SPECIES];
    int speciesPopulations[MAX_SPECIES];
    string speciesDietTypes[MAX_SPECIES];
    string speciesAgeGroups[MAX_SPECIES];

    string* ptrSpeciesNames = speciesNames;
    int* ptrSpeciesPopulations = speciesPopulations;
    string* ptrSpeciesDietTypes = speciesDietTypes;
    string* ptrSpeciesAgeGroups = speciesAgeGroups;

    while (true) {
        int choice;
        cout << "\nZoo Animal Population Tracker\n";
        cout << "1. Add species\n";
        cout << "2. Remove species\n";
        cout << "3. Change species diet\n";
        cout << "4. Change species age group\n";
        cout << "5. Display species\n";
        cout << "6. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        if (choice == 1) {
            if (speciesCount >= MAX_SPECIES) {
                cout << "Zoo is full! Cannot add more species.\n";
                continue;
            }

            cout << "Enter species name: ";
            cin >> *(ptrSpeciesNames + speciesCount);
            cout << "Enter species population: ";
            cin >> *(ptrSpeciesPopulations + speciesCount);
            cout << "Enter species diet (Carnivore, Herbivore, Omnivore): ";
            cin >> *(ptrSpeciesDietTypes + speciesCount);
            cout << "Enter species age group (Juvenile, Adult, Senior): ";
            cin >> *(ptrSpeciesAgeGroups + speciesCount);

            speciesCount++;
        } 
        else if (choice == 2) {
            string speciesToRemove;
            cout << "Enter species name to remove: ";
            cin >> speciesToRemove;

            bool speciesFound = false;
            for (int i = 0; i < speciesCount; i++) {
                if (*(ptrSpeciesNames + i) == speciesToRemove) {
                    speciesFound = true;
                    for (int j = i; j < speciesCount - 1; j++) {
                        *(ptrSpeciesNames + j) = *(ptrSpeciesNames + j + 1);
                        *(ptrSpeciesPopulations + j) = *(ptrSpeciesPopulations + j + 1);
                        *(ptrSpeciesDietTypes + j) = *(ptrSpeciesDietTypes + j + 1);
                        *(ptrSpeciesAgeGroups + j) = *(ptrSpeciesAgeGroups + j + 1);
                    }
                    speciesCount--;
                    break;
                }
            }
            if (!speciesFound) {
                cout << "Species not found!\n";
            }
        } 
        else if (choice == 3) {
            string speciesToChange;
            cout << "Enter species name to change diet: ";
            cin >> speciesToChange;

            bool speciesFound = false;
            for (int i = 0; i < speciesCount; i++) {
                if (*(ptrSpeciesNames + i) == speciesToChange) {
                    speciesFound = true;
                    cout << "Enter new diet type (Carnivore, Herbivore, Omnivore): ";
                    cin >> *(ptrSpeciesDietTypes + i);
                    break;
                }
            }
            if (!speciesFound) {
                cout << "Species not found!\n";
            }
        } 
        else if (choice == 4) {
            string speciesToChange;
            cout << "Enter species name to change age group: ";
            cin >> speciesToChange;

            bool speciesFound = false;
            for (int i = 0; i < speciesCount; i++) {
                if (*(ptrSpeciesNames + i) == speciesToChange) {
                    speciesFound = true;
                    cout << "Enter new age group (Juvenile, Adult, Senior): ";
                    cin >> *(ptrSpeciesAgeGroups + i);
                    break;
                }
            }
            if (!speciesFound) {
                cout << "Species not found!\n";
            }
        } 
        else if (choice == 5) {
            cout << "\nSpecies List:\n";
            for (int i = 0; i < speciesCount; i++) {
                cout << "Species Name: " << *(ptrSpeciesNames + i) << ", ";
                cout << "Population: " << *(ptrSpeciesPopulations + i) << ", ";
                cout << "Diet: " << *(ptrSpeciesDietTypes + i) << ", ";
                cout << "Age Group: " << *(ptrSpeciesAgeGroups + i) << endl;
            }
        } 
        else if (choice == 6) {
            break;  
        } 
        else {
            cout << "Invalid choice. Please try again.\n";
        }
    }

    return 0;
}

Sorting Character Names for a Game

Three game characters sorted by names.
Game Characters
Imagine you are developing a fantasy role-playing game where players can create and customize their characters. Each player gives their character a name during the game setup, and the game maintains a leaderboard to showcase the top players. The leaderboard displays the characters’ names in alphabetical order, but since names can be entered in any random order, you need to sort the list. To enhance the efficiency of the system, you decide to implement a C++ program that takes the names of characters as input and sorts these character names in alphabetical order using pointer arithmetic.

Test Case 
Input
Enter the number of players: 5
Enter the names of the players:
Maya
Max
Alice
Eve
Charlie
Expected Output
Sorted Player Names:
Alice
Charlie
Eve
Max
Maya
  • The program starts by asking the user to input the number of players. This input is saved in the numPlayers variable.
  • Next, the program creates array playerNames[10] to store the names of the players. A pointer ptrPlayerNames is then declared, which points to the first element of the playerNames array.
  • The program then proceeds to take the player names as input. It uses the pointer ptrPlayerNames to assign each player’s name to the array using pointer dereferencing (*(ptrPlayerNames + i)).
  • After collecting the names, the program sorts the player names in alphabetical order using Bubble Sort.
  • It compares each adjacent pair of names in the array by dereferencing the pointer and swaps the names if they are out of order.
  • This sorting process continues through all the elements using pointer arithmetic.
  • Once the names are sorted, the program displays the sorted names by looping through the array and printing each name using the pointer ptrPlayerNames and pointer dereferencing (*(ptrPlayerNames + i)).
#include <iostream>
using namespace std;

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

    string playerNames[10];
    string* ptrPlayerNames = playerNames;

    cout << "Enter the names of the players:\n";
    for (int i = 0; i < numPlayers; i++) {
        cin >> *(ptrPlayerNames + i);
    }

    for (int i = 0; i < numPlayers - 1; i++) {
        for (int j = 0; j < numPlayers - i - 1; j++) {
            if (*(ptrPlayerNames + j) > *(ptrPlayerNames + j + 1)) {
                string temp = *(ptrPlayerNames + j);
                *(ptrPlayerNames + j) = *(ptrPlayerNames + j + 1);
                *(ptrPlayerNames + j + 1) = temp;
            }
        }
    }

    cout << "\nSorted Player Names:\n";
    for (int i = 0; i < numPlayers; i++) {
        cout << *(ptrPlayerNames + i) << endl;
    }

    return 0;
}

PSL Match Points Tracker

PSL Trophy.
PSL Trophy
Imagine you’re in charge of tracking the statistics for the Pakistan Super League (PSL), a prestigious cricket tournament that initially features six teams. However, in this scenario, Multan Sultans and Quetta Gladiators have already been knocked out, leaving only four teams in the running: Islamabad United, Lahore Qalandars, Karachi Kings and Peshawar Zalmi. The remaining teams will play in the semi-final matches, and the winners will advance to the final to compete for the championship. For each match, the program takes the runs scored and wickets lost by both teams as input. The team with the higher runs wins the match and earns 2 points, and if a match ends in a tie, both teams receive 1 point. The program keeps track of the points for each team after every match and determines the final winner based on the highest points accumulated. Write a C++ program that takes the runs scored and wickets lost for each match as input, keeps track of the points for each team, and outputs the final winner of the tournament using pointers.

Test Case 
Input
Semi-Final:
Match between Islamabad United and Karachi Kings:
Enter runs scored by Islamabad United: 160
Enter wickets lost by Islamabad United: 6
Enter runs scored by Karachi Kings: 150
Enter wickets lost by Karachi Kings: 7
Islamabad United wins the match!

Match between Lahore Qalandars and Peshawar Zalmi:
Enter runs scored by Lahore Qalandars: 140
Enter wickets lost by Lahore Qalandars: 8
Enter runs scored by Peshawar Zalmi: 145
Enter wickets lost by Peshawar Zalmi: 7
Peshawar Zalmi wins the match!

Final:
Match between Peshawar Zalmi and Islamabad United:
Enter runs scored by Peshawar Zalmi: 170
Enter wickets lost by Peshawar Zalmi: 5
Enter runs scored by Islamabad United: 160
Enter wickets lost by Islamabad United: 6
Peshawar Zalmi wins the match!
Expected Output
Final Points Standing:
Islamabad United: 2 points
Karachi Kings: 0 points
Lahore Qalandars: 0 points
Peshawar Zalmi: 4 points
Winner: Peshawar Zalmi with 4 points!

The program begins by defining two arrays, one for the team names (teamNames[]) and another for their points (teamPoints[]).

The teamNames[] array stores the names of four cricket teams: Islamabad United, Karachi Kings, Lahore Qalandars, and Peshawar Zalmi, while teamPoints[] is initialized with zero points for each team.

Pointers, teamNamesPtr and teamPointsPtr, are then assigned to point to the respective arrays.

The semi-final phase starts, where two semi-final matches are played. The program runs a loop for two matches, and in each match:

The names of the two teams are retrieved using the pointers teamNamesPtr with pointer arithmetic *(teamNamesPtr + 2*i) and *(teamNamesPtr + 2*i + 1).

The user is prompted to input the runs and wickets for both teams in the match.

The program compares the runs of both teams and awards 2 points to the winning team, while the losing team gets 0 points.

If the match is a draw (when the runs are equal), both teams receive 1 point.

After the semi-finals, the program proceeds to the final match.

The semi-final winners are determined and the teams are selected for the final using the semiFinalWinner variable which stores the index of the winning team in each semi-final.

The winner of the final match is determined by comparing the runs scored by the teams, and the winner is awarded 2 points.

Finally, the program displays the final points standings. It uses pointer arithmetic to loop through each team and print their name and points.

The program also finds the team with the highest points and declares it as the tournament winner. If no team has earned points, the program announces that the tournament ended in a draw.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string teamNames[4] = {
        "Islamabad United", 
        "Karachi Kings", 
        "Lahore Qalandars", 
        "Peshawar Zalmi"
    };
    
    int teamPoints[4] = {0, 0, 0, 0};

    string* teamNamesPtr = teamNames;
    int* teamPointsPtr = teamPoints;

    cout << "\nSemi-Final:\n";
    int semiFinalWinner = -1;
    for (int i = 0; i < 2; ++i) { 
        string team1 = *(teamNamesPtr + 2*i);
        string team2 = *(teamNamesPtr + 2*i + 1);
        int runs1, wickets1, runs2, wickets2;

        cout << "\nMatch between " << team1 << " and " << team2 << ":\n";
        cout << "Enter runs scored by " << team1 << ": ";
        cin >> runs1;
        cout << "Enter wickets lost by " << team1 << ": ";
        cin >> wickets1;

        cout << "Enter runs scored by " << team2 << ": ";
        cin >> runs2;
        cout << "Enter wickets lost by " << team2 << ": ";
        cin >> wickets2;

        if (runs1 > runs2) {
            cout << team1 << " wins the match!\n";
            *(teamPointsPtr + 2*i) += 2;  
            semiFinalWinner = 2*i;        
        } else if (runs2 > runs1) {
            cout << team2 << " wins the match!\n";
            *(teamPointsPtr + 2*i + 1) += 2;  
            semiFinalWinner = 2*i + 1;        
        } else {
            cout << "The match is a draw!\n";
            *(teamPointsPtr + 2*i) += 1;
            *(teamPointsPtr + 2*i + 1) += 1;
        }
    }

    cout << "\nFinal:\n";
    string team1 = *(teamNamesPtr + semiFinalWinner);
    string team2 = *(teamNamesPtr + 3 - semiFinalWinner); 
    int runs1, wickets1, runs2, wickets2;

    cout << "\nMatch between " << team1 << " and " << team2 << ":\n";
    cout << "Enter runs scored by " << team1 << ": ";
    cin >> runs1;
    cout << "Enter wickets lost by " << team1 << ": ";
    cin >> wickets1;

    cout << "Enter runs scored by " << team2 << ": ";
    cin >> runs2;
    cout << "Enter wickets lost by " << team2 << ": ";
    cin >> wickets2;

    if (runs1 > runs2) {
        cout << team1 << " wins the match!\n";
        *(teamPointsPtr + semiFinalWinner) += 2;  
    } else if (runs2 > runs1) {
        cout << team2 << " wins the match!\n";
        *(teamPointsPtr + 3 - semiFinalWinner) += 2;  
    } else {
        cout << "The match is a draw!\n";
        *(teamPointsPtr + semiFinalWinner) += 1; 
        *(teamPointsPtr + 3 - semiFinalWinner) += 1;  
    }

    cout << "\nFinal Points Standing:\n";
    int maxPoints = 0;
    string winner;
    for (int i = 0; i < 4; ++i) {
        cout << *(teamNamesPtr + i) << ": " << *(teamPointsPtr + i) << " points\n";
        if (*(teamPointsPtr + i) > maxPoints) {
            maxPoints = *(teamPointsPtr + i);
            winner = *(teamNamesPtr + i);
        }
    }

    if (maxPoints > 1) {
        cout << "\nWinner: " << winner << " with " << maxPoints << " points!\n";
    } else {
        cout << "\nThe tournament ended in a draw.\n";
    }

    return 0;
}

Computer Shop

A computer shop with a sign and items on display.
Computer Shop
Imagine you are working at a computer hardware store that sells various PC parts, including CPUs, motherboards, RAM, graphic cards, and storage devices. The store manager needs a system to effectively manage the inventory, which includes keeping track of the part ID, name, price, stock quantity, category, and minimum stock level for each part. The system should allow the manager to perform operations such as adding new parts to the inventory, selling parts which will reduce the stock quantity, restocking parts when the inventory falls below a certain threshold, displaying the current inventory to show the details of each part, and removing parts from the inventory when their stock reaches zero. By using pointers, the program should efficiently manage the data, ensuring quick and accurate updates to the inventory as these operations are performed. Write a C++ program that takes the details of the parts as input, allows the manager to perform the operations, and displays the updated inventory

Test Case 
Input
===== PC Modification Inventory Tracker =====
1. Add a new part
2. Sell a part
3. Restock a part
4. Display inventory
5. Remove a part
6. Exit
Enter your choice: 1
Enter part ID: 101
Enter part name: Intel i7 Processor
Enter part price: 300
Enter part stock quantity: 10
Enter part category (e.g., CPU, RAM, GPU, etc.): CPU
Enter minimum stock level: 2

Enter your choice: 2
Enter part ID to sell: 101
Enter quantity to sell: 3

Enter your choice: 3
Enter part ID to restock: 101
Enter quantity to restock: 10

Enter your choice: 4

Enter your choice: 6

Expected Output
Part added successfully.

Sold 3 of Intel i7 Processor. Remaining stock: 7

Restocked 10 of Intel i7 Processor. New stock: 17

Current Inventory:
Part ID: 101, Name: Intel i7 Processor, Price: 300, Stock: 17, Category: CPU, Minimum Stock Level: 2

Exiting the program.
  • The program starts by defining arrays for storing part details like ID, name, price, stock, category, and minimum stock level.
  • The arrays are initialized to hold data for a maximum of 5 parts, and the program uses pointers to access and manipulate these arrays.
  • Next, the program presents a menu-driven system using a do-while loop, allowing the user to choose from a list of operations.
  • If the Add Item option is selected, the program prompts the user for various details of a part, such as part ID, name, price, stock quantity, category, and minimum stock level.
  • These details are stored in the arrays using pointer arithmetic. Specifically, *(ptrPartIDs + partCount) stores the part ID, *(ptrPartNames + partCount) stores the part name, and similarly for the other attributes.
  • After the details are entered, the program increments the partCount to keep track of how many parts have been added to the inventory.
  • If the Sell Item option is selected, the program prompts the user to enter the part ID of the part to be sold and the quantity to sell.
  • The program then searches through the inventory by using pointer arithmetic (*(ptrPartIDs + i)) to find the part with the specified part ID.
  • If the part is found, the stock is updated by subtracting the quantity sold (*(ptrPartStocks + i) -= quantityToSell). If the part is not found in the inventory, the program notifies the user that the part does not exist.
  • If the Restock Item option is selected, the program prompts the user for the part ID and the quantity to restock. The program then uses pointer arithmetic to find the corresponding part in the inventory.
  • If the part is found, the stock is updated by adding the restocked quantity (*(ptrPartStocks + i) += quantityToRestock). If the part is not found, the program notifies the user that the part is not in the inventory.
  • If the Display Inventory option is selected, the program loops through all the parts in the inventory using pointer dereferencing to access each part’s details.
  • The part ID, name, price, stock quantity, category, and minimum stock level are displayed for each part. This is done by dereferencing the pointers (e.g., *(ptrPartIDs + i)) to access and display the values stored in the arrays.
  • If the Remove Item option is selected, the program checks if any part’s stock has reached zero. If a part with zero stock is found, the program shifts the remaining elements in the arrays to remove that part from the inventory.
  • The elements are shifted by copying the values from the next index to the current index using pointer arithmetic. Once the part is removed, the partCount is decremented to reflect the updated number of parts in the inventory.
  • If the Exit option is selected, the program prints a closing message and exits, ending the program.
#include <iostream>
#include <string>
using namespace std;

int main() {
    const int MAX_PARTS = 5;

    int partIDs[MAX_PARTS];
    string partNames[MAX_PARTS];
    int partPrices[MAX_PARTS];
    int partStocks[MAX_PARTS];
    string partCategories[MAX_PARTS];
    int partMinStock[MAX_PARTS];

    int* ptrPartIDs = partIDs;
    string* ptrPartNames = partNames;
    int* ptrPartPrices = partPrices;
    int* ptrPartStocks = partStocks;
    string* ptrPartCategories = partCategories;
    int* ptrPartMinStock = partMinStock;

    int partCount = 0;
    int choice;

    do {
        cout << "\n===== PC Modification Inventory Tracker =====\n";
        cout << "1. Add a new part\n";
        cout << "2. Sell a part\n";
        cout << "3. Restock a part\n";
        cout << "4. Display inventory\n";
        cout << "5. Remove a part\n";
        cout << "6. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;
        cin.ignore(); 

        if (choice == 1) {
            if (partCount < MAX_PARTS) {
                cout << "\nEnter part ID: ";
                cin >> *(ptrPartIDs + partCount);
                cin.ignore(); 

                cout << "Enter part name: ";
                getline(cin, *(ptrPartNames + partCount)); 

                cout << "Enter part price: ";
                cin >> *(ptrPartPrices + partCount);
                cout << "Enter part stock quantity: ";
                cin >> *(ptrPartStocks + partCount);

                cin.ignore(); 

                cout << "Enter part category (e.g., CPU, RAM, GPU, etc.): ";
                getline(cin, *(ptrPartCategories + partCount));  

                cout << "Enter minimum stock level: ";
                cin >> *(ptrPartMinStock + partCount);

                partCount++;
                cout << "\nPart added successfully.\n";
            } else {
                cout << "\nInventory is full, cannot add more parts.\n";
            }
        }
        else if (choice == 2) {
            int partIDToSell, quantityToSell;
            cout << "\nEnter part ID to sell: ";
            cin >> partIDToSell;
            cout << "Enter quantity to sell: ";
            cin >> quantityToSell;

            bool partFound = false;
            for (int i = 0; i < partCount; i++) {
                if (*(ptrPartIDs + i) == partIDToSell) {
                    *(ptrPartStocks + i) -= quantityToSell;
                    partFound = true;
                    cout << "Sold " << quantityToSell << " of " << *(ptrPartNames + i)
                         << ". Remaining stock: " << *(ptrPartStocks + i) << endl;
                    break;
                }
            }
            if (!partFound) {
                cout << "\nPart not found in the inventory.\n";
            }
        }
        else if (choice == 3) {
            int partIDToRestock, quantityToRestock;
            cout << "\nEnter part ID to restock: ";
            cin >> partIDToRestock;
            cout << "Enter quantity to restock: ";
            cin >> quantityToRestock;

            bool partFound = false;
            for (int i = 0; i < partCount; i++) {
                if (*(ptrPartIDs + i) == partIDToRestock) {
                    *(ptrPartStocks + i) += quantityToRestock;
                    partFound = true;
                    cout << "Restocked " << quantityToRestock << " of " << *(ptrPartNames + i)
                         << ". New stock: " << *(ptrPartStocks + i) << endl;
                    break;
                }
            }
            if (!partFound) {
                cout << "\nPart not found in the inventory.\n";
            }
        }
        else if (choice == 4) {
            cout << "\nCurrent Inventory:\n";
            for (int i = 0; i < partCount; i++) {
                cout << "Part ID: " << *(ptrPartIDs + i) << ", Name: " << *(ptrPartNames + i) 
                     << ", Price: " << *(ptrPartPrices + i) << ", Stock: " << *(ptrPartStocks + i) 
                     << ", Category: " << *(ptrPartCategories + i) 
                     << ", Minimum Stock Level: " << *(ptrPartMinStock + i) << endl;
            }
        }
        else if (choice == 5) {
            int partIDToRemove;
            cout << "\nEnter part ID to remove: ";
            cin >> partIDToRemove;

            bool partFound = false;
            for (int i = 0; i < partCount; i++) {
                if (*(ptrPartStocks + i) == 0 && *(ptrPartIDs + i) == partIDToRemove) {
                    for (int j = i; j < partCount - 1; j++) {
                        *(ptrPartIDs + j) = *(ptrPartIDs + j + 1);
                        *(ptrPartNames + j) = *(ptrPartNames + j + 1);
                        *(ptrPartPrices + j) = *(ptrPartPrices + j + 1);
                        *(ptrPartStocks + j) = *(ptrPartStocks + j + 1);
                        *(ptrPartCategories + j) = *(ptrPartCategories + j + 1);
                        *(ptrPartMinStock + j) = *(ptrPartMinStock + j + 1);
                    }
                    partCount--;
                    partFound = true;
                    cout << "\nPart with ID " << partIDToRemove << " removed successfully.\n";
                    break;
                }
            }
            if (!partFound) {
                cout << "\nPart not found in the inventory.\n";
            }
        }
        else if (choice == 6) {
            cout << "Exiting the program.\n";
        }
        else {
            cout << "Invalid choice. Please try again.\n";
        }
    } while (choice != 6);

    return 0;
}

Leave a Comment

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

Scroll to Top