ms_learn_csharp/011_foreach_array_1/011_csharp.md

42 KiB
Raw Permalink Blame History

Guided project

Develop foreach and if-elseif-else structures to process array data in C#

Gain experience developing a console app that implements arrays, foreach loops, and if statements to achieve app specifications.

Introduction

Creating a code branch and iterating through a code block are essential capabilities for a developer. In C#, the if statement can be used to evaluate an expression and branch the execution path. The code block of a foreach statement can be used to iterate through each element of an array. Powerful and extensible applications can be created by combining the ability to iterate through an array with the ability to branch the execution path.

Suppose you're a teacher's assistant at a school. You've been working with a teacher to create an application that automates the grading process. Your C# programming skills have increased since you completed the initial version of your application. The teacher has asked you to update your application. The updates focus on using arrays, foreach statements, and if statements. The teacher also wants you to include extra credit assignments in your calculations of the final grades.

In this module, you'll be guided through the process of updating your Student Grading application. You'll use arrays to store student names and the scores of graded assignments, and you'll use foreach statements to iterate through array values. Each student's final grade will be calculated inside a foreach code block. You'll use an if statement to assign a final letter grade. Your completed application will output student grades using the teacher's score report specification.

By the end of this module, you'll have experience developing applications that use arrays, foreach statements, and if statements. You'll also be comfortable creating applications that efficiently process data using nested iteration and selection statements.

Note
This is a guided project module where youll complete an end-to-end project by following step-by-step instructions.

Prepare

In this guided project, you'll use Visual Studio Code to develop a C# application. The application will use arrays, foreach statements, and if statements to implement a list of design parameters. You'll begin by creating the array variables that contain your application data. To complete the project, you'll develop foreach and if statements that implement the application design goals.

Important
This module includes coding activities that require Visual Studio Code. You 'll need access to a development environment that has Visual Studio Code installed and configured for C# application development.

Project overview

You're developing a Student Grading application that automates the calculation of grades for each student in a class. The parameters for your application are:

  • Create a C# console application.

  • Start with four students. Each student has five exam scores.

  • Each exam score is an integer value, 0-100, where 100 represents 100% correct.

  • A student's overall exam score is the average of their five exam scores.

  • Criteria for extra credit assignments:

    • Include extra credit assignment scores in the student's scores array.
    • Extra credit assignments are worth 10% of an exam score (when calculating the final numeric grade).
    • Add extra credit assignment scores to the student's total exam score before calculating the final numeric grade.
    • Your application needs to automatically assign letter grades based on the calculated final score for each student.
  • Your application needs to output/display each students name and formatted grade.

  • Your application needs to support adding other students and scores with minimal impact to the code.

You've already completed an initial version of the application. The Starter code project for this Guided project module includes a Program.cs file that provides the following code features:

  • The code declares variables used to define student names and individual exam scores for each student.
  • The code includes the variables and algorithms used to sum the exam scores and calculate the average exam score for each student.
  • The code includes a hard coded letter grade that the developer must apply manually.
  • The code includes Console.WriteLine() statements to display the student grading report.

Your goal is to update the existing code to include the following features:

  • Use arrays to store student names and assignment scores.

  • Use a foreach statement to iterate through the student names as an outer program loop.

  • Use an if statement within the outer loop to identify the current student name and access that student's assignment scores.

  • Use a foreach statement within the outer loop to iterate through the assignment scores array and sum the values.

  • Use an updated algorithm within the outer loop to calculate the average exam score for each student.

  • Use an if-elseif-else construct within the outer loop to evaluate the average exam score and assign a letter grade automatically.

  • Integrate extra credit scores when calculating the student's final score and letter grade as follows:

    • Your code must detect extra credit assignments based on the number of elements in the student's scores array.
    • Your code must apply the 10% weighting factor to extra credit assignments before adding extra credit scores to the sum of exam scores.

The following list shows the letter grade that corresponds to numeric scores:

97 - 100   A+
93 - 96    A
90 - 92    A-
87 - 89    B+
83 - 86    B
80 - 82    B-
77 - 79    C+
73 - 76    C
70 - 72    C-
67 - 69    D+
63 - 66    D
60 - 62    D-
0  - 59    F

The update application needs to produce a formatted student grading report that appears as follows:

Student         Grade

Sophia:         92.2    A-
Andrew:         89.6    B+
Emma:           85.6    B
Logan:          91.2    A-

Setup

Use the following steps to prepare for the Guided project exercises.

  1. To download a zip file containing the Starter project code, select the following link: Lab Files.

  2. Unzip the download files.


Exercise

Create arrays and foreach loops

In this exercise, you'll review the Starter project code and then begin updating the application. Your first coding task will be creating the arrays that hold student exam scores. Once your application data is available in arrays, you'll begin working on a foreach loop that can be used to sum student grades. The detailed tasks that you'll complete during this exercise are:

  1. Code review: review the contents of the Program.cs file.

  2. Arrays: Create the arrays that store each student's assignment scores.

  3. Iteration: Create a foreach loop that can be used to sum Sophia's assignment grades.

  4. Calculate and display Sophia's average assignment grade.

  5. Verification test: perform a verification test for the code that you've developed in this exercise.

Important
You need to have completed the Setup instructions in the previous unit, Prepare, before you begin this Exercise.

Review the contents of the Program.cs file

In this task, you'll review the code that's provided as a Starter project for this module. The Program.cs file contains the initial version of the student grading application that you'll be updating.

Ensure that you have the GuidedProject folder open.

Take a few minutes to review the code in the Program.cs file.

Notice that the top portion of your code begins with a Using statement and a list of variable declarations.

// initialize variables - graded assignments 
int currentAssignments = 5;

int sophia1 = 90;
int sophia2 = 86;
int sophia3 = 87;
int sophia4 = 98;
int sophia5 = 100;

int andrew1 = 92;
int andrew2 = 89;
int andrew3 = 81;
int andrew4 = 96;
int andrew5 = 90;

int emma1 = 90;
int emma2 = 85;
int emma3 = 87;
int emma4 = 98;
int emma5 = 68;

int logan1 = 90;
int logan2 = 95;
int logan3 = 87;
int logan4 = 88;
int logan5 = 96;

The using statement enables you to write code that implements members of the System namespace without requiring you to specify System. For example, your code can use the Console.WriteLine() method without having to specify System.Console.WriteLine(). Among other things, the using statement makes your code easier to read.

Next, you see a comment line followed by a list of variables that are used to hold the scores of graded assignments for each student. Your first variable, currentAssignments is used to hold the number of exams that have been scored.

The assignment score variables represent a great opportunity to create and use arrays!

Scroll down and review the two groups of variable declaration code lines.

int sophiaSum = 0;
int andrewSum = 0;
int emmaSum = 0;
int loganSum = 0;

decimal sophiaScore;
decimal andrewScore;
decimal emmaScore;
decimal loganScore;

The first group of variables are integers that are being used to hold the sum of the exam scores.

The second group of variables are decimals that are used to hold the calculated average score. The code uses decimals here because an integer calculation rounds off the fractional portion of the calculated value.

Notice that you were using a unique variable for each student. This may provide another opportunity to slim down the number of code lines in your updated application.

It looks like the starter code begins score calculations next.

Scroll down a bit further and take a minute to review the following code:

sophiaSum = sophia1 + sophia2 + sophia3 + sophia4 + sophia5;
andrewSum = andrew1 + andrew2 + andrew3 + andrew4 + andrew5;
emmaSum = emma1 + emma2 + emma3 + emma4 + emma5;
loganSum = logan1 + logan2 + logan3 + logan4 + logan5;

sophiaScore = (decimal)sophiaSum / currentAssignments;
andrewScore = (decimal)andrewSum / currentAssignments;
emmaScore = (decimal)emmaSum / currentAssignments;
loganScore = (decimal)loganSum / currentAssignments;

The first group of equations is used to calculate the sum of the assignment scores for each student.

The second group of equations calculates the average score. Notice that the numerator is cast as a decimal to ensure the division retains the fractional component.

Take a minute to review the final code section:

Console.WriteLine("Student\t\tGrade\n");
Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");
Console.WriteLine("Andrew:\t\t" + andrewScore + "\tB+");
Console.WriteLine("Emma:\t\t" + emmaScore + "\tB");
Console.WriteLine("Logan:\t\t" + loganScore + "\tA-");

Console.WriteLine("Press the Enter key to continue");
Console.ReadLine();

This section prints the formatted output in accordance with the teacher's guidelines. The first line is a header line with column titles, followed by the names and scores for each student.

The Console.ReadLine() statement will pause the application so that the application user can review the output.

You will be using the TERMINAL panel to run .NET Command Line Interface (CLI) commands, such as dotnet build and dotnet run. The dotnet build command will compile your code and display error and warning messages related to your code syntax.

Important Ensure that terminal command prompt is open to the root of your project workspace. In this case, the root of your project workspace is the Starter folder, where your Starter.csproj and Program.cs files are located. When you run .NET CLI commands in the terminal, the commands will try to perform actions using the current folder location. If you try to run the dotnet build or dotnet run commands from a folder location that does not contain your files, the commands will generate error messages.

At the TERMINAL command prompt, to build your project code, enter the following command: dotnet build

After a couple seconds, you should see a message telling you that your build succeeded and that you have 0 Warning(s) and 0 Error(s).

Determining projects to restore...
All projects are up-to-date for restore.
Starter -> C:\Users\someuser\Desktop\GuidedProject\Starter\bin\Debug\net7.0\Starter.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Using .NET CLI commands is an easy way to build and run your applications.

At the Terminal command prompt, type dotnet run and then press Enter.

The dotnet run command will instruct the compiler to build your application and then, as long as there were no build errors, it will run your compiled code.

Important
The Starter project targets .NET 8 (in the Starter.csproj file). If you don 't have .NET 8 installed, the dotnet run command will generate an error. You can either install the .NET 8 SDK (recommended), or you can change the target framework in the Starter.csproj file to align with the version of .NET that you have installed in your environment.

Verify that your application produced the following output:

Student         Grade

Sophia:         92.2    A-
Andrew:         89.6    B+
Emma:           85.6    B
Logan:          91.2    A-
Press the Enter key to continue

In the TERMINAL panel, press the Enter key.

Your application was essentially paused after writing "Press the Enter key to continue" to the console. This behavior is caused by the Console.ReadLine() statement, which is used to collect user input in a console application. Your application will stop running once you press Enter.

That completes your code review. This application looks like the perfect opportunity to apply arrays, iterations, and selection statements.

It's time to get started on your updates!

Create the assignment score arrays

In this task, you'll replace the variables that hold the individual scores with arrays that hold the graded assignment scores for each student.

In the Visual Studio Code Editor, scroll to the top of the Program.cs file.

Create a blank code line below the line used to declare the currentAssignments variable.

On the new code line, to create an integer array that will be used for Sophia's assignment scores, enter the following code:

int[] sophiaScores = new int[5];

Notice that this code uses the new operator to specify that you're creating a new instance of an array. The set of square brackets in int[] tells the compiler that sophiaScores will be an integer array, while the set of square brackets in int[5] is used to specify the number of elements in the array.

You may recall that you have the option to assign array values as part of the declaration.

Note
In situations where you know the values of array elements ahead of time and when the values are unlikely to change, it makes sense to assign the array values when the array is declared. A good example would be an array that's used to hold the days of the week. Obviously, if the array values are unknown, you can't specify them when the array is declared, and you'll use the syntax that you entered above to declare your array.

To specify Sophia's assignment scores within the declaration, update the declaration for sophiaScores as follows:

int[] sophiaScores = new int[] { 90, 86, 87, 98, 100 };

Notice that the 5 that was used to specify the number of elements has been removed, and instead, you've included the scores of the five graded assignments.

Verify that the scores listed inside the {} match the individual scores for Sophia's assignments.

The five variables that are used to hold individual scores are as follows:

int sophia1 = 90;
int sophia2 = 86;
int sophia3 = 87;
int sophia4 = 98;
int sophia5 = 100;

Delete the code lines that declare the variables holding Sophia's individual scores.

Since you will be using the sophiaScores array to access Sophia's scores going forward, these variables are no longer needed.

To create an integer array that will be used for Andrew's assignment scores, enter the following code:

int[] andrewScores = new int[] {92, 89, 81, 96, 90};

Create the array declarations for the other students.

Be sure to name the arrays using the student's name, and then copy the values of their individual scores into {} on the array declaration line.

Verify that you've copied the individual scores into the array declarations accurately, and then delete the variables used to hold the individual scores for Andrew, Emma, and Logan.

The code at the top of your Program.cs file should now be similar to the following:

// initialize variables - graded assignments 
int currentAssignments = 5;

int[] sophiaScores = new int[] { 90, 86, 87, 98, 100 };
int[] andrewScores = new int[] { 92, 89, 81, 96, 90 };
int[] emmaScores = new int[] { 90, 85, 87, 98, 68 };
int[] loganScores = new int[] { 90, 95, 87, 88, 96 };

int sophiaSum = 0;

Good job, the scores arrays are declared and ready to use.

Create a foreach iteration to calculate Sophia's grade

In this task, you'll replace the existing code that's used to perform calculations with a foreach statement that iterates through Sophia's assignment scores. You will use the code block of the foreach loop to calculate the sum of Sophia's scores, and then calculate and display Sophia's grade.

Locate the code lines that are used to declare variables and perform calculations for the sum and average score values.

The code should look similar to the following:

int sophiaSum = 0;
int andrewSum = 0;
int emmaSum = 0;
int loganSum = 0;

decimal sophiaScore;
decimal andrewScore;
decimal emmaScore;
decimal loganScore;

sophiaSum = sophia1 + sophia2 + sophia3 + sophia4 + sophia5;
andrewSum = andrew1 + andrew2 + andrew3 + andrew4 + andrew5;
emmaSum = emma1 + emma2 + emma3 + emma4 + emma5;
loganSum = logan1 + logan2 + logan3 + logan4 + logan5;

sophiaScore = (decimal)sophiaSum / currentAssignments;
andrewScore = (decimal)andrewSum / currentAssignments;
emmaScore = (decimal)emmaSum / currentAssignments;
loganScore = (decimal)loganSum / currentAssignments;

Delete the code lines that are used to perform the sum calculations.

You'll be writing the code to calculate the sum inside a foreach loop once you're finished cleaning up.

Delete the code lines that declare int and decimal variables for Andrew, Emma, and Logan.

Note
Leave the code lines that declare variables for Sophia.

Delete the code lines that are used to calculate the average score for Andrew, Emma, and Logan.

Note
Leave the code line containing the average score calculation for Sophia.

Scroll down to the bottom of your code, and then delete the code lines used to report grades for Andrew, Emma, and Logan.

Verify that your updated Program.cs file contains the following code:

Note
Add or remove blank code lines so that your code matches the code shown below.

// initialize variables - graded assignments 
int currentAssignments = 5;

int[] sophiaScores = new int[] { 90, 86, 87, 98, 100 };
int[] andrewScores = new int[] { 92, 89, 81, 96, 90 };
int[] emmaScores = new int[] { 90, 85, 87, 98, 68 };
int[] loganScores = new int[] { 90, 95, 87, 88, 96 };

int sophiaSum = 0;

decimal sophiaScore;

sophiaScore = (decimal)sophiaSum / currentAssignments;

Console.WriteLine("Student\t\tGrade\n");
Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");

Console.WriteLine("Press the Enter key to continue");
Console.ReadLine();

Create a blank code line after the line used to declare sophiaScore.

To create a foreach statement that you will use to iterate through Sophia's scores, enter the following code:

foreach (int score in sophiaScores){
}

Notice that this code instantiates an integer variable named score as part of the foreach statement. You will be using score inside the code block of your foreach to access the values of the sophiaScores array.

To create the equation that sums Sophia's score, update the foreach code block as follows:

foreach (int score in sophiaScores){
    // add the exam score to the sum
    sophiaSum += score;    
}

Notice that this code is using the += operator to add the value of score to sophiaSum inside your foreach loop. Developers often use += as a shortcut when calculating a sum. This equation is equivalent to the following:

sophiaSum = sophiaSum + score;

Once your foreach loop has iterated through all of the values in the sophiaScores array, sophiaSum will contain the sum of her scores.

Take a minute to review your code.

Your code should now look similar to the following:

// initialize variables - graded assignments 
int currentAssignments = 5;

int[] sophiaScores = new int[] { 90, 86, 87, 98, 100 };
int[] andrewScores = new int[] { 92, 89, 81, 96, 90 };
int[] emmaScores = new int[] { 90, 85, 87, 98, 68 };
int[] loganScores = new int[] { 90, 95, 87, 88, 96 };

int sophiaSum = 0;

decimal sophiaScore;

foreach (int score in sophiaScores){
    // add the exam score to the sum
    sophiaSum += score;
}

sophiaScore = (decimal)sophiaSum / currentAssignments;

Console.WriteLine("Student\t\tGrade\n");
Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");

Console.WriteLine("Press the Enter key to continue");
Console.ReadLine();

At this point, you've created the scores arrays for all students and you're calculating the sum of Sophia's score inside a foreach loop that iterates through her scores. You still have a long way to go to complete all of the planned updates, but this is a good point to check your progress.

Check your work

In this task, you'll run the application to verify that your code logic is working as expected.

  1. Ensure that you've saved your changes to the Program.cs file.

  2. In the Visual Studio Code EXPLORER panel, right-click Starter, and then select Open in Integrated Terminal.

  3. You will be using the Terminal panel to enter .NET CLI commands that build and run your applications.

  4. Verify that the Terminal command prompt lists the Starter folder as the current folder location.

At the TERMINAL command prompt, to build your project code, enter the following command: dotnet build

After a couple seconds, you should see a message telling you that your build succeeded and that you have 0 Warning(s) and 0 Error(s).

Determining projects to restore...
All projects are up-to-date for restore.
Starter -> C:\Users\someuser\Desktop\GuidedProject\Starter\bin\Debug\net6.0\Starter.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

If you see Error or Warning messages, you need to fix them before continuing.

Error and Warning messages list the code line where the issue can be found. The following is an example of a Build FAILED error message:

C:\Users\someuser\Desktop\GuidedProject\Starter\Program.cs(53,18): error CS1002: ; expected [C:\Users\someuser\Desktop\GuidedProject\Starter\Starter.csproj]

This message tells you the type of error that was detected and where to find it. In this case, the message tells you that the Program.cs file contains an error - error CS1002: ; expected. The ; expected suggests that the developer forgot to include a ; at the end of a statement. The Program.cs(53,18) portion of the message tells you that the error is located on code line 53, at a position 18 characters in from the left.

A syntax error like this prevents the Build task from succeeding (Build FAILED). Some Build messages provide a "Warning" instead of an "Error", which means there is something to be concerned with, but you can try running the program anyway (Build succeeded).

Once you have fixed the issues and saved your updates, you can run the dotnet build command again. Continue updating and saving your code until you have 0 Warning(s) and 0 Error(s).

Note
If you have trouble resolving an issue on your own, you can examine the Program.cs code in the Final folder that's included as part of the download that you completed during Setup. The Program.cs code in the Final folder represents the conclusion of all exercises in this module, so it will include code that you have not created yet. It may look considerably different than the Program.cs code that you have developed at this point in the Guided project. However, you can try examining the Program.cs code in Final to help you isolate and fix an issue in your code if you need to. Try not to use the code in the Final folder as a guide if you can avoid it. Remember that you learn from your mistakes and that every developer spends time finding and fixing errors.

At the Terminal command prompt, type dotnet run and then press Enter.

The dotnet run command instructs the compiler to build your application and then, as long as no errors were detected, will run the compiled code.

Verify that your code produced the following output:

Student         Grade

Sophia:         92.2    A-
Press the Enter key to continue

Congratulations, you've built an application that uses a foreach loop to iterate through the elements of an array and perform calculations based on the contents of the array. You're making great progress on the required app updates!


Exercise

Construct a nested loop structure for student grade calculations

In this exercise, you'll add a string array to hold the student names, and then implement a nested foreach structure that iterates through the student names in an outer loop and student scores in the inner loop. You'll begin by constructing the studentNames array and a foreach loop that iterates through the array elements. Next, you'll move the code that's used to calculate Sophia 's grades into the code block of the "names" loop. Finally, you'll implement the code logic that uses the student's name to access their scores array, calculate their average score, and write their grade to the console. The detailed tasks that you'll complete during this exercise are:

Create names array: Create a student names array.

Create outer loop: Create a foreach loop that iterates through the student names.

Develop outer loop code block: Relocate the code that calculates and reports Sophia's score, placing it in the code block of the "names" loop.

Update calculations and reporting: Update the code that performs student score calculations using a new scores array.

Important
You need to have completed this module's previous Exercise, "Create arrays and foreach loops", before you begin this Exercise.

Create a student names array and outer foreach loop

In this task, you'll create a student names array and a foreach loop that iterates through the student names.

Scroll to the top of your code file, and then locate the code lines that are used to declare the scores arrays.

Create a blank code line below the declaration of the scores arrays.

Your blank code line should be located between the lines used to declare the scores arrays and the line used to declare sophiaSum.

To create a string array named studentNames that holds the names of the students, enter the following code:

// Student names
string[] studentNames = new string[] { "Sophia", "Andrew", "Emma", "Logan" };

Notice that you've specified the student names as part of the declaration.

To create a foreach statement that you can use to iterate through the student names, enter the following code:

foreach (string name in studentNames){
}

To verify that your foreach loop is iterating through the studentNames array as intended, update the code block of the foreach statement as follows:

foreach (string name in studentNames){
    Console.WriteLine($"{name}");

}

Take a minute to review the code that you've created.

// Student names
string[] studentNames = new string[] { "Sophia", "Andrew", "Emma", "Logan" };

foreach (string name in studentNames){
    Console.WriteLine($"{name}");

}

Your code will use this foreach loop as the outer loop of your application. During this exercise, you'll implement the following logic in your application:

For each of the students in the studentNames array, your application will:

  • determine the current student.
  • access the current student's scores.
  • calculate the current student's grade (sum and average).
  • write the current student's grade to the console.

For now, however, you'll just write the names of the students to the console.

At the Terminal command prompt, type dotnet build and then press Enter.

The dotnet build command instructs the compiler to build the application. If any errors are detected, they will be reported.

If you see Error or Warning messages, you need to fix them before continuing.

At the Terminal command prompt, type dotnet run and then press Enter.

Verify that your code produced the following output:

Sophia
Andrew
Emma
Logan
Student         Grade

Sophia:         92.2    A-
Press the Enter key to continue

Note
If you don't see the list of student names above Sophia's score report, go back and verify that you entered your code correctly.

Calculate Sophia's score inside the outer names loop

In this task, you'll relocate the code that calculates and reports Sophia's score, placing it in the code block of the "names" loop.

Locate the code lines that are used to calculate and report Sophia's grade.

int sophiaSum = 0;

decimal sophiaScore;

foreach (int score in sophiaScores){
    // add the exam score to the sum
    sophiaSum += score;

}

sophiaScore = (decimal)sophiaSum / currentAssignments;

Console.WriteLine("Student\t\tGrade\n");
Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");

Note
Your next step will be to move this code from its current location to the code block of the "names" foreach loop.

Use a cut-and-paste operation to move the code that calculates and reports Sophia's grade to the code block of the "names" foreach loop.

If you're unsure how to cut-and-paste in Visual Studio Code, try the approach described in the following steps:

Select the code that's used to calculate and report Sophia's grade. Position the cursor on the blank code line below the following code: Console.WriteLine($"{name}");

Update your code to display proper code line indentation.

Ensure that your updates match the following code:

// Student names
string[] studentNames = new string[] { "Sophia", "Andrew", "Emma", "Logan" };

foreach (string name in studentNames){
    Console.WriteLine($"{name}");
    int sophiaSum = 0;

    decimal sophiaScore;

    foreach (int score in sophiaScores)    {
        // add the exam score to the sum
        sophiaSum += score;

    }

    sophiaScore = (decimal)sophiaSum / currentAssignments;

    Console.WriteLine("Student\t\tGrade\n");
    Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");
}

Console.WriteLine("Press the Enter key to continue");
Console.ReadLine();

Notice that at this point, your code will calculate and report Sophia's score regardless of the name of the current student. You will address that shortly.

Delete the following code:

Console.WriteLine($"{name}");

On the blank code line that you just created, enter the following code:

if (name == "Sophia"){    

Create a blank code line after the code that's used to write Sophia's grade to the console.

To close the code block of the if statement, enter the following code:

}    

Update your code to display proper code line indentation.

Tip
Use the Format Document command to keep your code formatting updated. Right-click inside the Visual Studio Code Editor panel, and then select Format Document from the popup menu.

Take a minute to review your code.

Your code should match the following code:

// initialize variables - graded assignments 
int currentAssignments = 5;

int[] sophiaScores = new int[] { 90, 86, 87, 98, 100 };
int[] andrewScores = new int[] { 92, 89, 81, 96, 90 };
int[] emmaScores = new int[] { 90, 85, 87, 98, 68 };
int[] loganScores = new int[] { 90, 95, 87, 88, 96 };

// Student names
string[] studentNames = new string[] {"Sophia", "Andrew", "Emma", "Logan"};

foreach (string name in studentNames){
    if (name == "Sophia")    {
        int sophiaSum = 0;
        decimal sophiaScore;

        foreach (int score in sophiaScores){
            // add the exam score to the sum
            sophiaSum += score;
        }

        sophiaScore = (decimal)(sophiaSum) / currentAssignments;

        Console.WriteLine("Student\t\tGrade\n");
        Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");
    }
}

Console.WriteLine("Press the Enter key to continue");
Console.ReadLine();

Notice that the if statement inside your outer foreach code block limits which student's grade is calculated and reported. This isn't exactly what you need, but it's a step in the right direction.

Important
The Terminal command prompt must be displaying the folder path for your Program.cs file.

At the Terminal command prompt, type dotnet build and then press Enter.

The dotnet build command instructs the compiler to build the application. If any errors are detected, they will be reported.

If you see Error or Warning messages, you need to fix them before continuing.

At the Terminal command prompt, type dotnet run and then press Enter.

Verify that your code produced the following output:

Student         Grade

Sophia:         92.2    A-

Note
If you still see the list of student names displayed above Sophia's score report, make sure that you saved your updates.

Update the nested loop to calculate all student scores

In this task, you'll update the code that performs student score calculations using a new scores array. You'll begin by creating an array named studentScores that can be used to hold the scores of any student. Next, you'll create an if .. elseif construct that uses the current student's name to assign their scores array to studentScores. Finally, you'll update the code that calculates and reports the student's grades. When you're done, the report should include the name and numeric score for all students.

Create a blank code line below the declaration of the studentNames array.

The blank line should be above the outer foreach statement.

To create an integer array that you can use to hold the scores of the current student, enter the following code:

int[] studentScores = new int[10];

Notice that this code doesn't assign any values to the array at this point. You simply specify that the array can contain 10 elements.

Create a blank code line at the top of the outer foreach code block.

The blank line should be inside the foreach code block and above the if statement that evaluates whether name is equal to Sophia.

To create a string variable that will be used to hold the name of the current student, enter the following code:

string currentStudent = name;

Note
You could continue to use name to track the name of the current student as you iterate through the names array, but using currentName will make it easier to understand your code logic as you build out your application in the upcoming steps.

To substitute currentStudent for name in the if statement that evaluates whether name is equal to Sophia, update your code as follows:

if (currentStudent == "Sophia")

Move the code that calculates and reports Sophia's score to a location below the code block.

You're moving all of the code that's in the code block to a location below the code block. The reason for doing this will become apparent during the next few steps.

Verify that the code in your outer foreach code block matches the following code:

    ...
    string currentStudent = name;

    if (currentStudent == "Sophia"){
    }

    int sophiaSum = 0;
    decimal sophiaScore;

    foreach (int score in sophiaScores){
        // add the exam score to the sum
        sophiaSum += score;

    }

    sophiaScore = (decimal)sophiaSum / currentAssignments;

    Console.WriteLine("Student\t\tGrade\n");
    Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");

}

To assign the sophiaScores array to studentScores when currentStudent == "Sophia", update your if statement code as follows:

if (currentStudent == "Sophia")
    studentScores = sophiaScores;

Notice that you've removed the curly braces from the if statement code block during this code update.

To add an else if statement that assigns the andrewScores array to studentScores when currentStudent == "Andrew", enter the following code:

else if (currentStudent == "Andrew")
    studentScores = andrewScores;

Create another else if statement to assign the emmaScores array to studentScores when currentStudent == "Emma".

Create an else if statement to assign the loganScores array to studentScores when currentStudent == "Logan".

Ensure that your foreach code block matches the following code:

foreach (string name in studentNames){
    string currentStudent = name;

    if (currentStudent == "Sophia")
        studentScores = sophiaScores;

    else if (currentStudent == "Andrew")
        studentScores = andrewScores;

    else if (currentStudent == "Emma")
        studentScores = emmaScores;

    else if (currentStudent == "Logan")
        studentScores = loganScores;

    int sophiaSum = 0;

    decimal sophiaScore;

    foreach (int score in sophiaScores){
        // add the exam score to the sum
        sophiaSum += score;

    }

    sophiaScore = (decimal)sophiaSum / currentAssignments;

    Console.WriteLine("Student\t\tGrade\n");
    Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");

}

Next, you need to update the inner foreach loop to use studentScores and "depersonalize" the variables that you use in your calculations.

To substitute studentScores for sophiaScores in the foreach loop that iterates through the scores array, update your code as follows:

foreach (int score in studentScores)

To replace the Sophia-specific variable declarations with more generic names, update your code as follows:

int sumAssignmentScores = 0;

decimal currentStudentGrade = 0;

These two variable declarations are intended to replace the following Sophia -specific variable declarations:

int sophiaSum = 0;

decimal sophiaScore;

To apply the new variable name to the equation used to sum student scores, update your inner foreach code block as follows:

foreach (int score in studentScores){
    // add the exam score to the sum
    sumAssignmentScores += score;
}

To apply the new variable name to the equation used to calculate the average score, update your code as follows:

currentStudentGrade = (decimal)(sumAssignmentScores) / currentAssignments;

Take a minute to review your code.

int[] studentScores = new int[10];

foreach (string name in studentNames){
    string currentStudent = name;

    if (currentStudent == "Sophia")
        studentScores = sophiaScores;

    else if (currentStudent == "Andrew")
        studentScores = andrewScores;

    else if (currentStudent == "Emma")
        studentScores = emmaScores;

    else if (currentStudent == "Logan")
        studentScores = loganScores;

    // initialize/reset the sum of scored assignments
    int sumAssignmentScores = 0;

    // initialize/reset the calculated average of exam + extra credit scores
    decimal currentStudentGrade = 0;

    foreach (int score in studentScores)
    {
        // add the exam score to the sum
        sumAssignmentScores += score;
    }

    currentStudentGrade = (decimal)(sumAssignmentScores) / currentAssignments;

    Console.WriteLine("Student\t\tGrade\n");
    Console.WriteLine("Sophia:\t\t" + sophiaScore + "\tA-");

}

Your nested foreach loops will now iterate through the student names and use the student's scores to calculate their grades, but you still need to update the code used to generate the score report.

To print the student name and calculated score to the console, update the second Console.WriteLine statement as follows:

Console.WriteLine($"{currentStudent}\t\t{currentStudentGrade}\t?");

Notice that this code has replaced the letter grade assignment with a "?". You will work on automating the assignment of letter grades in the next exercise.

Move the Console.WriteLine statement that's used to write the column labels of your score report to the location just above the outer foreach loop.

You don't want to repeat the column headers for each student score, so you move this code to a point above the outer foreach loop.

Take a minute to review your application code.

Your full application should now match the following code:

// initialize variables - graded assignments 
int currentAssignments = 5;

int[] sophiaScores = new int[] { 90, 86, 87, 98, 100 };
int[] andrewScores = new int[] { 92, 89, 81, 96, 90 };
int[] emmaScores = new int[] { 90, 85, 87, 98, 68 };
int[] loganScores = new int[] { 90, 95, 87, 88, 96 };

// Student names
string[] studentNames = new string[] { "Sophia", "Andrew", "Emma", "Logan" };

int[] studentScores = new int[10];

// Write the Report Header to the console
Console.WriteLine("Student\t\tGrade\n");

foreach (string name in studentNames){
    string currentStudent = name;

    if (currentStudent == "Sophia")
        studentScores = sophiaScores;

    else if (currentStudent == "Andrew")
        studentScores = andrewScores;

    else if (currentStudent == "Emma")
        studentScores = emmaScores;

    else if (currentStudent == "Logan")
        studentScores = loganScores;

    // initialize/reset the sum of scored assignments
    int sumAssignmentScores = 0;

    // initialize/reset the calculated average of exam + extra credit scores
    decimal currentStudentGrade = 0;

    foreach (int score in studentScores){
        // add the exam score to the sum
        sumAssignmentScores += score;
    }

    currentStudentGrade = (decimal)(sumAssignmentScores) / currentAssignments;

    Console.WriteLine($"{currentStudent}\t\t{currentStudentGrade}\t?");
}

With the code that generates the student's score report updated; it appears that you're ready to check your work.

Check your work

In this task, you'll run the application to verify that your code logic is working as expected.

Ensure that you've saved your changes to the Program.cs file.

At the Terminal command prompt, type dotnet build and then press Enter.

If you see Error or Warning messages, you need to fix them before continuing.

At the Terminal command prompt, type dotnet run and then press Enter.

Verify that your code produced the following output:

Student         Grade

Sophia          92.2    ?
Andrew          89.6    ?
Emma            85.6    ?
Logan           91.2    ?
Press the Enter key to continue

Congratulations, your application has come a long way from where you started out. You are making efficient use of arrays and foreach iterations, and you've integrated an if statement that enables your code to select the correct scores array.