Solved

How to use loops

Posted on 2011-09-17
20
457 Views
Last Modified: 2013-12-17
Experts,
Details
Here is what I am trying to do, I have a program that needs to add the scores of 5 judges, subtract the highest and lowest scores / 3 and multiply by the level of difficulty (variable named =degreeDiff) and output the total score.

Problem
The variable called score only remembers the last score from the last judge (makes sense since it is being replaced by the score of the new judge). The math required to get the total score only happens based on the last number input by the user (i.e. judge)

Question
How to I keep all the scores from all the judges until the end of the loop so I can perform the correct calculations on it. Does each judges score need to be kept in a separate variable? Then add all the variables together to be placed into separate variable (ex. totalScore), then perform the calculations on that variable? Not sure how to get the desired result.

In addition, any idea why the input from the user is place on a separate line instead of next to the question? Example how it should look -  Divers name: Joe (see output image below)

Lastly, any idea how to start from Judge 1 instead of the program starting with Judge 0

Thank you very much for any help! Really appreciate it.

Output
Currently the total score variable outputs an incorrect number because it performs the calculations on the last known input.
output
using System;


namespace diver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string Name, city, processAnotherOneYoN;
            double Score, highestScore, lowestScore, degreeDiff, totalScore;
            int numberOfNames = 0;


            #region Outer do while loop
            do
            {
                Console.WriteLine("Enter a divers name: ");
                Name = Console.ReadLine();

                Console.WriteLine("Enter a city: ");
                city = Console.ReadLine();

                Console.WriteLine("Enter a degree of diffculty: ");
                degreeDiff = Convert.ToDouble(Console.ReadLine());

                while (degreeDiff < 1 || degreeDiff > 1.67)
                {
                    Console.Write("Invalid degree of difficulty, please reenter (Valid Range: 1 – 1.67)\n");
                    Console.Write("Enter dive degree of difficulty: ");
                    degreeDiff = Double.Parse(Console.ReadLine());
                }

                highestScore = -1;
                lowestScore = 11;
                totalScore = 0;

                #region for loop
                for (int i = 0; i < 5; i++)
                {
                    Console.WriteLine("Enter the score given by judge {0}: ", i);
                    Score = Double.Parse(Console.ReadLine());

                    while (Score < 0 || Score > 10)
                    {
                        Console.WriteLine("Invalid score - Please reenter (Valid Range: 0 - 10)\n");
                        Console.WriteLine("Enter the score given by judge #{0}: ", i);
                        Score = Double.Parse(Console.ReadLine());
                    }
                    if (Score > highestScore)
                        highestScore = Score;
                    if (Score < lowestScore)
                        lowestScore = Score;

//Calculate Total Score
                    Score = Score - lowestScore;
                    Score = Score - highestScore;
                    Score = Score/3;
                    totalScore = Score*degreeDiff;
                }

                #endregion

                Console.WriteLine();
                Console.WriteLine("Name = {0}, Lowest Score  = {1:F}, Highest Score = {2:F}, Final Score = {3:F}", Name, lowestScore, highestScore, totalScore);

                numberOfNames = numberOfNames + 1;

                Console.WriteLine();
                Console.Write("Do you want to process another diver? (Y/N)? ");
                processAnotherOneYoN = Console.ReadLine().ToUpper();
                Console.WriteLine();
                Console.WriteLine();
            } while (processAnotherOneYoN == "Y");

            #endregion

            Console.WriteLine();
            Console.WriteLine("Summary - Number of divers entered {0}, ", numberOfNames);
            Console.ReadLine();
        }
    }
}

Open in new window

0
Comment
Question by:Michael Reeve
  • 8
  • 7
  • 4
  • +1
20 Comments
 
LVL 33

Expert Comment

by:Norie
ID: 36554681
Use an array to store all the marks.

You can declare an array like this:
double[] scores = new double[5];

Open in new window

Within the first loop you can use it like this to store the scores:
scores[i] = score;

Open in new window

Which would go after the loop that checks a valid score has been entered.

To start at 0 either change the loop to this:
for (int i = 1; i < 6; i++)

Open in new window

or change i to i+1 here,
Console.WriteLine("Enter the score given by judge #{0}: ", i+1);

Open in new window

I don't quite follow how you get the final result I'm afraid.

If you just want to sum all the scores you could do that in the loop.

totalScore = totalScore+score*degreeDiff
0
 

Author Comment

by:Michael Reeve
ID: 36554761
Thank you for your reply imnorie, unfortunately I need to only use loops (not arrays - although I would agree that is a better route to go).  Here is the sample output I am trying to achieve:

Diver's name: Sue Jones
Diver's city: Dallas
Dive degree of difficulty: 1.9
Invalid degree of difficulty - Please reenter (Valid Range: 1 - 1.67)
Dive degree of difficulty: 2
Invalid degree of difficulty - Please reenter (Valid Range: 1 - 1.67)
Dive degree of difficulty: 1.2

Judge #1 score: 45
Invalid score - Please reenter (Valid Range: 0 - 10)
Judge #1 score: 3
Judge #2 score: 4.5
Judge #3 score 6.7
Judge #4 score 89
Invalid score - Please reenter (Valid Range: 0 - 10)
Judge #4 score 8
Judge #5 score: 9.2

Diver: Sue Jones
City: Dallas
Dive score: 7.68   <----this score needs to be the accumulation of all 5 judges scores minus the highest and lowest scores which are thrown out. I just can't continue to put the result of each judges score into a variable called score otherwise each time it will be erased when a new judges (the user) puts a records a new score. Could I use a counter to keep track? Not sure how that might work?
0
 
LVL 33

Expert Comment

by:Norie
ID: 36554788
I don't see how you can do this without an array unless you use multiple variables

I'm not even 100% sure how you would do it with multiple variables.

One thing I can't see you getting round is having to store all 5 scores until there in.

Then at the end calculate total score.

Maybe I'm missing something really obvious.

Why can't you use arrays anyway?
0
 

Author Comment

by:Michael Reeve
ID: 36554826
That is what I was thinking too, didn't know how to get around the issue without using multiple variables. I am new to C# and not familiar enough to use arrays and still get the outcome I am looking for. Not sure how to set it up in my current code so that it will store the values I need to output.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36554917
Use Write() instead of WriteLine() to keep the cursor on the same line.

*Also, you may want to switch from Parse() to TryParse() so your app doesn't crash if bad input is typed in!

Refactor the loop like this to get your desired result:
for (int i = 1; i <= 5; i++)
                {
                    Console.Write("Enter the score given by judge {0}: ", i);
                    Score = Double.Parse(Console.ReadLine());

                    while (Score < 0 || Score > 10)
                    {
                        Console.WriteLine("Invalid score - Please reenter (Valid Range: 0 - 10)\n");
                        Console.Write("Enter the score given by judge #{0}: ", i);
                        Score = Double.Parse(Console.ReadLine());
                    }
                    if (i == 1 || Score > highestScore)
                        highestScore = Score;
                    if (i == 1 || Score < lowestScore)
                        lowestScore = Score;
                    totalScore = totalScore + Score; // Just keep a running tally in the loop...
                }
                // Now subtract the low/high and do the calculation!
                totalScore = totalScore - lowestScore;
                totalScore = totalScore - highestScore;
                totalScore = totalScore / (double)3;
                totalScore = totalScore * degreeDiff;

Open in new window

0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 36554932
totalscore: sum up on each "loop"
highest score: keep that value in 1 variable, and change to the score in the loop only if that one is higher than the current highest score
lowest score: same as above, just changing to lower value ...

that's it.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36554933
Couldn't agree more...
0
 
LVL 33

Expert Comment

by:Norie
ID: 36554941
Knew I was missing something.
0
 

Author Comment

by:Michael Reeve
ID: 36555099
Thank you everyone! I still seem to be getting a negative number. If I am doing my math correctly it should (in this example - see attached file) be 6.5 as the answer. The totalScore variable is a negative number. Any ideas why it is giving me this answer?

 output results
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36555106
Show us your code...

Also, why does your highest score say 6 when the highest entered was 10?
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:Michael Reeve
ID: 36555129
Good point. I think I am over working the code because is was working.
using System;


namespace diver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string Name, city, processAnotherOneYoN;
            double Score, highestScore, lowestScore, degreeDiff, totalScore;
            int numberOfNames = 0;


            #region Outer do while loop
            do
            {
                Console.Write("Enter a divers name: ");
                Name = Console.ReadLine();

                Console.Write("Enter a city: ");
                city = Console.ReadLine();

                Console.Write("Enter a degree of diffculty: ");
                degreeDiff = Convert.ToDouble(Console.ReadLine());

                while (degreeDiff < 1 || degreeDiff > 1.67)
                {
                    Console.Write("Invalid degree of difficulty, please reenter (Valid Range: 1 – 1.67)\n");
                    Console.Write("Enter dive degree of difficulty: ");
                    degreeDiff = Double.Parse(Console.ReadLine());
                }

                highestScore = -1;
                lowestScore = 11;
                totalScore = 0;

                #region for loop
                for (int i = 0; i < 5; i++)
                {
                    Console.Write("Enter the score given by judge {0}: ", i+1);
                    Score = Double.Parse(Console.ReadLine());

                    while (Score < 0 || Score > 10)
                    {
                        Console.WriteLine("Invalid score - Please reenter (Valid Range: 0 - 10)\n");
                        Console.Write("Enter the score given by judge #{0}: ", i);
                        Score = Double.Parse(Console.ReadLine());
                    }
                    if (i == 1 || Score > highestScore)
                        highestScore = Score;
                    if (i == 1 || Score < lowestScore)
                        lowestScore = Score;
                    totalScore = totalScore + Score;

                    // Now subtract the low/high and do the calculation!
                    totalScore = totalScore - lowestScore;
                    totalScore = totalScore - highestScore;
                    totalScore = totalScore / (double)3;
                    totalScore = totalScore * degreeDiff;
                }

                #endregion

                Console.WriteLine();
                Console.WriteLine("Name = {0}, Lowest Score  = {1:F}, Highest Score = {2:F}, Total Score = {3:F}", Name, lowestScore, highestScore, totalScore);

                numberOfNames = numberOfNames + 1;

                Console.WriteLine();
                Console.Write("Do you want to process another diver? (Y/N)? ");
                processAnotherOneYoN = Console.ReadLine().ToUpper();
                Console.WriteLine();
                Console.WriteLine();

            } while (processAnotherOneYoN == "Y");

            #endregion

            Console.WriteLine();
            Console.WriteLine("Summary - Number of divers entered {0}, ", numberOfNames);
            Console.ReadLine();
        }
    }
}

Open in new window

0
 

Author Comment

by:Michael Reeve
ID: 36555151
The highest and lowest numbers work if I put this code back into it:

                    if (Score > highestScore)
                        highestScore = Score;
                    if (Score < lowestScore)
                        lowestScore = Score;

However, it is still coming back with a negative number as the total  score. Not sure why it would return a negative number?
0
 
LVL 33

Accepted Solution

by:
Norie earned 500 total points
ID: 36555156
You don't put the code to subtract the lowest and highest scores in the loop.

If you do then they will get subtract more than once and that could be why you get the negative nos.
                #region for loop
                for (int i = 0; i < 5; i++)
                {
                    Console.Write("Enter the score given by judge {0}: ", i+1);
                    Score = Double.Parse(Console.ReadLine());

                    while (Score < 0 || Score > 10)
                    {
                        Console.WriteLine("Invalid score - Please reenter (Valid Range: 0 - 10)\n");
                        Console.Write("Enter the score given by judge #{0}: ", i);
                        Score = Double.Parse(Console.ReadLine());
                    }
                    if (i == 1 || Score > highestScore)
                        highestScore = Score;
                    if (i == 1 || Score < lowestScore)
                        lowestScore = Score;
                    totalScore = totalScore + Score;
             
                }

                // loop finished 

       	// Now subtract the low/high and do the calculation!
                    totalScore = totalScore - lowestScore;
                    totalScore = totalScore - highestScore;
                    totalScore = totalScore / (double)3;
                    totalScore = totalScore * degreeDiff;


                #endregion

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36555161
0
 

Author Comment

by:Michael Reeve
ID: 36555184
Idle Mind,
I appreciate you working on this with me, I had changed the if statement earlier per your post but the results were the same for the totalScore variable, still negative. Could it be that I had initialized the totalScore variable to zero instead of just declaring it as a double?


using System;


namespace diver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string Name, city, processAnotherOneYoN;
            double Score, highestScore, lowestScore, degreeDiff, totalScore;
            int numberOfNames = 0;


            #region Outer do while loop
            do
            {
                //Get input from the user
                Console.Write("Enter a divers name: ");
                Name = Console.ReadLine();

                Console.Write("Enter a city: ");
                city = Console.ReadLine();

                Console.Write("Enter a degree of diffculty: ");
                degreeDiff = Convert.ToDouble(Console.ReadLine());

                //Check the degree of difficulty is within the set range
                while (degreeDiff < 1 || degreeDiff > 1.67)
                {
                    Console.Write("Invalid degree of difficulty, please reenter (Valid Range: 1 – 1.67)\n");
                    Console.Write("Enter dive degree of difficulty: ");
                    degreeDiff = Double.Parse(Console.ReadLine());
                }

                highestScore = -1;
                lowestScore = 11;
                totalScore = 0;

                #region for loop
                for (int i = 0; i < 5; i++)
                {
                    Console.Write("Enter the score given by judge {0}: ", i+1);
                    Score = Double.Parse(Console.ReadLine());

                    while (Score < 0 || Score > 10)
                    {
                        Console.WriteLine("Invalid score - Please reenter (Valid Range: 0 - 10)\n");
                        Console.Write("Enter the score given by judge #{0}: ", i);
                        Score = Double.Parse(Console.ReadLine());
                    }
                    if (i == 1 || Score > highestScore)
                        highestScore = Score;
                    if (i == 1 || Score < lowestScore)
                        lowestScore = Score;
                    totalScore = totalScore + Score;

                    /*
                    if (Score > highestScore)
                        highestScore = Score;
                    if (Score < lowestScore)
                        lowestScore = Score;
                    */

                    // subtract the low/high and do the calculation
                    totalScore = totalScore - lowestScore;
                    totalScore = totalScore - highestScore;
                    totalScore = totalScore / (double)3;
                    totalScore = totalScore * degreeDiff;
                }

                #endregion
                //print the results to the screen
                Console.WriteLine();
                Console.WriteLine("Name = {0}, Lowest Score  = {1:F}, Highest Score = {2:F}, Final Score = {3:F}", Name, lowestScore, highestScore, totalScore);

                numberOfNames = numberOfNames + 1;
                //Get feedback from user to continue
                Console.WriteLine();
                Console.Write("Do you want to process another diver? (Y/N)? ");
                processAnotherOneYoN = Console.ReadLine().ToUpper();
                Console.WriteLine();
                Console.WriteLine();

            } while (processAnotherOneYoN == "Y");

            #endregion

            Console.WriteLine();
            Console.WriteLine("Summary - Number of divers entered {0}, ", numberOfNames);
            Console.ReadLine();
        }
    }
}

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36555197
As noted before, and just as it is in the examples, you need to move lines #65 thru #9 to OUTSIDE the loop at line #71.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36555199
#9 should be #69.
0
 

Author Comment

by:Michael Reeve
ID: 36555244
Got it!! You were right, should have seen my mistake immediately as you noted earlier. Thanks for the patience.
0
 

Author Closing Comment

by:Michael Reeve
ID: 36555252
imnorie was extremely helpful and patient. He worked the solution with me until I understood my mistake. His knowledge and experience in this field was representative of an expert. Experts like this is what makes Experts Exchange so successful. Thank you!
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36555267
*sigh* Lol....
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now