C# Programming Fundamentals: Arrays, Loops, and Decisions

Life Expectancy Analysis with Parallel Arrays

This exercise demonstrates the use of parallel arrays to store and process life expectancy data by gender.

Instructions

  1. Create four parallel arrays containing the life expectancy data as shown in Table 1.
  2. Iterate through the parallel arrays to count and display a list of country names where the life expectancy for both genders exceeds 80 years.
  3. Prompt the user to input a country code.
  4. Use a loop to display the country name and life expectancies for males, females, and both genders combined based on the country code entered.
    • If the country code is not found in the array, display “The country is not found.”
    • The life expectancy for both genders combined can be approximated by calculating the average life expectancies for males and females.
    • For example, in Japan (JP), the life expectancy for both genders combined is (87.97 + 81.91) / 2 = 84.94.
  5. Finally, iterate through the arrays to count and display all the country names where males have a higher life expectancy than females, pertaining specifically to the country code that was inputted.

Table 1: Life Expectancies for Specific Countries

Note: This data may change, so do not hard-code the array’s length.

Country CodesCountry NamesFemalesMales
JPJapan87.9781.91
CACanada84.9481.07
USUnited States82.2377.27
MXMexico78.3671.76
INIndia73.6570.52

C# Implementation

{
    // Define the parallel arrays
    string[] countryCodes = {"JP", "CA", "US", "MX", "IN"};
    string[] countryNames = {"Japan", "Canada", "United States", "Mexico", "India"};
    double[] lifeExpectancyFemales = {87.97, 84.94, 82.23, 78.36, 73.65};
    double[] lifeExpectancyMales = {81.91, 81.07, 77.27, 71.76, 70.52};

    // 1. Display countries where life expectancy for both genders exceeds 80 years
    Console.WriteLine("Countries where life expectancy for both genders exceeds 80 years:");
    for (int i = 0; i < countryCodes.Length; i++)
    {
        double avgLifeExpectancy = (lifeExpectancyFemales[i] + lifeExpectancyMales[i]) / 2;
        if (avgLifeExpectancy > 80)
        {
            Console.WriteLine(countryNames[i]);
        }
    }

    // 2. Prompt user for country code
    Console.Write("\nEnter a country code: ");
    string userInput = Console.ReadLine().Trim().ToUpper();

    // 3. Display life expectancy details for the entered country
    int index = Array.IndexOf(countryCodes, userInput);
    if (index != -1)
    {
        double avgLifeExpectancy = (lifeExpectancyFemales[index] + lifeExpectancyMales[index]) / 2;
        Console.WriteLine($"\nCountry: {countryNames[index]}");
        Console.WriteLine($"Life Expectancy (Females): {lifeExpectancyFemales[index]}");
        Console.WriteLine($"Life Expectancy (Males): {lifeExpectancyMales[index]}");
        Console.WriteLine($"Life Expectancy (Both Genders Combined): {avgLifeExpectancy:F2}");
        
        // 4. Check if males have higher life expectancy than females
        if (lifeExpectancyMales[index] > lifeExpectancyFemales[index])
        {
            Console.WriteLine("\nMales have a higher life expectancy than females in this country.");
        }
    }
    else
    {
        Console.WriteLine("The country is not found.");
    }
}

Integer Array Manipulation in C#

Instructions

  1. Initialize an array a capable of holding ten integers. The array will initially contain `[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`.
  2. Using a loop, assign array a with values from -5 to 5, excluding zero. Print the elements. The resulting array should be `[-5, -4, -3, -2, -1, 1, 2, 3, 4, 5]`.
  3. Use a loop to allow a user to input exactly ten positive integers (greater than zero) into a new array b. Prompt the user to re-enter the number if they enter a zero or a negative number.
  4. Display the average value of all elements in array b using a loop.
  5. Multiply each corresponding pair of elements from arrays a and b, updating array a with the result. Print all elements in the updated array a. For example, if array b is `[3, 2, 5, 1, 4, 7, 6, 9, 8, 10]`, array a will become `[-15, -8, -15, -2, -4, 7, 12, 27, 32, 50]`.
  6. Use a loop to calculate and display the average of all elements in array b that are larger than their preceding elements. For example, if array b is `[3, 2, 5, 1, 4, 7, 6, 9, 8, 10]`, the average is (5 + 4 + 7 + 9 + 10) / 5 = 7.
  7. Show an error message if the average cannot be calculated. For example, if array b contains values in descending order like `[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]`, this average cannot be determined.

C# Implementation

int[] a = new int[10];

int n = -5;
for(int i = 0; i < 10; i++){
    if(n == 0) n = 1;
    a[i] = n++;
}

Console.Write($"{string.Join(" ", a)}");

int[] b = new int[10];

for (int i = 0; i < 10; i++){
    int input;
    do{
        Console.WriteLine($"Enter 10 positive integers.");
        input = Convert.ToInt32(Console.ReadLine());
        if (input <= 0){
            Console.WriteLine("Invalid Input!");
        }
    } while (input <= 0);
    b[i] = input;
}

int sum = 0;
int count = 0;
double average;

for (int i = 0; i < 10; i++){
    sum += b[i];
}
average = sum / 10.0;
Console.WriteLine($"Average of array b: {average:F2}");

for (int i = 0; i < 10; i++) {
    a[i] *= b[i];
}
Console.WriteLine("Updated array a: " + string.Join(" ", a));

sum = 0;
count = 0;
for (int i = 1; i < 10; i++){
    if(b[i] > b[i-1]){
        sum += b[i];
        count++;
    }
}

if (count > 0) {
    average = sum / (double)count;
    Console.WriteLine($"Average of elements in b larger than their preceding elements: {average:F2}");
} else {
    Console.WriteLine("Error: No elements in b are larger than their preceding elements.");
}

Custom Number Sequence Iteration

Instructions

  1. Print numbers between 1.0 and 5.0.
  2. Each pair of consecutive numbers printed should have a difference of 0.1, except for those around whole numbers (e.g., 1.0, 2.0), which should have a difference of 0.2 (e.g., 1.7, 1.8, 2.0, 2.2, 2.3, …).
  3. Calculate and display the total number of values printed.

Expected Output:

1.0, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 2.0, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 3.0, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 4.0, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 5.0
Count = 33.

C# Implementation

using System;

class Program
{
    static void Main()
    {
        double start = 1.0;
        double end = 5.0;
        double step = 0.1;
        int count = 0;

        for (double i = start; i <= end; i += step)
        {
            Console.Write(i.ToString("0.0") + ", ");
            count++;

            // Adjust step size around whole numbers
            if (Math.Abs(i + step - Math.Round(i + step)) < 0.05)
            {
                i += step; // Additional step to make the jump 0.2
            }
        }
        Console.WriteLine("\nCount = " + count);
    }
}

Core C# Looping and Array Concepts

Sentinel-Controlled Loops

A sentinel-controlled loop continues executing until a special value (sentinel) is encountered, which signals the loop to stop. Here’s an example in C# where the user enters numbers, and the loop stops when they enter -1 (the sentinel value):

using System;

class Program
{
    static void Main()
    {
        int number;
        int sum = 0;
        
        Console.WriteLine("Enter numbers to sum (enter -1 to stop):");

        while (true)
        {
            Console.Write("Enter a number: ");
            number = int.Parse(Console.ReadLine());

            if (number == -1) // Sentinel value
                break;

            sum += number;
        }

        Console.WriteLine("Total sum: " + sum);
    }
}

Array Accumulation

An array with accumulations involves summing up (or performing another operation on) the elements of an array. Here’s a C# example where we calculate the sum and average of numbers stored in an array:

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 10, 20, 30, 40, 50 }; // Array of numbers
        int sum = 0;  // Accumulator for sum

        // Accumulate the sum of array elements
        for (int i = 0; i < numbers.Length; i++)
        {
            sum += numbers[i];
        }

        // Calculate the average
        double average = (double)sum / numbers.Length;

        // Display results
        Console.WriteLine("Sum: " + sum);
        Console.WriteLine("Average: " + average);
    }
}

Searching Multiple Arrays

Here’s a C# program that demonstrates searching through multiple arrays to find specific conditions. The program finds students who scored above 80, displays their names, indexes, total count, and sum of their scores.

using System;

class Program
{
    static void Main()
    {
        // Two related arrays: student names and their scores
        string[] students = { "Alice", "Bob", "Charlie", "David", "Eve" };
        int[] scores = { 75, 85, 90, 60, 95 };

        int sum = 0;  // Accumulate scores that meet the condition
        int count = 0; // Count of students meeting the condition

        Console.WriteLine("Students who scored above 80:");

        // Loop through the arrays
        for (int i = 0; i < students.Length; i++)
        {
            if (scores[i] > 80) // Condition: score greater than 80
            {
                Console.WriteLine($"Index: {i}, Name: {students[i]}, Score: {scores[i]}");
                sum += scores[i];
                count++;
            }
        }

        // Display total count and sum of qualifying scores
        Console.WriteLine($"\nTotal students with scores above 80: {count}");
        Console.WriteLine($"Sum of their scores: {sum}");
    }
}

How This Works

  • Two arrays:
    • students[] stores names.
    • scores[] stores corresponding scores.
  • Loop through both arrays, checking for scores above 80.
  • Print student details (name, index, score) if the condition is met.
  • Accumulate sum and count of scores that meet the condition.
  • Print the total count and sum at the end.

ISAM 3333 Test 2 Cheat Sheet


Chapter 4 – Making Decisions

Logic and Decision Making

  • Use if statements for simple conditions.
  • Use if-else for two-way branching.
  • Use nested ifs for multiple conditions.
  • Use switch statements (optional) for multiple cases.
  • Use the NOT operator (!) to negate conditions.
  • Avoid errors such as:
    • Using = instead of == in conditions.
    • Forgetting braces {} in multi-line if statements.

Examples

if (score >= 90) {
    Console.WriteLine("Grade: A");
} else if (score >= 80) {
    Console.WriteLine("Grade: B");
} else {
    Console.WriteLine("Grade: C or below");
}

Chapter 5 – Looping

While Loop (Sentinel-controlled loops)

int sum = 0;
int num;
Console.WriteLine("Enter numbers (-1 to stop):");
while ((num = int.Parse(Console.ReadLine())) != -1) {
    sum += num;
}
Console.WriteLine("Total: " + sum);

For Loop (Counting Loops)

for (int i = 0; i < 10; i++) {
    Console.WriteLine(i);
}

Do-While Loop (Executes at least once)

int x;
do {
    Console.Write("Enter a number: ");
    x = int.Parse(Console.ReadLine());
} while (x != 0);

Loop Optimization Tips

  • Avoid unnecessary computations inside loops.
  • Use break to exit loops early when necessary.
  • Use continue to skip an iteration.

Chapter 6 – Arrays

Declaring and Initializing Arrays

int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;

Looping Through an Array

int[] arr = {10, 20, 30, 40, 50};
for (int i = 0; i < arr.Length; i++) {
    Console.WriteLine(arr[i]);
}

Accumulation with Arrays

int[] values = { 5, 10, 15, 20 };
int total = 0;
for (int i = 0; i < values.Length; i++) {
    total += values[i];
}
Console.WriteLine("Sum: " + total);

Searching an Array (Manual Search)

int[] arr = {10, 20, 30, 40, 50};
int searchValue = 30;
bool found = false;

for (int i = 0; i < arr.Length; i++) {
    if (arr[i] == searchValue) {
        Console.WriteLine("Found at index: " + i);
        found = true;
        break;
    }
}
if (!found) {
    Console.WriteLine("Not found");
}

Parallel Arrays Example

string[] names = {"Alice", "Bob", "Charlie"};
int[] scores = {85, 92, 78};

for (int i = 0; i < names.Length; i++) {
    Console.WriteLine(names[i] + " scored " + scores[i]);
}

Counting and Summing with Parallel Arrays

int sum = 0, count = 0;
for (int i = 0; i < scores.Length; i++) {
    if (scores[i] > 80) {
        sum += scores[i];
        count++;
    }
}
Console.WriteLine("Total Sum: " + sum);
Console.WriteLine("Count: " + count);

Key Takeaways

  • Decision making: Use if, if-else, switch, and logical operators.
  • Loops: Know while, for, and do-while loops.
  • Arrays: Understand declaration, access, searching, and parallel arrays.
  • Sentinel-controlled loops: Use while loops with a stopping condition.
  • Accumulations: Keep track of sums and counts using loops.
  • No built-in functions allowed: Implement searches manually using loops.

Good luck on your test! 🚀