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

This article presents a collection of challenging, scenario-based programming questions focused on 2D arrays in C++. It covers a variety of real-world scenarios, such as product sales analysis, treasure map decoding, robot health evaluation, and more. These questions will help you sharpen your skills in working with 2D arrays, performing matrix operations, and solving practical problems using loops, conditionals, and arrays. Whether you’re just starting or looking to strengthen your problem-solving abilities, this article provides detailed guidance to enhance your C++ programming knowledge.

Product Sales Analyzer

A tech store with a cashier and 3 products on display
Tech Store
Imagine you run a store selling 3 products, and you track their sales for 4 days. At the end of the fourth day, you need to calculate the total sales for each product to see which one performed best. Write a C++ program that takes sales data as input, and calculates the total sales for each product.

Test Case
Input
Enter sales data for 3 products over 4 days:
Product 1, Day 1: 10
Product 1, Day 2: 15
Product 1, Day 3: 20
Product 1, Day 4: 25
Product 2, Day 1: 5
Product 2, Day 2: 10
Product 2, Day 3: 15
Product 2, Day 4: 20
Product 3, Day 1: 8
Product 3, Day 2: 12
Product 3, Day 3: 18
Product 3, Day 4: 22
Expected Output
Total Sales for Each Product:
Product 1: 70 units
Product 2: 50 units
Product 3: 60 units
  • The program starts by defining a 3×4 2D array called sales to store sales data for 3 products over 4 days.
  • The user is prompted to enter daily sales for each product using nested loops.
  • The outer loop iterates over the products, while the inner loop takes input for each day’s sales.
  • After collecting the data, the program calculates the total sales for each product by summing the values in each row.
  • The results are then displayed in a formatted output.
#include <iostream>
using namespace std;

int main() {
    int sales[3][4];
    
    cout << "Enter sales data for 3 products over 4 days:\n";
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            cout << "Product " << i + 1 << ", Day " << j + 1 << ": ";
            cin >> sales[i][j];
        }
    }
    
    cout << "\nTotal Sales for Each Product:\n";
    for (int i = 0; i < 3; i++) {
        int total = 0;
        for (int j = 0; j < 4; j++) {
            total += sales[i][j];
        }
        cout << "Product " << i + 1 << ": " << total << " units\n";
    }
    return 0;
}

The Treasure Map

Old treasure map
Treasure Map
You have discovered a 5×5 treasure map, where each cell contains either 0 (empty) or 1 (treasure). Your task is to write a C++ program that scans the grid and prints the coordinates of all treasure locations.

Test Case
Input
Enter the 5×5 treasure map (0 for empty, 1 for treasure):
0 0 1 0 0
0 0 0 0 0
1 0 0 0 1
0 1 0 0 0
0 0 0 1 0
Expected Output
Treasure found at:
Row 1, Column 3
Row 3, Column 1
Row 3, Column 5
Row 4, Column 2
Row 5, Column 4
  • The program starts by asking the user to enter the 5×5 treasure map, where 0 represents an empty spot and 1 represents a treasure. The input is stored in a 2D array named map.
  • The program then uses a nested for loop to traverse each cell of the array.
  • The outer loop iterates over the rows, while the inner loop iterates over the columns.
  • For each cell, the program checks if the value is 1. If it is, the program prints the row and column index of that location.
  • Once the entire map has been scanned, the program terminates.
#include <iostream>
using namespace std;

int main() {
    int map[5][5];

    cout << "Enter the 5x5 treasure map (0 for empty, 1 for treasure):\n";
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            cin >> map[i][j];
        }
    }

    cout << "\nTreasure found at:\n";
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            if (map[i][j] == 1) {
                cout << "Row " << i+1 << ", Column " << j+1 << endl;
            }
        }
    }
    return 0;
}

Battle of the Robots

A grid showing different robots with their health levels
Battle of Robots
On a battlefield filled with robots, each robot has a certain health value. The battlefield is represented as a 2D grid, where each cell contains a number indicating a robot’s health. Your mission is to identify the strongest robot, i.e., the one with the highest health, and print its location along with its health value. Write a C++ program that first asks the user for the number of rows and columns of the battlefield, then takes the grid values as input, and finally determines and prints the coordinates of the strongest robot along with its health.

Test Case
Input
Enter the number of rows: 4
Enter the number of columns: 5
Enter the battlefield grid (each value represents a robot’s health):
10 15 20 35 10
25 40 30 10 5
10 5 60 20 25
5 10 15 20 35
Expected Output
Strongest robot is at Row 3, Column 3 with health 60.
  • The program starts by asking the user to enter the number of rows and columns for the battlefield grid. These inputs are saved in the variables rows and cols, respectively.
  • Next, the program declares a 2D array battlefield of size [rows][cols] to store the health values of robots.
  • The user is then prompted to enter the battlefield grid, where each value represents the health of a robot.
  • This input is collected using a nested for loop, with the outer loop iterating through the rows and the inner loop iterating through the columns.
  • After taking input, the program initializes three variables: maxHealth (set to -1 initially), rowIndex, and colIndex (both set to -1). These variables are used to keep track of the robot with the highest health and its location in the grid.
  • The program then scans the entire grid using a nested for loop. For each robot, it checks if its health is greater than the current maxHealth. If so, maxHealth is updated with the new highest value, and rowIndex and colIndex are updated with the current position of that robot.
  • Once the entire grid has been scanned, the program prints the location of the strongest robot using 1-based indexing. Instead of displaying the default 0-based array positions, it adds 1 to rowIndex and colIndex before printing, ensuring that the output is user-friendly.
#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    
    cout << "Enter the number of rows: ";
    cin >> rows;
    cout << "Enter the number of columns: ";
    cin >> cols;

    int battlefield[rows][cols];

    cout << "Enter the battlefield grid (each value represents a robot's health):\n";
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cin >> battlefield[i][j];
        }
    }

    int maxHealth = -1, rowIndex = -1, colIndex = -1;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (battlefield[i][j] > maxHealth) {
                maxHealth = battlefield[i][j];
                rowIndex = i;
                colIndex = j;
            }
        }
    }

    cout << "\nStrongest robot is at Row " << (rowIndex + 1) << ", Column " << (colIndex + 1) << " with health " << maxHealth << ".\n";

    return 0;
}

Restaurant Ratings Analyzer

Restaurant Ratings
Restaurant Ratings
Imagine that you manage an online review platform where customers rate restaurants based on different criteria such as food quality, service, and ambiance. To streamline the process, you want to store these ratings systematically and quickly calculate the overall average rating for each restaurant. Write a C++ program that takes the number of restaurants, the number of rating categories, and ratings provided by customers as input, then calculates and displays the average rating for each restaurant.

Test Case
Input
Enter the number of restaurants: 2
Enter the number of rating categories: 3
Enter ratings for restaurant 1: 4 5 6
Enter ratings for restaurant 2: 5 5 4
Expected Output
Average rating for restaurant 1: 5
Average rating for restaurant 2: 4.66667
  • The program begins by prompting the user to enter the number of restaurants and the number of rating categories. These values are stored in the variables restaurants and categories, respectively.
  • Then, using nested loops, the program asks the user to input ratings for each restaurant across all rating categories. These inputs are stored in a 2D array named ratings, where each row corresponds to a restaurant, and each column corresponds to a specific rating category.
  • The program calculates the average rating for each restaurant separately.
  • It initializes a variable sum for each restaurant and adds all the ratings from each category for that restaurant to this sum.
  • To find the average, the sum of ratings for each restaurant is divided by the total number of rating categories, which gives the average rating per restaurant.
  • The calculated average rating for each restaurant is displayed immediately after calculation.
#include <iostream>
using namespace std;

int main() {
    int restaurants, categories;
    cout << "Enter the number of restaurants: ";
    cin >> restaurants;
    cout << "Enter the number of rating categories: ";
    cin >> categories;

    int ratings[restaurants][categories];

    for(int i = 0; i < restaurants; i++) {
        cout << "Enter ratings for restaurant " << i+1 << ": ";
        for(int j = 0; j < categories; j++)
            cin >> ratings[i][j];
    }

    for(int i = 0; i < restaurants; i++) {
        int sum = 0;
        for(int j = 0; j < categories; j++)
            sum += ratings[i][j];

        cout << "Average rating for restaurant " << i+1 << ": " << (double)sum/categories << endl;
    }

    return 0;
}

Library Book Tracker

Library with bookshelves
Library
You’re organizing books in a library arranged on multiple shelves and sections. You need to record how many books are placed on each shelf within each section.
Write a C++ program that takes the number of sections, number of shelves per section, and the number of books per shelf as input, then calculates and displays the total number of books in each section.

Test Case
Input
Enter the number of sections: 2
Enter the number of shelves per section: 3
Enter number of books for section 1 on each shelf: 12 15 10
Enter number of books for section 2 on each shelf: 9 8 7
Expected Output
Total books in section 1: 37
Total books in section 2: 24
  • The program first asks the user to enter the number of sections and the number of shelves per section. These values are stored in the variables sections and shelves, respectively.
  • Using nested loops, the program then prompts the user to input the number of books for each shelf within each section. These values are stored in a 2D array called books, where each row represents a section, and each column represents a shelf.
  • The program calculates the total number of books in each section by initializing a variable total for each section and summing the number of books across all shelves in that section.
  • Finally, the total number of books for each section is displayed immediately after calculation.
#include <iostream>
using namespace std;

int main() {
    int sections, shelves;
    cout << "Enter the number of sections: ";
    cin >> sections;
    cout << "Enter the number of shelves per section: ";
    cin >> shelves;

    int books[sections][shelves];

    for(int i = 0; i < sections; i++) {
        cout << "Enter number of books for section " << i+1 << " on each shelf: ";
        for(int j = 0; j < shelves; j++)
            cin >> books[i][j];
    }

    for(int i = 0; i < sections; i++) {
        int total = 0;
        for(int j = 0; j < shelves; j++)
            total += books[i][j];

        cout << "Total books in section " << i+1 << ": " << total << endl;
    }

    return 0;
}

Treasure Map Decipher

Treasure Map
Treasure Map
You’re an explorer who discovered a mysterious ancient treasure map represented by a 2D array of characters. The map contains hidden instructions in the form of vowels. To decode the map, you must count and display how many vowels each row contains. Write a C++ program that deciphers the treasure map by counting vowels in each row and displays these counts.

Test Case
Input
Enter the number of rows for the map: 3
Enter the number of columns for the map: 3
Enter the treasure map characters:
a x e
i o u
p o a
Expected Output
Vowel count in row 1: 2
Vowel count in row 2: 3
Vowel count in row 3: 2
  • The program starts by asking the user to enter the number of rows and columns for the map. This input is saved in the rows and cols variables.
  • Next, the program prompts the user to enter the characters of the treasure map. These characters are stored in a 2D array map[rows][cols]. The program uses nested for loops to take input for every row and column of the map.
  • Once the map has been populated with the characters, the program moves on to the main logic, counting vowels in each row of the map.
  • The program starts by initializing a variable vowelCount to 0 for each row.
  • For each row, the program checks each character to see if it is a vowel.
  • This is done using an if statement that checks for both lowercase and uppercase vowels (a, A, e, E, i, I, o, O, u, U).
  • If a character is found to be a vowel, vowelCount is incremented by 1.
  • After processing all the characters in the current row, the program displays the vowel count for that row immediately using cout.
  • This process repeats for all rows in the map. By the end, the program will have displayed the number of vowels for each row, helping to decode the hidden instructions in the treasure map.
#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    cout << "Enter the number of rows for the map: ";
    cin >> rows;
    cout << "Enter the number of columns for the map: ";
    cin >> cols;

    char map[rows][cols];
    cout << "Enter the treasure map characters: \n";
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            cin >> map[i][j];
        }
    }

    for(int i = 0; i < rows; i++) {
        int vowelCount = 0;
        for(int j = 0; j < cols; j++) {
            char ch = map[i][j];
            if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') {
                vowelCount++;
            }
        }
        cout << "Vowel count in row " << i + 1 << ": " << vowelCount << endl;
    }

    return 0;
}

The Magic Potion Lab

A wizard and two students with different potion bottles
Magic Potion Lab
In a wizardry school, students are experimenting with potion recipes. Each potion recipe consists of ingredients represented by potency values. A potion is considered stable if the sum of potency values of all its ingredients equals an exact magical number. You have multiple potions (rows) and ingredients (columns). Write a C++ program that takes the number of potions, number of ingredients, potency values for each ingredient in every potion, and the magical stability number as input. The program should then determine how many potions are stable and display the count.

Test Case
Input
Enter number of potions: 2
Enter number of ingredients per potion: 3
Enter potency values for potion 1: 3 4 5
Enter potency values for potion 2: 2 2 6
Enter magical stability number: 12
Expected Output
Number of stable potions: 1
  • The program starts by asking the user to enter the number of potions and ingredients. These inputs are stored in variables potions and ingredients.
  • Then, the program uses nested loops to input the potency values for each ingredient in every potion, storing these values in a 2D array potency.
  • Next, the program asks the user for the magical stability number, storing this in the variable magicNumber.
  • The program calculates the sum of potency values for each potion.
  • If the sum equals the magicalNumber, a counter (stableCount) is incremented.
  • Finally, the program displays the total number of stable potions.
#include <iostream>
using namespace std;

int main() {
    int potions, ingredients, magicNumber;
    cout << "Enter number of potions: ";
    cin >> potions;
    cout << "Enter number of ingredients per potion: ";
    cin >> ingredients;

    int potency[potions][ingredients];

    for(int i=0; i<potions; i++) {
        cout << "Enter potency values for potion " << i+1 << ": ";
        for(int j=0; j<ingredients; j++)
            cin >> potency[i][j];
    }

    cout << "Enter magical stability number: ";
    cin >> magicNumber;

    int stableCount = 0;

    for(int i=0; i<potions; i++) {
        int sum = 0;
        for(int j=0; j<ingredients; j++)
            sum += potency[i][j];
        if(sum == magicNumber)
            stableCount++;
    }

    cout << "Number of stable potions: " << stableCount << endl;
    return 0;
}

Alien Signal Detector

A scientist looking through a telescope, thinking about alien signals
Alien Signals
You are a scientist working for a secret space agency. Your job is to scan signals from space using a 2D radar grid. Alien signals are represented by prime numbers, while noise is represented by non-prime numbers. Write a C++ program that scans the radar grid and counts how many prime-numbered alien signals are detected.

Test Case
Input
Enter the number of rows for the radar grid: 3
Enter the number of columns for the radar grid: 3
Enter signal values for radar grid:
2 4 5
7 10 3
11 8 9
Expected Output
Number of alien signals detected: 5
  • The program begins by asking the user to input the dimensions of the radar grid. These inputs are stored in the rows and cols variables.
  • For the radar grid, the program then uses nested loops to allow the user to input signal values into a 2D array radar[rows][cols]. This 2D array will represent the radar grid, where each element stores a signal value.
  • Next, the program initializes a counter variable alienSignals to 0, which will be used to count how many alien signals (prime numbers) are detected.
  • Then, the program starts processing each signal in the grid using another set of nested loops to iterate through each row and each column of the radar array. For each signal, it checks if the number is prime.
  • To check if a number is prime, the program first verifies that the number is greater than 1 (since primes are defined as greater than 1).
  • Then, for each number, it checks if it is divisible by any number from 2 to the square root of the number.
  • If any such divisor is found, the number is not prime, and the check is stopped.
  • If the signal is a prime number, the program increments the alienSignals counter by 1.
  • After processing all signals in the grid, the program prints the total number of alien signals detected by displaying the value of alienSignals.
#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    cout << "Enter the number of rows for the radar grid: ";
    cin >> rows;
    cout << "Enter the number of columns for the radar grid: ";
    cin >> cols;

    int radar[rows][cols];
    cout << "Enter signal values for radar grid: \n";
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++)
            cin >> radar[i][j];
    }

    int alienSignals = 0;

    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            int signal = radar[i][j];
            bool isPrime = true;
            if(signal <= 1) {
                isPrime = false;
            } else {
                for(int k = 2; k * k <= signal; k++) {
                    if(signal % k == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }

            if(isPrime) {
                alienSignals++;
            }
        }
    }

    cout << "Number of alien signals detected: " << alienSignals << endl;
    return 0;
}

Plant Growth Tracker

A gardener analyzing which plant has grown the most
Plant Growth
You are a gardener in charge of tracking the growth of various plants across multiple days. Each plant grows at a different rate each day depending on the weather, soil, and care provided. You need to track how much each plant grows daily and identify which plant has experienced the most and least growth overall. Write a C++ program that takes the number of plants, the number of days, and the growth rate for each plant on each day as input. The program should then calculate and display which plant has the highest and the lowest total growth over the given period.

Test Case
Input
Enter the number of plants: 3
Enter the number of days: 3
Enter the growth rates for each plant on each day:
1 3 2
4 2 3
5 1 4
Expected Output
Plant 3 experienced the greatest growth of 10
Plant 1 experienced the least growth of 6
  • The program starts by asking the user to enter the number of plants and the number of days for which the growth is being tracked. These values are saved in the plants and days variables.
  • Next, the program prompts the user to input the growth rate for each plant on each day. This data is stored in a 2D array growth[plants][days], where each row corresponds to a plant, and each column corresponds to the growth of that plant on a specific day.
  • Once the data is entered, the program proceeds to calculate the total growth for each plant.
  • It initializes two variables: maxGrowth and minGrowth.
  • The maxGrowth is initialized to -1 to ensure that any positive growth value will be considered greater, and minGrowth is initialized to an arbitrarily large value (1000000) so that any plant’s growth will be smaller initially.
  • For each plant, the program calculates the total growth by summing up the growth for each day of that plant using a nested for loop.
  • After calculating the total growth for each plant, the program compares it to the current maximum and minimum growth values.
  • If the total growth of the current plant is greater than the maxGrowth, the program updates the maxGrowth to this value and stores the plant’s index as maxGrowthPlant.
  • Similarly, if the total growth of the current plant is less than the minGrowth, the program updates the minGrowth to this value and stores the plant’s index as minGrowthPlant.
  • After processing all plants, the program displays the plant that had the most growth and the plant that had the least growth.
#include <iostream>
using namespace std;

int main() {
    int plants, days;
    cout << "Enter the number of plants: ";
    cin >> plants;
    cout << "Enter the number of days: ";
    cin >> days;

    int growth[plants][days];

    cout << "Enter the growth rates for each plant on each day: \n";
    for(int i = 0; i < plants; i++) {
        for(int j = 0; j < days; j++) {
            cin >> growth[i][j];
        }
    }

    int maxGrowth = -1;
    int minGrowth = 1000000;  
    int maxGrowthPlant = -1;
    int minGrowthPlant = -1;

    for(int i = 0; i < plants; i++) {
        int totalGrowth = 0;
        for(int j = 0; j < days; j++) {
            totalGrowth += growth[i][j];
        }
        
        if(totalGrowth > maxGrowth) {
            maxGrowth = totalGrowth;
            maxGrowthPlant = i;
        }
        
        if(totalGrowth < minGrowth) {
            minGrowth = totalGrowth;
            minGrowthPlant = i;
        }
    }

    cout << "Plant " << maxGrowthPlant + 1 << " experienced the greatest growth of " << maxGrowth << endl;
    cout << "Plant " << minGrowthPlant + 1 << " experienced the least growth of " << minGrowth << endl;

    return 0;
}

Pet Care Inventory

Pet Store
Pet Shop
Imagine that you are managing a pet store that sells various pet supplies, such as food, toys, bedding, and grooming products. The store keeps track of inventory for each type of pet product across different pet categories, such as dogs, cats, and birds. You are responsible for creating a program to help the store manage its pet care inventory. In this store, inventory is represented as a 2D array, where each row corresponds to a pet category (such as dogs, cats, or birds), and each column corresponds to a specific product type (food, toys, bedding, grooming products). The store regularly updates the stock count for each product, and your job is to keep track of how many items are available for each category and type. Write a C++ program that takes the number of pet categories and product types as input from the user, allows the user to input the stock count for each product in each pet category, calculates and displays the total stock for each product type across all pet categories, displays the total stock for each pet category, and finally displays the overall stock for the entire pet store.

Test Case 
Input
Enter the number of pet categories: 3
Enter the number of product types: 4
Enter the stock for product type 1 in category 1: 50
Enter the stock for product type 2 in category 1: 20
Enter the stock for product type 3 in category 1: 10
Enter the stock for product type 4 in category 1: 30
Enter the stock for product type 1 in category 2: 40
Enter the stock for product type 2 in category 2: 50
Enter the stock for product type 3 in category 2: 20
Enter the stock for product type 4 in category 2: 10
Enter the stock for product type 1 in category 3: 30
Enter the stock for product type 2 in category 3: 10
Enter the stock for product type 3 in category 3: 40
Enter the stock for product type 4 in category 3: 20
Expected Output
Total stock for each product type across all categories:
Product type 1: 120 items
Product type 2: 80 items
Product type 3: 70 items
Product type 4: 60 items
Total stock for each pet category:
Category 1: 110 items
Category 2: 120 items
Category 3: 100 items
Total stock for the entire store: 330 items
  • The program begins by asking the user to enter the number of pet categories (rows) and the number of product types (columns). These values are saved in the variables categories and products, respectively.
  • Next, the program creates a 2D array called inventory to store the stock count for each product in each pet category.
  • The user is prompted to input the stock count for each product in each pet category, which is then stored in the inventory[i][j]. Here, i represents the pet category (row), and j represents the product type (column).
  • After populating the array with stock counts, the program calculates the total stock for each product type across all pet categories. This is done by summing the values in each column of the array.
  • The program then displays the total stock for each product type.
  • Next, the program calculates the total stock for each pet category by summing the values in each row. It then displays the total stock for each pet category.
  • Finally, the program calculates the overall stock for the entire store by summing all the values in the inventory array and displaying the total store stock.
#include <iostream>
using namespace std;

int main() {
    int categories, products;

    cout << "Enter the number of pet categories: ";
    cin >> categories;
    cout << "Enter the number of product types: ";
    cin >> products;

    int inventory[categories][products];

    for (int i = 0; i < categories; i++) {
        for (int j = 0; j < products; j++) {
            cout << "Enter the stock for product type " << j+1 << " in category " << i+1 << ": ";
            cin >> inventory[i][j];
        }
    }

    cout << "\nTotal stock for each product type across all categories:" << endl;
    for (int j = 0; j < products; j++) {
        int totalProductStock = 0;
        for (int i = 0; i < categories; i++) {
            totalProductStock += inventory[i][j];
        }
        cout << "Product type " << j+1 << ": " << totalProductStock << " items" << endl;
    }

    cout << "\nTotal stock for each pet category:" << endl;
    for (int i = 0; i < categories; i++) {
        int totalCategoryStock = 0;
        for (int j = 0; j < products; j++) {
            totalCategoryStock += inventory[i][j];
        }
        cout << "Category " << i+1 << ": " << totalCategoryStock << " items" << endl;
    }

    int totalStoreStock = 0;
    for (int i = 0; i < categories; i++) {
        for (int j = 0; j < products; j++) {
            totalStoreStock += inventory[i][j];
        }
    }
    cout << "\nTotal stock for the entire store: " << totalStoreStock << " items" << endl;

    return 0;
}

City Traffic Flow Optimization

Busy Intersection
Busy Intersection
Imagine that you are a traffic control engineer responsible for optimizing traffic flow across a city’s intersections. The city has multiple streets, and each intersection has a traffic light that stays green for a certain duration. These green times depend on the number of vehicles passing through the intersection. You need to calculate the optimal green light time for each intersection based on the number of vehicles expected. The city is represented as a 2D array, where each row corresponds to a street, and each column corresponds to an intersection. The value in each cell represents the number of vehicles expected at that intersection. Your task is to calculate the green light duration for each intersection using the formula: greenTime = vehicles * 0.5 seconds, where vehicles are the number of cars expected at that intersection. Write a C++ program that takes the number of streets, number of intersections, and the number of vehicles at each intersection as input. The program should then calculate and display the optimal green light time for each intersection, as well as the total green light time for all intersections in the city.

Test Case 
Input
Enter the number of streets: 3
Enter the number of intersections: 2
Enter the number of vehicles at intersection (1,1): 50
Enter the number of vehicles at intersection (1,2): 30
Enter the number of vehicles at intersection (2,1): 40
Enter the number of vehicles at intersection (2,2): 60
Enter the number of vehicles at intersection (3,1): 70
Enter the number of vehicles at intersection (3,2): 80
Expected Output
Intersection (1,1) should have a green light for 25 seconds.
Intersection (1,2) should have a green light for 15 seconds.
Intersection (2,1) should have a green light for 20 seconds.
Intersection (2,2) should have a green light for 30 seconds.
Intersection (3,1) should have a green light for 35 seconds.
Intersection (3,2) should have a green light for 40 seconds.
Total green light time for the entire city: 165 seconds.
  • The program starts by asking the user to enter the number of streets and intersections. This input is saved in the variables rows and cols, respectively.
  • The program creates a 2D array called cityGrid with rows number of rows and cols number of columns.
  • The user is asked to enter the number of vehicles for each intersection. This input is stored in the array cityGrid[i][j], where i represents the street and j represents the intersection.
  • Once the array is populated with the vehicle counts, the program proceeds to calculate the green light time for each intersection.
  • The green light time for an intersection is calculated using the formula greenTime = cityGrid[i][j] * 0.5. This is done in a nested for loop that iterates over each intersection.
  • The green time for each intersection is stored in the variable greenTime.
  • The program keeps track of the total green light time across all intersections. It does this by adding each intersection’s green time to a variable called totalGreenTime using the operation totalGreenTime += greenTime.
  • Finally, the program displays the green light time for each intersection, as well as the total green light time for the entire city.
#include <iostream>
using namespace std;

int main() {
    int rows, cols;

    cout << "Enter the number of streets: ";
    cin >> rows;
    cout << "Enter the number of intersections: ";
    cin >> cols;

    int cityGrid[rows][cols];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << "Enter the number of vehicles at intersection (" << i+1 << "," << j+1 << "): ";
            cin >> cityGrid[i][j];
        }
    }

    double totalGreenTime = 0; 
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            double greenTime = cityGrid[i][j] * 0.5;
            totalGreenTime += greenTime;
            cout << "Intersection (" << i+1 << "," << j+1 << ") should have a green light for " << greenTime << " seconds." << endl;
        }
    }

    cout << "Total green light time for the entire city: " << totalGreenTime << " seconds." << endl;

    return 0;
}

Image Transformation

A matrix image showing transformation with numbers
Image Transformation
Imagine that you are working on a project to transform images in a graphic design application. The application applies various transformations like rotation, scaling, and translation to images. Each transformation is represented by a matrix, and these matrices can be multiplied together to achieve the desired effect.
To apply these transformations to an image, the image itself is represented as a matrix, where each element corresponds to a pixel’s color value. Similarly, the transformation matrices are represented as 2D matrices, and to apply a transformation, you multiply the image matrix by the transformation matrix.
For instance, to rotate the image, a rotation matrix is multiplied by the image matrix. For scaling or translating the image, other transformation matrices are used. Your task is to write a C++ program that multiplies two matrices: one representing an image and another representing a transformation. The result should be the transformed image matrix. The program should take the dimensions of both matrices as input, ask the user to input the elements of both matrices, then multiply the image matrix by the transformation matrix and display the resulting transformed image matrix.

Test Case 
Input
Enter the number of rows and columns for the transformation matrix: 3 2
Enter the elements of the image matrix:
imageMatrix[0][0]: 1
imageMatrix[0][1]: 2
imageMatrix[0][2]: 3
imageMatrix[1][0]: 4
imageMatrix[1][1]: 5
imageMatrix[1][2]: 6
Enter the elements of the transformation matrix:
transformMatrix[0][0]: 1
transformMatrix[0][1]: 0
transformMatrix[1][0]: 0
transformMatrix[1][1]: 1
transformMatrix[2][0]: 0
transformMatrix[2][1]: 0
Expected Output
The transformed image matrix is:
1 2
4 5
  • The program begins by asking the user to enter the number of rows and columns for both the image matrix and the transformation matrix. These dimensions are stored in the variables imageRows, imageCols, transformRows, and transformCols.
  • Before proceeding, the program checks if the multiplication of the two matrices is possible. For matrix multiplication to be valid, the number of columns in the image matrix must match the number of rows in the transformation matrix. If this condition is not met, the program will print an error message and stop further execution.
  • After confirming that the matrices can be multiplied, the program creates three 2D arrays: one for the image matrix, one for the transformation matrix, and one for the resulting matrix. The user is prompted to enter the values for both the image matrix and the transformation matrix.
  • Next, the program proceeds to perform the matrix multiplication. This involves taking each element of the image matrix and multiplying it by the corresponding element of the transformation matrix.
  • The multiplication is done by iterating through the rows of the image matrix and the columns of the transformation matrix.
  • For each element in the result matrix, the program calculates the sum of the products of the corresponding elements from the image matrix row and the transformation matrix column.
  • Finally, the program displays the resulting transformed matrix, which represents the image after applying the transformation.
#include <iostream>
using namespace std;

int main() {
    int imageRows, imageCols, transformRows, transformCols;

    cout << "Enter the number of rows and columns for the image matrix: ";
    cin >> imageRows >> imageCols;
    cout << "Enter the number of rows and columns for the transformation matrix: ";
    cin >> transformRows >> transformCols;

    if (imageCols != transformRows) {
        cout << "Matrix multiplication is not possible. The number of columns in the image matrix must equal the number of rows in the transformation matrix." << endl;
        return 0;
    }

    int imageMatrix[imageRows][imageCols];
    int transformMatrix[transformRows][transformCols];
    int resultMatrix[imageRows][transformCols];

    cout << "Enter the elements of the image matrix: " << endl;
    for (int i = 0; i < imageRows; i++) {
        for (int j = 0; j < imageCols; j++) {
            cout << "imageMatrix[" << i << "][" << j << "]: ";
            cin >> imageMatrix[i][j];
        }
    }

    cout << "Enter the elements of the transformation matrix: " << endl;
    for (int i = 0; i < transformRows; i++) {
        for (int j = 0; j < transformCols; j++) {
            cout << "transformMatrix[" << i << "][" << j << "]: ";
            cin >> transformMatrix[i][j];
        }
    }

    for (int i = 0; i < imageRows; i++) {
        for (int j = 0; j < transformCols; j++) {
            resultMatrix[i][j] = 0;
            for (int k = 0; k < imageCols; k++) {
                resultMatrix[i][j] += imageMatrix[i][k] * transformMatrix[k][j];
            }
        }
    }

    cout << "\nThe transformed image matrix is: " << endl;
    for (int i = 0; i < imageRows; i++) {
        for (int j = 0; j < transformCols; j++) {
            cout << resultMatrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

Castle Room Security

A simple drawing of a Castle
Castle
You are in charge of securing a medieval castle. The castle consists of multiple rooms arranged in a grid-like layout, where each room has a security rating. A room can either be locked (represented by a ‘1’) or unlocked (represented by a ‘0’). The rooms are connected by doors, and your task is to find the largest contiguous area of unlocked rooms in the castle. Write a C++ program that takes the dimensions of the castle (rows and columns) and the security layout of the rooms (0 for unlocked and 1 for locked). The program should find and return the largest contiguous region of unlocked rooms. The rooms can be adjacent either horizontally or vertically, not diagonally.

Test Case 1
Input
Enter the number of rows and columns for the castle: 4 4
Enter the security layout of the rooms (0 for unlocked, 1 for locked):
0 1 0 1
0 1 0 1
0 0 0 1
1 1 1 1
Expected Output
The largest contiguous region of unlocked rooms has an area of: 7

Test Case 2
Input
Enter the number of rows and columns for the castle: 4 4
Enter the security layout of the rooms (0 for unlocked, 1 for locked):
1 1 0 1
1 1 0 0
1 1 1 0
0 1 0 0
Expected Output
The largest contiguous region of unlocked rooms has an area of: 6
  • The program starts by asking the user to enter the dimensions of the castle, specifically the number of rows and columns. These values are saved in the rows and cols variables.
  • Next, the program creates a 2D array castle[50][50] to store the security layout of the rooms. In this array, each element represents a room in the castle, and its value will be either 0 (unlocked) or 1 (locked). The user is prompted to enter these values for each room in the grid.
  • To keep track of which rooms have been visited during the search for contiguous unlocked rooms, the program uses another 2D array visited[50][50] that is initialized to false. This array will help ensure that each room is only processed once during the DFS (Depth-First Search).
  • The program then initializes a variable maxArea to 0. This will hold the size of the largest region of contiguous unlocked rooms found during the search.
  • Now, the program uses DFS (Depth-First Search) to explore the castle. But instead of using recursive DFS (which might cause issues with stack overflow for large grids), the program uses a stack-based DFS.
  • The stack is implemented manually using a 2D array stack[rows * cols][2], where each element in the stack holds the coordinates (x, y) of a room.
  • The program iterates through each room in the castle grid. If a room is unlocked (0) and has not been visited before, the DFS begins from that room. The room’s coordinates are pushed onto the stack.
  • The coordinates of the starting room are pushed onto the stack (stack[++top][0] = i and stack[top][1] = j). This ensures that the DFS will start at that room.
  • The DFS continues by popping the room’s coordinates from the stack and checking the four possible directions: up, down, left, and right.
  • If the neighboring room is unlocked (0), within bounds of the grid, and has not been visited before, its coordinates are pushed onto the stack, and it is marked as visited.
  • Each time a room is explored, the area is incremented by 1. This keeps track of the size of the current contiguous region of unlocked rooms.
  • Once all connected rooms are visited for a given starting room, the program moves on to the next room in the grid.
  • After the DFS finishes for a region, the area (size of the current region) is compared with maxArea. If the current region is larger, maxArea is updated.
  • This process repeats for all rooms in the castle.
  • After all rooms have been processed, the program outputs the largest contiguous region of unlocked rooms found by the DFS, which is stored in maxArea.
#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    cout << "Enter the number of rows and columns for the castle: ";
    cin >> rows >> cols;

    int castle[50][50];
    bool visited[50][50] = {false};

    cout << "Enter the security layout of the rooms (0 for unlocked, 1 for locked): \n";
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            cin >> castle[i][j];
        }
    }

    int maxArea = 0;

    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            if(castle[i][j] == 0 && !visited[i][j]) { 
                int area = 0;
                int stack[rows * cols][2]; 
                int top = -1;
                
                stack[++top][0] = i;
                stack[top][1] = j;
                visited[i][j] = true;

                int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
                
                while(top >= 0) {
                    int x = stack[top][0];
                    int y = stack[top--][1];
                    area++;
                    
                    for(int d = 0; d < 4; d++) {
                        int nx = x + directions[d][0];
                        int ny = y + directions[d][1];
                        
                        if(nx >= 0 && nx < rows && ny >= 0 && ny < cols && castle[nx][ny] == 0 && !visited[nx][ny]) {
                            visited[nx][ny] = true;
                            stack[++top][0] = nx;
                            stack[top][1] = ny;
                        }
                    }
                }
                if(area > maxArea) {
                    maxArea = area;
                }
            }
        }
    }

    cout << "The largest contiguous region of unlocked rooms has an area of: " << maxArea << endl;
    return 0;
}

Cricket Match Performance Analysis

A cricket player hitting a ball with a bat
Cricket
Imagine you are a data analyst working for a cricket team. Your task is to analyze the performance of players over multiple matches and generate reports that help the team improve its overall performance. The team has played several matches, and for each match, the performance of each player is recorded in terms of runs scored, wickets taken, and overs bowled. You are tasked with creating a program that processes the performance data of each player across multiple matches. The data for each match consists of three statistics for each player: runs scored, wickets taken, and overs bowled. The program should be able to calculate various statistics for each player, including their total runs, total wickets, and total overs bowled across all matches, as well as their average runs, average wickets, and average overs per match. Write a C++ program that takes the number of matches and the number of players as input, takes the performance data (runs, wickets, overs) for each player in each match as input, calculates the total runs, total wickets, and total overs for each player across all matches, calculates the average runs, average wickets, and average overs per match for each player, and displays the performance statistics for each player and their overall contribution to the team.

Test Case 
Input
Enter the number of matches: 2
Enter the number of players: 3
Enter data for Player 1:
Match 1 – Runs: 45
Match 1 – Wickets: 2
Match 1 – Overs: 4
Match 2 – Runs: 50
Match 2 – Wickets: 3
Match 2 – Overs: 5
Enter data for Player 2:
Match 1 – Runs: 60
Match 1 – Wickets: 1
Match 1 – Overs: 3
Match 2 – Runs: 55
Match 2 – Wickets: 2
Match 2 – Overs: 4
Enter data for Player 3:
Match 1 – Runs: 30
Match 1 – Wickets: 0
Match 1 – Overs: 5
Match 2 – Runs: 40
Match 2 – Wickets: 1
Match 2 – Overs: 6
Expected Output
Player 1 Statistics:
Total Runs: 95
Total Wickets: 5
Total Overs: 9
Average Runs per match: 47.5
Average Wickets per match: 2.5
Average Overs per match: 4.5
Player 2 Statistics:
Total Runs: 115
Total Wickets: 3
Total Overs: 7
Average Runs per match: 57.5
Average Wickets per match: 1.5
Average Overs per match: 3.5
Player 3 Statistics:
Total Runs: 70
Total Wickets: 1
Total Overs: 11
Average Runs per match: 35
Average Wickets per match: 0.5
Average Overs per match: 5.5
  • The program starts by asking the user to input the number of matches and players. These inputs are stored in matches and players variables.
  • The program then creates a 2D array, performanceMatrix[players][matches * 3], where each row corresponds to a player and each set of three consecutive columns corresponds to the player’s runs, wickets, and overs for a particular match.
  • After that, the program prompts the user to input the performance data for each player in each match. This data is stored in the performanceMatrix array, where:
    • performanceMatrix[i][j * 3] stores the runs for player i in match j.
    • performanceMatrix[i][j * 3 + 1] stores the wickets for player i in match j.
    • performanceMatrix[i][j * 3 + 2] stores the overs for player i in match j.
  • Once all data has been entered, the program proceeds to calculate the statistics for each player:
  • It initializes variables totalRuns, totalWickets, and totalOvers to 0.
  • The program then sums up the runs, wickets, and overs for each player across all matches by iterating over the columns in the matrix.
  • After calculating the totals, the program computes the averages for each player by dividing the totals by the number of matches.
  • Finally, the program displays the following performance statistics for each player:
  • Average Runs, Average Wickets, Average Overs: The average value for each statistic per match
  • Total Runs, Total Wickets, Total Overs: The sum of the respective values over all matches.
#include <iostream>
using namespace std;

int main() {
    int matches, players;

    cout << "Enter the number of matches: ";
    cin >> matches;
    cout << "Enter the number of players: ";
    cin >> players;

    int performanceMatrix[players][matches * 3];

    for (int i = 0; i < players; i++) {
        cout << "Enter data for Player " << i + 1 << ":\n";
        for (int j = 0; j < matches; j++) {
            cout << "Match " << j + 1 << " - Runs: ";
            cin >> performanceMatrix[i][j * 3]; 
            cout << "Match " << j + 1 << " - Wickets: ";
            cin >> performanceMatrix[i][j * 3 + 1];
            cout << "Match " << j + 1 << " - Overs: ";
            cin >> performanceMatrix[i][j * 3 + 2];
        }
    }

    for (int i = 0; i < players; i++) {
        int totalRuns = 0, totalWickets = 0, totalOvers = 0;
        
        for (int j = 0; j < matches; j++) {
            totalRuns += performanceMatrix[i][j * 3];
            totalWickets += performanceMatrix[i][j * 3 + 1];
            totalOvers += performanceMatrix[i][j * 3 + 2];
        }

        double avgRuns = (double)totalRuns / matches;
        double avgWickets = (double)totalWickets / matches;
        double avgOvers = (double)totalOvers / matches;

        cout << "\nPlayer " << i + 1 << " Statistics:" << endl;
        cout << "Total Runs: " << totalRuns << endl;
        cout << "Total Wickets: " << totalWickets << endl;
        cout << "Total Overs: " << totalOvers << endl;
        cout << "Average Runs per match: " << avgRuns << endl;
        cout << "Average Wickets per match: " << avgWickets << endl;
        cout << "Average Overs per match: " << avgOvers << endl;
    }

    return 0;
}

University Student Result Management System

A person holding a test sheet with the highest score marked
Exam Result
Imagine you’re developing software for a university to manage students’ results effectively. Your task is to build a robust Student Result Management System that tracks students’ scores across various subjects. Each student has a unique name, and each subject has a specific name. Your program should first ask the user to input the number of students and the number of subjects. After this, the program should prompt the user to input the names of all students and all subjects before proceeding further. Once all names are entered, the program should display a menu-driven interface to perform various tasks repeatedly, such as entering student marks, displaying all marks clearly along with student and subject names, calculating total marks and percentages for each student, computing subject-wise average marks, finding the highest-scoring student, determining the most difficult subject (the subject in which the most students scored below average), and exiting the system. Write a menu-driven C++ program implementing all the described features.

Test Case 
Input
Enter number of students: 2
Enter number of subjects: 2

Enter names of students:
Student 1 name: Ali
Student 2 name: Sara

Enter names of subjects:
Subject 1 name: Math
Subject 2 name: Physics

— Student Result Management System —
1. Enter Students’ Marks
2. Display All Marks
3. Calculate Total Marks and Percentage of Each Student
4. Subject-wise Average Marks
5. Student with Highest Total Marks
6. Most Difficult Subject (Most students below average)
7. Exit

Enter your choice: 1
Enter marks for Ali:
Math: 90
Physics: 80
Enter marks for Sara:
Math: 70
Physics: 60

Enter your choice: 2

Enter your choice: 3

Enter your choice: 4

Enter your choice: 5

Enter your choice: 6

Enter your choice: 7
Expected Output
Student\Subject Math Physics
Ali 90 80
Sara 70 60

Total and Percentage of each student:
Ali: Total = 170, Percentage = 85%
Sara: Total = 130, Percentage = 65%

Subject-wise average marks:
Math: Average = 80
Physics: Average = 70

Highest Scoring Student: Ali with 170 marks.

Most difficult subject: Math (1 students below average)

Exiting program.
  • The program begins by asking the user to input the number of students and subjects. This input is saved in the students and subjects variables, respectively.
  • Two 1D arrays are created for storing students and subjects names.
  • Next, the program prompts the user to input the names of the students. It uses a for loop to iterate through each student and stores the entered names in the studentNames array.
  • The program then asks the user to input the names of the subjects. Using another for loop, the program stores these names in the subjectNames array.
  • After collecting the student and subject names, the program initializes a 2D array called marks. The array has students rows (one for each student) and subjects columns (one for each subject), which will hold the marks for each student in each subject.
  • Now, the program enters a do-while loop that continuously presents the user with a menu of options until the user chooses to exit (option 7). The menu contains multiple operations that can be performed on the student result data.
  • Option 1: Enter Students’ Marks
    The program asks the user to enter the marks for each student. A nested for loop is used to iterate over each student and each subject to accept the marks and store them in the marks array.
  • Option 2: Display All Marks
    The program displays a table of all students’ marks, with student names listed in the first column and subject names in the first row. A loop is used to display the marks in a structured format for easy reading, showing each student’s marks across all subjects.
  • Option 3: Calculate Total Marks and Percentage of Each Student
    For each student, the program calculates the total marks by summing up the marks for all subjects using a loop. Then, it calculates the percentage by dividing the total marks by the number of subjects. The total marks and percentage for each student are displayed immediately after the calculations.
  • Option 4: Subject-wise Average Marks
    This option calculates the average marks for each subject. The program loops through each subject and calculates the sum of the marks for that subject across all students. It then calculates the average by dividing the total sum by the number of students and displays the average marks for each subject.
  • Option 5: Student with Highest Total Marks
    The program identifies the student with the highest total marks. It does this by looping through each student, calculating the total marks, and comparing it with the highest total found so far. Once the student with the highest total is identified, their name and total marks are displayed.
  • Option 6: Most Difficult Subject (Most Students Below Average)
    The program calculates the number of students who scored below average in each subject. It first calculates the average marks for each subject, then checks each student’s marks for that subject. If a student’s score is below the average, it increases a counter. The program identifies the subject with the highest number of students scoring below average and displays the subject name and the count.
  • Option 7: Exit
    The program exits the loop when the user selects option 7. It displays a message saying “Exiting program.” and stops running.
  • After each operation, the menu is displayed again to allow the user to perform another action. If the user enters an invalid choice, the program prompts the user to try again.
#include <iostream>
#include <string>
using namespace std;

int main() {
    int students, subjects, choice;

    cout << "Enter number of students: ";
    cin >> students;
    cout << "Enter number of subjects: ";
    cin >> subjects;

    string studentNames[students];
    string subjectNames[subjects];

    cout << "\nEnter names of students:\n";
    for (int i = 0; i < students; i++) {
        cout << "Student " << (i + 1) << " name: ";
        cin >> studentNames[i];
    }

    cout << "\nEnter names of subjects:\n";
    for (int j = 0; j < subjects; j++) {
        cout << "Subject " << (j + 1) << " name: ";
        cin >> subjectNames[j];
    }

    int marks[students][subjects];

    do {
        cout << "\n--- Student Result Management System ---\n";
        cout << "1. Enter Students' Marks\n";
        cout << "2. Display All Marks\n";
        cout << "3. Calculate Total Marks and Percentage of Each Student\n";
        cout << "4. Subject-wise Average Marks\n";
        cout << "5. Student with Highest Total Marks\n";
        cout << "6. Most Difficult Subject (Most students below average)\n";
        cout << "7. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        if (choice == 1) {
            for (int i = 0; i < students; i++) {
                cout << "\nEnter marks for " << studentNames[i] << ":\n";
                for (int j = 0; j < subjects; j++) {
                    cout << subjectNames[j] << ": ";
                    cin >> marks[i][j];
                }
            }
        }
        else if (choice == 2) {
            cout << "\nStudent\\Subject\t";
            for (int j = 0; j < subjects; j++)
                cout << subjectNames[j] << "\t";
            cout << endl;

            for (int i = 0; i < students; i++) {
                cout << studentNames[i] << "\t\t";
                for (int j = 0; j < subjects; j++)
                    cout << marks[i][j] << "\t";
                cout << endl;
            }
        }
        else if (choice == 3) {
            cout << "\nTotal and Percentage of each student:\n";
            for (int i = 0; i < students; i++) {
                int total = 0;
                for (int j = 0; j < subjects; j++)
                    total += marks[i][j];
                double percent = (double)total / subjects;
                cout << studentNames[i] << ": Total = " << total << ", Percentage = " << percent << "%\n";
            }
        }
        else if (choice == 4) {
            cout << "\nSubject-wise average marks:\n";
            for (int j = 0; j < subjects; j++) {
                int subjectTotal = 0;
                for (int i = 0; i < students; i++)
                    subjectTotal += marks[i][j];
                double avg = (double)subjectTotal / students;
                cout << subjectNames[j] << ": Average = " << avg << endl;
            }
        }
        else if (choice == 5) {
            int highestTotal = -1, topStudent = -1;
            for (int i = 0; i < students; i++) {
                int total = 0;
                for (int j = 0; j < subjects; j++)
                    total += marks[i][j];
                if (total > highestTotal) {
                    highestTotal = total;
                    topStudent = i;
                }
            }
            cout << "\nHighest Scoring Student: " << studentNames[topStudent] << " with " << highestTotal << " marks.\n";
        }
        else if (choice == 6) {
            int difficultSubject = -1, maxBelowAvg = -1;
            for (int j = 0; j < subjects; j++) {
                int total = 0, countBelow = 0;
                for (int i = 0; i < students; i++)
                    total += marks[i][j];
                double avg = (double)total / students;
                for (int i = 0; i < students; i++)
                    if (marks[i][j] < avg)
                        countBelow++;
                if (countBelow > maxBelowAvg) {
                    maxBelowAvg = countBelow;
                    difficultSubject = j;
                }
            }
            cout << "\nMost difficult subject: " << subjectNames[difficultSubject]
                 << " (" << maxBelowAvg << " students below average)\n";
        }
        else if (choice == 7) {
            cout << "\nExiting program.\n";
        }
        else {
            cout << "Invalid choice! Please try again.\n";
        }

    } while (choice != 7);

    return 0;
}

Leave a Comment

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

Scroll to Top