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.
Related
My program is where someone is inputting temperatures until they enter 999, the temps need to be in between -20 and 130. once 999 is entered, it is supposed to calculate the total amount of temps entered and the average temperature. Im not sure where im going wrong with this code, i do have a little trouble with the loops. any help is appreciated!
static void Main(string[] args)
{
int temp = 0, total = 0, sum = 0;
double avg;
string = tempString;
WriteLine("Enter daily high temperatures, to stop program enter 999.");
tempString = ReadLine();
temp = Convert.ToInt32(tempString);
do
{
if (temp >= 20 && temp <= 130)
{
WriteLine("Enter daily high temperatures, to stop program enter 999");
ReadLine();
total++;
}
else
{
WriteLine("Valid temperatures range from -20 to 130. Please reenter temperature.");
ReadLine();
}
} while (temp != 999);
sum += temp;
avg = sum / total;
WriteLine("The number of temperatures entered: {0} /n The average temperature is: {1}.", total, avg);
}
You want to add temp to sum in your first if statement before you read the next temp. Also set temp to the next ReadLine in each if statement. Also, you had 20 in the first if statement instead of -20. Finally, add a ReadLine to the end so the console doesn't close instantly after entering 999.
static void Main(string[] args)
{
int temp = 0, total = 0, sum = 0;
double avg;
string tempString;
Console.WriteLine("Enter daily high temperatures, to stop program enter 999.");
tempString = Console.ReadLine();
temp = Convert.ToInt32(tempString);
do
{
if (temp >= -20 && temp <= 130)
{
sum += temp;
Console.WriteLine("Enter daily high temperatures, to stop program enter 999");
temp = Convert.ToInt32(Console.ReadLine());
total++;
}
else
{
Console.WriteLine("Valid temperatures range from -20 to 130. Please reenter temperature.");
temp = Convert.ToInt32(Console.ReadLine());
}
} while (temp != 999);
avg = sum / total;
Console.WriteLine("The number of temperatures entered: {0} /n The average temperature is: {1}.", total, avg);
Console.ReadLine();
}
Update your code to following -
static void Main(string[] args)
{
int temp = 0, total = 0, sum = 0;
double avg;
string tempString=string.Empty;
Console.WriteLine("Enter daily high temperatures, to stop program enter 999.");
tempString = Console.ReadLine();
temp = Convert.ToInt32(tempString);
while (temp != 999)
{
if (temp >= 20 && temp <= 130)
{
Console.WriteLine("Enter daily high temperatures, to stop program enter 999");
tempString = Console.ReadLine();
temp = Convert.ToInt32(tempString);
sum += temp;
total++;
}
else
{
Console.WriteLine("Valid temperatures range from -20 to 130. Please reenter temperature.");
Console.ReadLine();
}
}
avg = sum / total;
Console.WriteLine("The number of temperatures entered: {0} {2}The average temperature is: {1}.", total, avg,"\n");
}
Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}
So I have this very simple program that I have created that gets the user input and then pass the values to the method named average. Everything is perfectly fine, however, something crossed my mind like "What if the user only enters two numbers or an array of numbers?". I know that I have to use array as a parameter, but somehow I am not sure how to accomplish what i want to do. Do you guys have any tips on how I can achieve what i am trying to do? My code is here:
using System;
namespace Averages
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
double num1 = Convert.ToInt32(Console.ReadLine());
double num2 = Convert.ToInt32(Console.ReadLine());
double num3 = Convert.ToInt32(Console.ReadLine());
average(num1, num2, num3);
Console.ReadKey();
}
static void average(double num1, double num2, double num3)
{
double avg = (num1 + num2 + num3) / 3;
Console.WriteLine("You have entered: " + num1 + ", " + num2 + ", " + num3);
Console.WriteLine("The average is: " + avg);
}
}
}
I would appreciate any help. Thank you!
you can ask user for input of comma delimited numbers. Or, you can repeat input until user enters something like 0. I that case, you can change your program into this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Averages
{
class Program
{
static void Main(string[] args)
{
//list to hold your numbers, way more flexible than array
List<double> enteredNubers = new List<double>();
//message user
Console.WriteLine("Enter number(s) or 0 to end: ");
//run this block of code indefinitely
while (true)
{
//take user input
string userinput = Console.ReadLine().Trim();
//if user enters 0, exit this loop
if (userinput == "0")
break;
double num;
//try to convert text to number
if (double.TryParse(userinput, out num))
{
//if it is successful, add number to list
enteredNubers.Add(num);
}
else //else message user with error
Console.WriteLine("Wrong input. Please enter number or 0 to end");
}
//when loop is exited (when user entered 0), call method that calculates average
Average(enteredNubers);
Console.ReadKey();
}
static void Average(List<double> numbers)
{
double sum = 0;
//go through list and add each number to sum
foreach (double num in numbers)
{
sum += num;
}
//or, you can sum it using linq like this:
//sum = numbers.Sum();
//or you can even calculate average by calling Average method on list, like numbers. Average();
//show message - all the entered numbers, separated by comma
Console.WriteLine("You have entered: " + string.Join(", ", numbers.ToArray()));
//write average
Console.WriteLine("The average is: " + sum/numbers.Count);
}
}
}
Let's solve the problem step by step. First we want to add a single double:
private static bool ReadDouble(out double value) {
value = 0.0;
while (true) {
Console.WriteLine("Enter number or X to exit:");
string input = Console.ReadLine().Trim();
if (input == "X" || input == "x")
return false;
else if (double.TryParse(input, out value))
return true;
Console.Write("Syntax error, please, try again.");
}
}
Now we are ready to read arbitrary number of values. Since we don't know the number, List<double> is a better choice than double[]
using System.Collections.Generic;
...
private static List<double> ReadDoubles() {
List<double> result = new List<double>();
while (ReadDouble(out var value))
result.Add(value);
return result;
}
Finally, we want to compute average
static void Main(string[] args) {
List<double> list = ReadDoubles();
if (list.Count <= 0)
Console.WriteLine("Empty list: no average");
else {
double sum = 0.0;
foreach (double item in list)
sum += item;
double avg = sum / list.Count;
Console.Write("The average is: " + avg);
}
}
However, you can do it in just few lines via Linq:
using System.Collections.Generic;
using System.Collections.Linq;
...
static void Main(string[] args) {
Console.WriteLine("Enter numbers separated by spaces, e.g. 1 2 3 15");
double avg = Console
.ReadLine()
.Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => double.Parse(item))
.Average();
Console.Write($"The average is: {avg}");
}
Here Update your methods Accordingly
static void Main(string[] args)
{
Console.WriteLine("Type Exit to stop the program... \nEnter number");
List<double> doubleList = new List<double>();
string input = Console.ReadLine();
double d;
while(!input.Equals("Exit"))
{
if(String.IsNullOrEmpty(input) || !Double.TryParse(input,out d))
{
break;
}
doubleList.Add(d);
input = Console.ReadLine();
}
average(doubleList);
Console.ReadKey();
}
static void average(List<double> doubleData)
{
double total = 0;
foreach (double number in doubleData)
{
total += number;
}
Console.WriteLine("Average = " + total/doubleData.Count);
}
Something like the following should meet your needs:
string stopLine = "STOP";
List<double> lines = new List<double>();
string line;
while ((line = Console.ReadLine()) != stopLine) {
lines.Add(Convert.ToDouble(line));
}
Average(lines);
Console.ReadLine();
Now your average method becomes
private static void Average(List<double> lines) {
Console.WriteLine(lines.Average());
}
Note that you should handle the case where the input is not a number.
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
string input = "";
List<double> doubleList = new List<double>();
while (input != "q")
{
input = Console.ReadLine();
if(input != "q")
{
try
{
doubleList.Add(Convert.ToInt32(input));
}
catch
{
Console.WriteLine("Invalid input");
}
}
}
average(doubleList);
Console.ReadKey();
}
static void average(List<double> myList)
{
double sum = 0;
Console.Write("You have entered: ")
foreach (int element in myList)
{
sum += element;
Console.Write(element + ", ");
}
Console.WriteLine("");
double avg = sum / myList.Count;
Console.WriteLine("The average is: " + avg);
}
static void Main(string[] args)
{
var numbers = new List<double>();
Console.WriteLine("Enter the three numbers, one per line");
for (var i = 0; i < 3; ++i)
{
while (true)
{
if (double.TryParse(Console.ReadLine(), out var enteredNumber))
{
//the number is a number, so...
numbers.Add(enteredNumber);
break;
}
//if not a number...
Console.WriteLine("That's not a number, try again");
}
}
Average(numbers);
Console.ReadKey();
}
static void Average(IEnumerable<double> numbers)
{
var average = numbers.Average();
Console.Write("You have entered: ");
foreach (var num in numbers)
{
Console.Write($" {num} ");
}
Console.WriteLine(String.Empty);
Console.WriteLine("The average is: " + average);
}
In general, Lists are better than Arrays for this kind of thing; List's are stretchy, Arrays are not. If you want this to work with 4 (or 200) numbers, all you have to do is change the for loop's bounds.
I'm using double.TryParse, this way I can let the user correct a badly entered number (always assume users will enter bad data). I'm passing the collection of numbers to the average function as an IEnumerable and not a List (the Average function is hardly needed (note that the calculation of the average is just an extension method on collections of numerics) but you had one, so I included it. An IEnumerable cannot be changed by the called function, so it's more appropriate here (and, all lists (and all arrays, for that matter) are enumerable).
Looking at all these fancy answers,i guess people are forgetting the basics of programming.
The OP literally states using arrays and instead of that you all are pushing him into hard to read code. The guy is trying to learn the basics which obviously no one cares to learn about.
Dear Cyrus don't get into generics right away. I would suggest that you stick to arrays for a while.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number(s): ");
double[] values = new double[3]; //initialize double array with its size
for (int i = 0; i < values.Length; i++)
{
//iterate through the array and assign value to each index of it.
values[i]=Convert.ToDouble(Console.ReadLine());
}
average(values);
Console.ReadKey();
}
//set method that accepts double array as parameter
static void average(double[] values)
{
double average =0;// declare var that will hold the sum of numbers
int length = values.Length;//get array length, use it to divide the summation of numbers
Console.WriteLine("You have entered: ");
for (int i = 0; i < values.Length; i++)
{
//also display the numbers if you need to
Console.WriteLine(values[i]);
//iterate through each value in the array and sum it up.
average = values[i] + average;
}
//divide the sum of numbers by the length of array
Console.WriteLine("The average is: " + (average/length));
}
}
You can also dynamically set the length of the array by letting the user input its length, just play with code and let your imagination loose. Happy coding!
You have a couple options. Either ask for the user input to be delimited somehow. For example a comma delimited user input would be"1, 2, 3, 4". You've then got to worry about parsing that and ensuring the user entered valid input.
Another option is to have a while loop that has Console.ReadLine() within, and you only exit the loop when the user enters a pre-determined exit word (such as "stop" or exit")
static void Main(string[] args)
{
var inputValues = new List<double>();
while (true)
{
var input = Console.ReadLine();
if (input.Equals("stop", StringComparison.InvariantCultureIgnoreCase))
break;
if (double.TryParse(input, out double inputValue))
{
inputValues.Add(inputValue);
}
else
{
Console.WriteLine("Invalid input!");
}
}
PrintAverage(inputValues);
Console.ReadKey();
}
static void PrintAverage(IEnumerable<double> values)
{
Console.WriteLine("You have entered: {0}", string.Join(", ", values));
Console.WriteLine("The average is: {0}", values.Average());
}
Here I've opted for the second option. It'll continuously loop until the input is stop. It will also now try parse the value rather than directly convert, and will print a warning message if the parse failed.
If the parse was successful it's added to our inputValues collection. Once out of the while loop, we pass the collection to PrintAverage - a method that takes an IEnumerable<double> (could be one value, 100 values, or no values). Because List implements IEnumerable, we can pass our list to this method. IEnumerable has an Average() method built-in.
I'm new to C#, and i'm writing a do while loop that continues to ask the user to enter "price", until they enter "-1" for price.
Afterwards, I need to add up all the values for price they entered and declare that as the subtotal.
The problem I have is that it only remember the last number entered, which would be -1. What would I have to do to fix this?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
} while (price != -1);
subtotal = Convert.ToInt32(price);
Console.Write("Subtotal: ${0}", subtotal);
}
}
}
Try this variation to Artem's answer. I think this is a little cleaner.
int count = 0;
decimal input = 0;
decimal price = 0;
while (true)
{
Console.Write("Item {0} Enter Price: ", count++);
input = Convert.ToDecimal(Console.ReadLine());
if (input == -1)
{
break;
}
price += input;
}
In each iteration of the loop, you overwrite the value of price. Separate input and storage price.
decimal input = 0;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
input = Convert.ToDecimal(Console.ReadLine());
if (input != -1)
price += input;
} while (input != -1);
Use a list and keep adding the entries to the list.
Or you can keep a running total in another integer.
Something like:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;
Please try to use this
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal = 0m; //subtotal is needed to be initialized from 0
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
if (price != -1) //if the console input -1 then we dont want to make addition
subtotal += price;
} while (price != -1);
//subtotal = Convert.ToInt32(price); this line is needed to be deleted. Sorry I didnt see that.
Console.Write("Subtotal: ${0}", subtotal); //now subtotal will print running total
}
}
}
I'm taking a C# class this semester and it has been quite fun so far. I have an assignment where I need to do several things with an array: add numbers in the array, see the numbers entered in the array, find a number in the array, sort the numbers in the array, create statistics based on the array numbers, and finally exit the application.
So far I have been having a little bit of an issue with adding numbers to the array while making sure that the data entered is only numbers. I think I am about to figure it out, but help is always appreciated. And, does my findData() method look ok?
Thank you again for your time in reading this question!
class Program
{
static char myChoice = Console.ReadKey().KeyChar;
static double[] myArray = new double[100];
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Welcome to Lab 2");
Console.WriteLine();
Console.WriteLine("Main Menu");
Console.WriteLine("1- Add new data");
Console.WriteLine("2- See all data");
Console.WriteLine("3- Find a number");
Console.WriteLine("4- Sort the data");
Console.WriteLine("5- Create statistics");
Console.WriteLine("6- Exit Program");
switch (myChoice)
{
case '1':
Console.WriteLine("1- Add new data");
addData();
break;
case '2':
Console.WriteLine("2- See all data");
seeData();
break;
case '3':
Console.WriteLine("3- Find a number");
findData();
break;
case '4':
Console.WriteLine("4- Sort the data");
sortData();
break;
case '5':
Console.WriteLine("5- Create statistics");
createData();
break;
case '6':
Console.WriteLine();
exitProgram();
break;
}
}
}
//This method will add numbers to the array
public static void addData()
{
bool isNumber = false;
double number;
double temp;
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("Enter a number you would like to add");
myArray[i] = Convert.ToDouble(Console.ReadLine());
temp = myArray[i];
if (!Double.TryParse(temp, out number))
{
Console.WriteLine("Invalid input. Please enter a valid number")
}
else
{
}
}
}
//This method will see the numbers entered in the array
public static void seeData()
{
foreach (var item in myArray)
{
Console.WriteLine(item.ToString());
}
}
//This method will find a specific number within the array and check if it has already been entered
public static void findData()
{
Console.WriteLine("Find a number");
string myChoice = Console.ReadLine();
double number;
bool isNumber = Double.TryParse(myChoice, out number);
{
}
}
//This method will sort the array ascending to descending
public static void sortData()
{
Console.WriteLine("The array has been sorted in ascending order");
Array.Sort(myArray);
Console.WriteLine("The array has been sorted in descending order");
Array.Reverse(myArray);
}
//This method will create statistics based on the numbers in the array
public static void createData()
{
//Sum
double sum = myArray.Sum();
Console.WriteLine("The total sum of the array is: " + sum);
//Average
double average = sum / myArray.Length;
Console.WriteLine("The average number of the array is: " + average);
//Maximum
double maximum = myArray.Max();
Console.WriteLine("The maximum value in the array is: " + maximum);
//Minimum
double minimum = myArray.Min();
Console.WriteLine("The minimum value in the array is: " + minimum);
//Mean
double mean = sum / myArray.Length;
Console.WriteLine("The mean average of the array is: " + mean);
}
//This method will exit the program
public static void exitProgram()
{
Environment.Exit(0);
}
}
}
does my findData() method look ok?
Your findData() method does acutally nothing.
Here is one approach
public static void findData()
{
Console.WriteLine("Find a number");
string myChoice = Console.ReadLine();
double number = -1;
if(!Double.TryParse(myChoice, out number))
{
Console.WriteLine("Invalid number");
}
else if (Array.IndexOf<double>(myArray, number) == -1)
{
Console.WriteLine("Number does not exist");
}
else
{
Console.WriteLine("Number does exist");
}
}
This should solve your add problem
public static void addData()
{
for (int i = 0; i < myArray.Length; i++)
{
bool success = false;
while (!success)
{
Console.WriteLine("Enter a number you would like to add");
string input = Console.ReadLine();
double number;
if (Double.TryParse(input, out number))
{
success = true;
myArray[i] = number;
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number")
}
}
}
}
Your addData method doesn't make much sense: you first insert a double value into array and then you check if that value is a double (and it certainly is, because the array is of type double and can contain values only of that type).
Also, the Convert.ToDouble may throw exception if the user input is not valid. But I see you get the point of using Double.TryParse method, which returns true if the string (first parameter) is a valid number. So your addData method should look something like this:
//This method will add numbers to the array
public static void addData()
{
double number;
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine("Enter a number you would like to add");
// read user input
string input = Console.ReadLine();
// condition is true if user input is a number
if (double.TryParse(input, out number))
myArray[i] = number;
else
Console.WriteLine("Invalid input. Please enter a valid number");
}
}
To find a number in your array you can use LINQ Contains extension method which does exacly that: it returns true if array contains element, otherwise false:
//This method will find a specific number within the array and check if it has already been entered
public static void findData()
{
double number;
Console.WriteLine("Find a number");
string input = Console.ReadLine();
// we use the same logic here as in the addData method to make sure the user input is a number
if (!double.TryParse(input, out number))
{
bool found = myArray.Contains(number);
if (found)
Console.WriteLine("Array has number {0}", number);
else
Console.WriteLine("Array doesn't have number {0}", number);
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number");
}
}