I am trying to output the overall class average on a test using a program which makes use of arrays. The program is meant to be for a class of 12 students. When I try to input all data I need, I don't get the average for the class as a whole. The problem obviously lies in the average calculator itself but seeing as I am a beginner I have little clue how to fix it. Any help would be appreciated. Just to reiterate, I am looking for a solution on how to fix my average calculator to give the class average as an overall. I have entered my code below. I hope I have been specific.
string[] studentnames = new string[12];
int[] testscore = new int[12];
int i;
int index;
double average;
int total = 0;
//title
Console.Write("\n\nStudent lists:\n");
Console.Write("******************\n");
//asks user to input names
Console.Write("Enter student names:\n");
for (i = 1; i < 12; i++)
{
Console.Write("Student name {0} : ", i);
studentnames[i] = (Console.ReadLine());
//asks user to enter student's test score
Console.Write("Please enter their test score: ");
testscore[i] = Convert.ToInt32(Console.ReadLine());
}
//outputs all values user has entered
Console.WriteLine("\nStudent marks: ");
for (i = 1; i < 12; i++)
{
Console.WriteLine("Name: ");
Console.WriteLine("{0} ", studentnames[i]);
Console.WriteLine("Test score: ");
Console.WriteLine("{0} ", testscore[i]);
}
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
Console.ReadKey();
The division by the total needs to be after the for loop.
This:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
Needs to become:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
}
average = ((double)total) / 12;
Console.WriteLine("The class average was: " + average);
Another problem: your for loops start at index 1. C# uses 0 based indexing. I assume you are trying to calculate the average for 12 students, not 11.
Also, for the love of god please stop writing the number 12. If you absolutely must hard-code it, use a constant.
Edit: I've updated my answer to account for flydog's comment
Related
I have been trying to make a program that you input a number and i keeps asking for numbers untill their sum has reached the number and displays how many numbers it took. the problem i'm facing is that if the last number makes it over the input number it still counts it while it should stop.
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;`
while (sum < sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
sum += number;
count++;
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
}
Here's one option to fix it, depending on your expected result you can let the count start at -1 or 0:
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = -1;
int number = 0;
while (sum + number < sumLimit)
{
sum += number;
count++;
number = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
Struggling with understanding the while loop. I'm just starting to learn programming. While testing the code, it appears as if only the second number entered gets processed into the final answer.
static void Main(string[] args)
{
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = Double.Parse(input);
double sum = 0.0;
int counter = 1;
int total = 3;
while (counter < total)
{
sum = sum + value;
counter = counter + 1;
Console.WriteLine("Enter another test score");
input = Console.ReadLine();
value = Double.Parse(input);
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
}
You need your while loop to run three times so start the counter from 0 instead of 1.
Within the loop you can ask for the test scores and add them to the sum and then increment the counter.
double sum = 0.0;
int counter = 0;
int total = 3;
while (counter < total)
{
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);
sum += value;
counter++;
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
Or like this if you need the question to be different, you can ask the question outside of the loop and save the result to the sum variable. Since we have already asked the question once we can make the counter start at 1 instead of 0.
double sum = 0.0;
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);
sum = sum + value;
int counter = 1;
int total = 3;
while (counter < total)
{
Console.WriteLine("Enter another test score");
input = Console.ReadLine();
value = double.Parse(input);
sum += value;
counter++;
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
You use Wrong number
total is 3, but you need repeat 3 times calculate
counter 1 calculate clear
counter 2 calculate clear
but counter 3 is while false.
you need to fix counter <=total or counter started 0
A few weeks ago I began studying a c# beginners course, I got stuck on Arrays.
I do not want the complete answer for my problem, I want the tools or links to figure it out of myself
I´am trying to make a console Application that acts like a "Weather Station".
The program should take user input as an array on how many measurements have been made (Done). After that the user will enter the degrees in an loop (Done)
The program should write out all the measurements and the average measurement.
I can calculate the average but don't know how to print the results
I've come this far...
Console.WriteLine("How many measurements have you done");
string str = Console.ReadLine();
int size = Convert.ToInt32(str);
int[] temperatur = new int[size];
for (int i = 0; i < temperatur.Length; i++)
{
Console.WriteLine("Enter temperature " + i + ": ");
str = Console.ReadLine();
int element = Convert.ToInt32(str);
temperatur[i] = element;
}
Console.WriteLine("");
int sum = 0;
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " +
sum / temperatur.Length);
Seeing as you state that the only problem you are having is 'print out all the measurements', all you have to do is add an additional Console.WriteLine() to the existing for loop you already have. You will also to have to add braces. As such:
int sum = 0;
for (int i = 0; i < temperatur.Length; i++){
sum = sum + temperatur[i];
Console.WriteLine("Measurement {0} is {1}", i+1, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
You might not recognise that Console.WriteLine(), but it's basically a neat way of formatting your output using placeholders. The {0} will be replaced with the first value provided, the {1} with the second.
EDIT: MSDN documentation on Console.WriteLine() and also String.Format
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Change this to :
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0} is {1}", i, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
If you want to do it in the same for:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0}", temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
In another statement:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
}
temperatur.ForEach(x => Console.WriteLine("Temperature {0}", x));
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
...
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Console.ReadLine();
In the end type Console.ReadLine();
This Console Application is Supposed to Display Prices and then set it in a average format and in a Less than NUM and Higher then NUM which I am entirely confused. The total and the Average come Out to the right amount just not the lessthanfive and the higherthanaverage.
CODE:
double[] prices = new double[5];
int count = 0;
double TotalValues = 0;
double Average = 0;
string inputString;
double lessthanfive = 0;
double higherthanaverage = 0;
int x;
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
Average = TotalValues / prices.Length;
if (prices[x] < 5)
lessthanfive++;
if (prices[x] > Average)
higherthanaverage++;
}
Console.WriteLine();
Console.WriteLine("The Sum of The Values Are: {0}", TotalValues.ToString("C2"));
Console.WriteLine("Numbers Less Than $5.00 Are: {0}", lessthanfive.ToString("C2"));
Console.WriteLine("The Average of The 20 Prices Are: {0}", Average.ToString("C2"));
Console.WriteLine("Numbers Higher then Average Are: {0}", higherthanaverage.ToString("C2"));
Console.ReadLine();
You can't know the average until after the last value has been entered, so you need another loop to count the number of items above the average:
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
if (prices[x] < 5) {
lessthanfive++;
}
}
Average = TotalValues / prices.Length;
for (x = 0; x < prices.Length; x++)
{
if (prices[x] > Average) {
higherthanaverage++;
}
}
Your average is going to be wrong, and your counts are going to be off because of it. Calculating everything outside of that loop will keep things easy to debug, as well. Now, this isn't the most elegant solution out there, but it uses a List to leverage the built-in Sum and Average functions, as well as allowing your list to be re-sizable, in case you don't want to add 20 numbers each time.
List<decimal> prices = new List<decimal>();
int numPrices;
decimal totalPrice;
decimal averagePrice;
string inputString;
int lessThanFive = 0;
int higherThanAverage = 0;
Console.Write("Enter the number of prices that you will be entering: ");
numPrices = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < numPrices; i++)
{
Console.Write("Enter the price for item #{0}: $", i+1);
inputString = Console.ReadLine();
prices.Add(Convert.ToDecimal(inputString));
}
totalPrice = prices.Sum();
averagePrice = prices.Average();
foreach (decimal item in prices)
{
if (5 > item)
{
lessThanFive++;
}
if (averagePrice > item)
{
higherThanAverage++;
}
}
Console.WriteLine();
Console.WriteLine("The sum of the values are: {0:C}", totalPrice);
Console.WriteLine("The number of prices less than $5.00 are: {0}", lessThanFive);
Console.WriteLine("The average of the prices entered is: {0:C}", averagePrice);
Console.WriteLine("The number of prices that are higher than average are: {0}", higherThanAverage);
Console.ReadLine();
Now, I used decimal instead of double for these because, well, in this example it certainly wouldn't need a double for anything, but it could be converted back without any problems. Also added some minor string formatting, etc. The main thing is, I checked the math and it works.
The average is calculated in the wrong scope (inside the loop) and so is the higherthanaverage. To fix it:
class Program
{
static void Main(string[] args)
{
double[] prices = new double[5];
int count = 0;
double TotalValues = 0;
double Average = 0;
string inputString;
double lessthanfive = 0;
double higherthanaverage = 0;
int x;
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
if (prices[x] < 5)
lessthanfive++;
}
Average = prices.Average();
higherthanaverage = prices.Where(price => price > Average).Count();
Console.WriteLine();
Console.WriteLine("The Sum of The Values Are: {0:C2}", TotalValues);
Console.WriteLine("Numbers Less Than $5.00 Are: {0:C2}", lessthanfive);
Console.WriteLine("The Average of The 20 Prices Are: {0:C2}", Average);
Console.WriteLine("Numbers Higher then Average Are: {0:C2}", higherthanaverage);
Console.ReadLine();
}
}
I'm new to C#, well, coding in general.
I have done fairly well by myself to date, in this introduction course I am taking, but I ran into a road bump.
I am trying to figure out how to code a if statement that will run inside a loop to analyze 5 different ints as they are entered and to put the max int and min int seperatly so that I can ue the remaining three ints to make a calculation.
To be exact, validate user input and remove the min/max user input to average the remaining three.
PS, I tried an array but for some reason it wasn't working well. I don't have the code as I'm at work right now though. I was told in a lecture that an if statement should be used but arrays are possible too.
Thank you for your time and any possible answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city, value;
double rating, avg = 0;
double[] array1 = new double[5];
double max = 0;
double min = double.MaxValue;
double score, totalScore = 0;
//get basic information
do
{
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
value = Console.ReadLine();
score = Convert.ToDouble(value);
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
array1[s] = Convert.ToDouble(score); //----this line keeps throwing an exception
}
Console.ReadLine();
//calculate totalScore by dropping min/max scores and averaging them times dive rating
foreach (int i in array1)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
totalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", totalScore);
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
}
}
}
or you can go list route and
List<int> apples = new List<int>();
apples.Add(31);
apples.Add(34);
apples.Add(100);
apples.Add(57);
apples.Add(1);
int min = apples.Min();
int max = apples.Max();
apples.Remove(min);
apples.Remove(max);
decimal average = (decimal)(apples.Sum()) / apples.Count;
Not sure about your question... You want to know, the max and min about 5 values, and the avarage about the three others...
int[] n = { 4, 7, 29, 3, 87 };
int max = 0;
int min = int.MaxValue;
double avg = 0;
foreach (int i in n)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
avg = avg / n.Count - 2;
try this code:
int[] a = new int[5];
int minpos;
int maxpos;
int min = Int32.MaxValue;
int max = a[0];
int temp = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" Enter number " + (i + 1));
Int32.TryParse(Console.ReadLine(), out temp);
a[i] = temp;
//Decision Making Logic
if (min > temp)
{
min = temp;
minpos = i;
}
if (max < temp)
{
max = temp;
maxpos = i;
}
}
//At the end of this loop you will see that minpos contains the index of minimum element
//and maxpos contains index of maximum element,values in remaining indeces contain elements that are neither max or min in that //collection
Thanks guys, it appears I needed a good night of sleep. Thanks a ton for all these helpful answers as I'm sure I will be delving into those methods soon and it will be good to be able to get a head start on them. Here is my code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city;
double rating, avg = 0;
double max = 0;
double min = 10;
double score, value = 0, totalScore = 0, finalScore = 0;
//get basic information
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
score = Convert.ToDouble(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
if (score > max)
max = score;
if (score < min)
min = score;
totalScore = score + totalScore;
}
Console.ReadLine();
\\Calculate values
value = totalScore - max - min;
avg = value / 3;
finalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", finalScore);
Console.WriteLine("\n");
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
Console.WriteLine("\n");
}
}
}