Exercise
Two Dimensional Array
Objective
Write a C# program to ask the user for marks for 20 pupils (2 groups of 10, using a two-dimensional array), and display the average for each group.
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace for basic functionality
class Program // Define the main class
{
static void Main() // The entry point of the program
{
// Create a two-dimensional array to store marks for 2 groups of 10 pupils
double[,] marks = new double[2, 10];
double group1Sum = 0, group2Sum = 0; // Variables to store the sum of marks for each group
double group1Average, group2Average; // Variables to store the average marks for each group
// Ask the user to enter marks for the pupils
Console.WriteLine("Enter marks for 20 pupils (2 groups of 10):");
// Input marks for Group 1 (10 pupils)
for (int i = 0; i < 10; i++)
{
Console.Write($"Enter mark for pupil {i + 1} in Group 1: ");
while (!double.TryParse(Console.ReadLine(), out marks[0, i]) || marks[0, i] < 0)
{
Console.WriteLine("Invalid input. Please enter a valid mark (non-negative number).");
Console.Write($"Enter mark for pupil {i + 1} in Group 1: ");
}
group1Sum += marks[0, i]; // Add the mark to the sum for Group 1
}
// Input marks for Group 2 (10 pupils)
for (int i = 0; i < 10; i++)
{
Console.Write($"Enter mark for pupil {i + 1} in Group 2: ");
while (!double.TryParse(Console.ReadLine(), out marks[1, i]) || marks[1, i] < 0)
{
Console.WriteLine("Invalid input. Please enter a valid mark (non-negative number).");
Console.Write($"Enter mark for pupil {i + 1} in Group 2: ");
}
group2Sum += marks[1, i]; // Add the mark to the sum for Group 2
}
// Calculate the average marks for each group
group1Average = group1Sum / 10;
group2Average = group2Sum / 10;
// Display the averages for each group
Console.WriteLine($"\nAverage mark for Group 1: {group1Average:F2}");
Console.WriteLine($"Average mark for Group 2: {group2Average:F2}");
}
}