'How to do while loop/Do while loop with sentinel value with switch

Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.

    // declare variables

    char deptCode = ' ';
    int count = 0;
    double markVal, sum = 0, average = 0.0;

    

    {
        Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
        deptCode = Convert.ToChar(Console.ReadLine());
        while (char.ToUpper(deptCode) != 'Q')

            do
            {
                Console.Write("Enter a mark between 0 and 100 => ");
                markVal = Convert.ToDouble(Console.ReadLine());

                {
            Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
            deptCode = Convert.ToChar(Console.ReadLine());
        } while (markVal >= 0 && markVal <= 100);



        count++;

        average = (double)sum / count;

        Console.WriteLine("***Error, Please Enter Valid Mark");

        Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
        Console.WriteLine("The Average mark for Biology Students is {0}", average);
        Console.WriteLine("The Average mark for Physics Students is {0}", average);

        Console.ReadLine();

        {
        

       


Solution 1:[1]

I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.

One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.

  1. An endless loop that lets the user enter any number of discipline marks.
  2. An endless loop when we ask the user which discipline to use
  3. And an endless loop when we ask the user for a Mark between 0 and 100

When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.

And finally when the user presses the ‘q’ character, then we can output the averages.

So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…

private static char GetDisciplineFromUser() {
  string userInput;
  while (true) {
    Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
    userInput = Console.ReadLine().ToLower();
    if (userInput.Length > 0) {
      if (userInput[0] == 'c' || userInput[0] == 'b' ||
        userInput[0] == 'p' || userInput[0] == 'q') {
        return userInput[0];
      }
    }
    Console.WriteLine("Invalid discipline => " + userInput + " try again.");
  }
}

Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.

Next is the endless loop to get the Mark from the user and may look something like…

private static double GetMarkFromUser() {
  string userInput;
  while (true) {
    Console.WriteLine("Enter a mark between 0 and 100 => ");
    userInput = Console.ReadLine().Trim();
    if (double.TryParse(userInput, out double mark)) {
      if (mark >= 0 && mark <= 100) {
        return mark;
      }
    }
    Console.WriteLine("Invalid Mark => " + userInput + " try again.");
  }
}

Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.

These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…

int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;

Now you have something to store the users input in.

And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.

static void Main(string[] args) {
  //  you will need some kind of storage for each discipline.. see above...
  char currentDiscipline = 'x';
  double currentMark;
  while (currentDiscipline != 'q') {
    currentDiscipline = GetDisciplineFromUser();
    if (currentDiscipline != 'q') {
      currentMark = GetMarkFromUser();
      switch (currentDiscipline) {
        case 'c':
          // add 1 to total number of CS marks
          // add currentMarkValue to the total of CS marks
          break;
        case 'b':
          // add 1 to total number of Biology marks
          // add currentMarkValue to the total of Biology marks
          break;
        default: // <- we know for sure that only p could be left
          // add 1 to total number of Physics marks
          // add currentMarkValue to the total of Physics marks
          break;
      }
    }
  }
  Console.WriteLine("Averages ------");
  //Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
  //Console.WriteLine("The Average mark for Biology Students is {0}", ...);
  //Console.WriteLine("The Average mark for Physics Students is {0}", ...);
  Console.ReadLine();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JohnG