Minimum value returning zero [duplicate] - c#

This question already has answers here:
max and min of array c#
(3 answers)
Closed 1 year ago.
I have a program to find the minimum and maximum grade. I The maximum function works but the minimum function returns 0. I'm not sure what I did wrong, there is no errors in my code. Thanks!
using System;
using System.Collections.Generic;
namespace GradeConverter
{
class Program
{
static void Main(string[] args)
{
bool doAgain = true;
//float totalScore = 0 , averageScore;
string moreConversions;
int numberOfGrades;
//Ask the user to enter their first and last name
string userName = getName();
//Print a welcome message: "Hello [first name] [last name] Welcome to the Grade Converter!"
Console.WriteLine($"\nHello {userName}! Welcome to the Grade Converter!");
while(doAgain){
List<float> scores = new List<float>();
//Prompt the user to enter the number of grades they need to convert "Enter the number of grades you need to convert: "
numberOfGrades = getNumberOfGrades();
//Prompt the user to enter the grades. The grades should be stored in a list and you should use the appropriate data type for the grades.
scores = populateGradesList(scores, numberOfGrades);
//Print Grade Report
printGradeReport(scores);
printGradeStatistics(scores, numberOfGrades);
float aveScore = getAverageGrade(scores);
float maximumGrade = getMaximumGrade(scores);
float minimumGrade = getMinimumGrade(scores);
//averageScore = totalScore / numberOfGrades;
Console.WriteLine("Would you like to convert more grades (y/n)?");
moreConversions = Console.ReadLine();
//reset total score
//totalScore = 0;
if (moreConversions != "y" && moreConversions != "Y"){
doAgain = false;
}
}
}
static float getMinimumGrade(List<float> listOfNumberGrades){
float min = 0;;
foreach(float grade in listOfNumberGrades){
if( grade < min){
min = grade;
}
}
return min;
}
static float getMaximumGrade(List<float> listOfNumGrades){
float max = 0;
foreach(float grade in listOfNumGrades){
if( grade > max){
max = grade;
}
}
return max;
}
static float getAverageGrade(List<float> listOfGrades){
float total = 0;
float average = 0;
foreach(float grade in listOfGrades){
total += grade;
}
average = total / listOfGrades.Count;
return average;
}
static void printGradeStatistics(List<float> listOfGrades, int numberOfGrades){
float averageScore = getAverageGrade(listOfGrades);
float maximumGrade = getMaximumGrade(listOfGrades);
float minimumGrade = getMinimumGrade(listOfGrades);
Console.WriteLine("\nGrade Statistics\n-------------------------\n");
Console.WriteLine($"Number of grades: {numberOfGrades}");
Console.WriteLine($"Average Grade: {averageScore} which is a {getLetterGrade(averageScore)}");
Console.WriteLine($"Maximum Grade: {maximumGrade}");
Console.WriteLine($"Minimum Grade: {minimumGrade}");
}
static void printGradeReport(List<float> scoresList){
string letterGrade;
Console.WriteLine();
foreach(float testScore in scoresList){
//Convert the number grades to letter grades (A = 90-100, B = 80-89, C = 70-79, D = 60 - 69, F lower than 60)
letterGrade = getLetterGrade(testScore);
//Print all the numerical grades and their corresponding letter grades to the console
Console.WriteLine($"A score of {testScore} is a {letterGrade} grade");
}
return;
}
static List<float> populateGradesList(List<float> listOfScores, int numGrades){
float score;
for(int counter = 0; counter < numGrades; counter ++){
score = getScores();
listOfScores.Add(score);
}
return listOfScores;
}
static int getNumberOfGrades(){
Console.WriteLine("\nEnter the number of grades you need to convert:");
int numberOfGrades = int.Parse(Console.ReadLine());
return numberOfGrades;
}
static string getName(){
Console.WriteLine("Please enter your first name and last name");
string userName = Console.ReadLine();
return userName;
}
static float getScores(){
float grade;
while(true){
Console.WriteLine("\nEnter the score to be converted: ");
try{
grade = float.Parse(Console.ReadLine());
break;
}catch(FormatException){
Console.WriteLine("Error: Only numbers allowed");
}
}
return grade;
}
static string getLetterGrade(float score){
//(A = 90-100, B = 80-89, C = 70-79, D = 60 - 69, F lower than 60).
if (score >= 90){
return "A";
}else if(score >= 80){
return "B";
}else if (score >= 70){
return "C";
}else if(score >= 60){
return "D";
}else{
return "F";
}
}
}
}

You could set the starting value as the first one in the list. Something like this:
static float getMinimumGrade(List<float> listOfNumberGrades){
float min = listOfNumberGrades.First();
foreach(float grade in listOfNumberGrades){
if( grade < min){
min = grade;
}
}
return min;
}
Note though, that this doesn't work if there are 0 items in the list, also, it accesses the first item in the list first.
An even easier way, is to use IEnumerable.Min:
static float getMinimumGrade(List<float> listOfNumberGrades){
return listOfNumberGrades.Min();
}

Related

How to put a variable from one function to another

I couldn't think of a good title name, so feel free to change it.
I am making a C# maths console project where the user answers addition, subtraction, multiplication, division, power and square root questions based on the difficulty they choose!
Here is my code:
using System;
using System.Collections.Generic;
namespace mathstester
{
class Program
{
public enum UserDifficulty
{
Easy,
Normal,
Hard
}
public enum MathOperation
{
Addition = 1,
Subtraction = 2,
Multiplication = 3,
Division = 4,
Power = 5,
SquareRoot = 6
}
public static (int operationMin, int operationMax) GetPossibleOperationsByDifficulty(UserDifficulty userDifficulty)
{
switch (userDifficulty)
{
case UserDifficulty.Easy:
return (1, 4);
case UserDifficulty.Normal:
return (1, 5);
case UserDifficulty.Hard:
return (3, 7);
default:
throw new Exception();
}
}
public static (string message, double correctAnswer) GetMathsEquation(MathOperation mathOperation, UserDifficulty userDifficulty)
{
int number1;
int number2;
Random randomNumber = new Random();
switch (mathOperation)
{
case MathOperation.Addition:
number1 = randomNumber.Next(1000);
number2 = randomNumber.Next(1000);
return ($"{number1} + {number2}", number1 + number2);
case MathOperation.Subtraction:
number1 = randomNumber.Next(1000);
number2 = randomNumber.Next(1000);
return ($"{number1} - {number2}", number1 - number2);
case MathOperation.Multiplication:
number1 = userDifficulty == UserDifficulty.Easy ? randomNumber.Next(13) : randomNumber.Next(1000);
number2 = userDifficulty == UserDifficulty.Easy ? randomNumber.Next(13) : randomNumber.Next(1000);
return ($"{number1} * {number2}", number1 * number2);
case MathOperation.Division:
number1 = randomNumber.Next(10000);
number2 = randomNumber.Next(1000);
return ($"{number1} / {number2}", number1 / (double)number2);
case MathOperation.Power:
number1 = randomNumber.Next(13);
number2 = randomNumber.Next(5);
return ($"{number1} ^ {number2}", Math.Pow(number1, number2));
case MathOperation.SquareRoot:
number1 = randomNumber.Next(1000);
return ($"√{number1}", Math.Sqrt(number1));
default:
throw new Exception();
}
}
public static (int operationQuestion, int operationScore) Score(MathOperation mathOperation)
{
int additionQuestion = 0;
int additionScore = 0;
int subtractionQuestion = 0;
int subtractionScore = 0;
int multiplicationQuestion = 0;
int multiplicationScore = 0;
int divisionQuestion = 0;
int divisionScore = 0;
int powerQuestion = 0;
int powerScore = 0;
int squareRootQuestion = 0;
int squareRootScore = 0;
switch (mathOperation)
{
case MathOperation.Addition:
return (additionQuestion, additionScore);
case MathOperation.Subtraction:
return (subtractionQuestion, subtractionScore);
case MathOperation.Multiplication:
return (multiplicationQuestion, multiplicationScore);
case MathOperation.Division:
return (divisionQuestion, divisionScore);
case MathOperation.Power:
return (powerQuestion, powerScore);
case MathOperation.SquareRoot:
return (squareRootQuestion, squareRootScore);
default:
throw new Exception();
}
}
public static (int, int, int) RunTest(int numberOfQuestionsLeft, UserDifficulty userDifficulty)
{
int totalScore = 0;
Random random = new Random();
var (operationMin, operationMax) = GetPossibleOperationsByDifficulty(userDifficulty);
var (operationQuestion, operationScore) = (0, 0);
while (numberOfQuestionsLeft > 0)
{
int mathRandomOperation = random.Next(operationMin, operationMax);
MathOperation mathOperation = (MathOperation)mathRandomOperation;
(operationQuestion, operationScore) = Score(mathOperation);
var (message, correctAnswer) = GetMathsEquation(mathOperation, userDifficulty);
if (mathRandomOperation == 4 || mathRandomOperation == 6)
{
Console.Write($"To the nearest integer, What is {message} =");
}
else
{
Console.Write($"What is {message} =");
}
double userAnswer = Convert.ToDouble(Console.ReadLine());
if (Math.Round(correctAnswer) == userAnswer)
{
Console.WriteLine("Well Done!");
totalScore++;
operationQuestion++;
operationScore++;
}
else
{
Console.WriteLine("Your answer is incorrect!");
operationQuestion++;
}
numberOfQuestionsLeft--;
}
return (totalScore, operationQuestion, operationScore);
}
public static void Main(string[] args)
{
Dictionary<string, UserDifficulty> dict = new Dictionary<string, UserDifficulty>();
dict.Add("E", UserDifficulty.Easy);
dict.Add("N", UserDifficulty.Normal);
dict.Add("H", UserDifficulty.Hard);
string userInputDifficulty = "";
do
{
Console.WriteLine("What difficulty level would you like to do! Please type E for Easy, N for Normal and H for hard");
userInputDifficulty = Console.ReadLine().ToUpper();
} while (userInputDifficulty != "E" && userInputDifficulty != "N" && userInputDifficulty != "H");
UserDifficulty userDifficulty = dict[userInputDifficulty];
int numberOfQuestions = 0;
do
{
Console.WriteLine("How many questions would you like to answer? Please type a number divisible by 10!");
int.TryParse(Console.ReadLine(), out numberOfQuestions);
} while (numberOfQuestions % 10 != 0);
var (totalScore, operationQuestion, operationScore) = RunTest(numberOfQuestions, userDifficulty);
Console.WriteLine($"You got a score of {totalScore} out of {numberOfQuestions}");
if(userDifficulty == UserDifficulty.Easy)
{
Console.WriteLine($"You got an addittion score of {operationScore} out of {operationQuestion}");
Console.WriteLine($"You got an addition score of {operationScore} out of {operationQuestion}");
Console.WriteLine($"You got a score of {operationScore} out of {operationQuestion}");
}
else if (userDifficulty == UserDifficulty.Normal)
{
Console.WriteLine($"You got a score of {operationScore} out of {operationQuestion}");
Console.WriteLine($"You got a score of {operationScore} out of {operationQuestion}");
Console.WriteLine($"You got a score of {operationScore} out of {operationQuestion}");
}
else if (userDifficulty == UserDifficulty.Hard)
{
Console.WriteLine($"You got a score of {operationScore} out of {operationQuestion}");
Console.WriteLine($"You got a score of {operationScore} out of {operationQuestion}");
Console.WriteLine($"You got a score of {operationScore} out of {operationQuestion}");
}
}
}
}
In my function "Score" I have quite a few variables that I want to use in my function "RunTest".
How do I move the variables without having to write them all again?
Thanks!
As noted by #devNull, Score always returns (0, 0). The function can be re-written as the following:
public static (int operationQuestion, int operationScore) Score(MathOperation mathOperation)
{
switch (mathOperation)
{
case MathOperation.Addition:
case MathOperation.Subtraction:
case MathOperation.Multiplication:
case MathOperation.Division:
case MathOperation.Power:
case MathOperation.SquareRoot:
return (0, 0);
default:
throw new Exception();
}
}
Or if you're sure that you don't need the exception handling for incompatible MathOperator:
// Note: no more parameters as well
public static (int operationQuestion, int operationScore) Score()
{
return (0, 0);
}
This will still have the same functionality in your while loop in RunTest because the variables in Score were locally defined, and are not reference values.
If you're wanting those variables to be returned as well in Score, you can extract them to their own class and return an instance of it.
For example:
public class QuestionScoreModel
{
public int AdditionQuestion {get;set;}
public int AdditionScore {get;set;}
public int SubtractionQuestion {get;set;}
public int SubtractionScore {get;set;}
public int MultiplicationQuestion {get;set;}
public int MultiplicationScore {get;set;}
public int DivisionQuestion {get;set;}
public int DivisionScore {get;set;}
public int PowerQuestion {get;set;}
public int PowerScore {get;set;}
public int SquareRootQuestion {get;set;}
public int SquareRootScore {get;set;}
}
And score can be like so:
public static QuestionScoreModel Score()
{
// Initialize it with any values required
return new QuestionScoreModel();
}
Which can be used like:
var scores = Score();
scores.AdditionQuestion++;
Which would help track what type of questions the user got right.

C# Program to store multiple student record with name, grade1 - grade5, and average

I am trying to create a program that takes user input for the amount of students and then with that in mind prompt for 5 grades and an average per student.
An example of a student record would be as follows:
Student #...... Grade1..... Grade2..... Grade3..... Grade4..... Grade5..... Average
Code so far (Probably not correct in anyway):
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Question_Two
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input the number of students: ");
int n = int.Parse(Console.ReadLine());
Student[] students = new Student[6];
string studentId = "Student 1"; //error here
students[0].addGrade(double.Parse(studentId)); // or error here
double value;
value = double.Parse(Console.ReadLine());
students[1].addGrade(value);
value = double.Parse(Console.ReadLine());
students[2].addGrade(value);
value = double.Parse(Console.ReadLine());
students[3].addGrade(value);
value = double.Parse(Console.ReadLine());
students[4].addGrade(value);
value = double.Parse(Console.ReadLine());
students[5].addGrade(value);
students[6].getAverage();
}
public class Student
{
private ArrayList grades;
public Student()
{
grades = new ArrayList();
}
public void addGrade(double val)
{
grades.Add(val);
}
public double getAverage()
{
double avg = 0;
for (int i = 0; i < grades.Count; i++)
{
avg += (double)grades[i];
}
avg /= grades.Count;
return avg;
}
}
}
}
I am not sure where to go from here as I have an error when storing the name into the array.
Creating an array with new does not create each individual element (except primitives like int). You need to call new for every item in the array:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Input the number of students: ");
int n = int.Parse(Console.ReadLine());
// Create array of size n (instead of 6)
// Array is created but individual Students are not created yet!
Student[] students = new Student[n];
// Use a loop to get all student info
for (int s = 0; s < n; s++) {
string studentId = $"Student{s+1}";
// Important! Need to create a student object
students[s] = new Student(studentId);
// Use another loop to get grades
for (int g = 0; g < 5; g++) {
double grade = double.Parse(Console.ReadLine());
students[s].addGrade(grade);
}
// Print average
Console.WriteLine($"{students[s].id} average = {students[s].getAverage()}");
}
}
Also, modify the Student class to have an id
public class Student
{
private ArrayList grades;
public string id;
// Accepts one parameter : an id
public Student(string studentId)
{
id = studentId;
grades = new ArrayList();
}
public void addGrade(double val)
{
grades.Add(val);
}
public double getAverage()
{
double avg = 0;
for (int i = 0; i < grades.Count; i++)
{
avg += (double)grades[i];
}
avg /= grades.Count;
return avg;
}
}
}
You can not parse a string "Student 1" to double like in the following code:
string studentId = "Student 1"; //error here
students[0].addGrade(double.Parse(studentId));
I don't know what you want to the result to be. But make sure that the student id is a numeric value (can be in string form). You can use the following code to get what you want.
Console.WriteLine("Input the number of students: ");
int numberOfStudents = int.Parse(Console.ReadLine());
Student student = new Student();
string studentId = "1";
student.addGrade(double.Parse(studentId));
double value;
value = double.Parse(Console.ReadLine());
student.addGrade(value);
value = double.Parse(Console.ReadLine());
student.addGrade(value);
value = double.Parse(Console.ReadLine());
student.addGrade(value);
value = double.Parse(Console.ReadLine());
student.addGrade(value);
value = double.Parse(Console.ReadLine());
student.addGrade(value);
double avarageNumber = student.getAverage();

how can i number each user input? C#

Just started learning C#, my question is how do i keep record of the user input in order like this: score 1:
score 1: 98
score 2: 76
score 3: 65
score 4: 78
score 5: 56
In my code i can input the number but cant seem to setup the order how can i achieve this goal
my input:
98
76
65
78
56
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyGrade03
{
public class Program
{
private int total; // sum of grades
private int gradeCounter; //number of grades entered
private int aCount; // Count of A grades
private int bCount; // Count of B grades
private int cCount; // Count of C grades
private int dCount; // Count of D grades
private int fCount; // Count of F grades
private string v;
public string CourseName { get; set; }
public Program(string name)
{
CourseName = name;
}
public void DisplayMessage()
{
Console.WriteLine("Welcome to the grade book for \n{0}!\n",
CourseName);
}
public void InputGrade()
{
int grade;
string input;
Console.WriteLine("{0}\n{1}",
"Enter the integer grades in the range 0-100",
"Type <Ctrl> z and press Enter to terminate input:");
input = Console.ReadLine(); //read user input
while (input != null)
{
grade = Convert.ToInt32(input); //read grade off user input
total += grade;// add grade to total
gradeCounter++; // increment number of grades
IncrementLetterGradeCounter(grade);
input = Console.ReadLine();
}
}
private void IncrementLetterGradeCounter(int grade)
{
switch (grade / 10)
{
case 9: //grade was in the 90s
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case7:
++cCount;
case6:
++dCount;
break;
default:
++fCount;
break;
}
}
public void DisplayGradeReport()
{
Console.WriteLine("\nGrade Report");
if (gradeCounter != 0)
{
double average = (double)total / gradeCounter;
Console.WriteLine("Total of the {0} grades entered is {1}",
gradeCounter, total);
Console.WriteLine("class average is {0:F}", average);
Console.WriteLine("{0}A: {1}\nB: {2}\nC: {3}\nD: {4}\nF: {5} ",
"Number of students who received each grade: \n",
aCount,
bCount,
cCount,
dCount,
fCount);
}
else
Console.WriteLine("No grades were entered");
}
static void Main(string[] args)
{
Program mygradebook = new Program(
"CS101 introduction to C3 programming");
mygradebook.DisplayMessage();
mygradebook.InputGrade();
mygradebook.DisplayGradeReport();
}
}
}
There are a lot of data structures that will allow you to store data in order. I'd personally recommend a List<int> for this.
You can add things to it as simply as:
var list = new List<int>();
list.Add(37);
list.Add(95);
And you can either read it with an iterator (foreach(var score in list){...}) or get individual numbers out (var firstScore = list[0]). The documentation will tell you more about what you can do with a List<T>.
declare one variable to count inputs like private static int counter = 0;
in InputGrade method, put like below
Console.WriteLine("{0}\n{1}",
"Enter the integer grades in the range 0-100",
"Type <Ctrl> z and press Enter to terminate input:");
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine(); //read user input
and inside while (input != null) put like below
IncrementLetterGradeCounter(grade);
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine();
so, output will be like
Here is the full code
public class Program
{
private int total; // sum of grades
private int gradeCounter; //number of grades entered
private int aCount; // Count of A grades
private int bCount; // Count of B grades
private int cCount; // Count of C grades
private int dCount; // Count of D grades
private int fCount; // Count of F grades
private string v;
private static int counter = 0;
public string CourseName { get; set; }
public Program(string name)
{
CourseName = name;
}
public void DisplayMessage()
{
Console.WriteLine("Welcome to the grade book for \n{0}!\n",
CourseName);
}
public void InputGrade()
{
int grade;
string input;
Console.WriteLine("{0}\n{1}",
"Enter the integer grades in the range 0-100",
"Type <Ctrl> z and press Enter to terminate input:");
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine(); //read user input
while (input != null)
{
grade = Convert.ToInt32(input); //read grade off user input
total += grade;// add grade to total
gradeCounter++; // increment number of grades
IncrementLetterGradeCounter(grade);
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine();
}
}
private void IncrementLetterGradeCounter(int grade)
{
switch (grade / 10)
{
case 9: //grade was in the 90s
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case7:
++cCount;
case6:
++dCount;
break;
default:
++fCount;
break;
}
}
public void DisplayGradeReport()
{
Console.WriteLine("\nGrade Report");
if (gradeCounter != 0)
{
double average = (double)total / gradeCounter;
Console.WriteLine("Total of the {0} grades entered is {1}",
gradeCounter, total);
Console.WriteLine("class average is {0:F}", average);
Console.WriteLine("{0}A: {1}\nB: {2}\nC: {3}\nD: {4}\nF: {5} ",
"Number of students who received each grade: \n",
aCount,
bCount,
cCount,
dCount,
fCount);
}
else
Console.WriteLine("No grades were entered");
}
static void Main(string[] args)
{
Program mygradebook = new Program(
"CS101 introduction to C3 programming");
mygradebook.DisplayMessage();
mygradebook.InputGrade();
mygradebook.DisplayGradeReport();
Console.ReadKey();
}
}
You can look for Collections available in C# (MSDN Collections).
In your case, you don't really care about order, you can use List<int>. Otherwise if you want to keep an order you can use Stack<int> or Queue<int>. And if you want to keep a collection of Student Name + Score you can use a Dictionary<string,int>

How to display highest and lowest of an array

here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.

C# bowling array program

So I am having problems with programming a bowling application in c# to calculate 5 different scores, storing them in an array and returning the average, highest and lowest scores, I am having problems with the code for storing the array and returning the scores. Here is what i have so far:
static void Main(string[] args)
{
//Declarations
const double MIN_SCORE = 0;
const double MAX_SCORE = 300;
const int SCORE_COUNT = 5;
int[] scores = new int[SCORE_COUNT]; //stores all the scores
int inputScore; //stores one score
double total = 0; //to total the scores for average
double average; //average the grades
double highScore; //highest score of the games
double lowScore; //lowest score of the games
//INPUT
//loop to get scores
for (int bowler = 0; bowler < scores.Length; bowler++)
{
try
{
//prompt for and get the input
Console.Write("Please enter score for game " + (bowler + 1) + ":");
inputScore = Convert.ToInt16(Console.ReadLine());
//valid range?
if (inputScore > MAX_SCORE || inputScore < MIN_SCORE)
{
Console.WriteLine("Scores must be between " + MIN_SCORE +
" and " + MAX_SCORE + ". Please try again. ");
bowler--;
}
else
{
scores[bowler] = inputScore;
}
}
catch (Exception myEx)
{
Console.WriteLine(myEx.Message + " Please try again. ");
bowler--;
}
//PROCESS
Array.Sort(scores);
//OUTPUT
Console.WriteLine("\n\nAverage Score for Bowler:{0}");
}
}
Add this using statement:
using System.Linq;
Then you can use:
scores.Average();
scores.Max();
scores.Min();
Simple enough.

Categories