Display running total - c#

Hi I was wondering if someone could explain how to to make this method diplay a running count and average, and not just display it once the user has finished entering its data?
public void InScreen()
{
int count = 0;
double total = 0.0;
double average = 0.0;
double number;
Console.WriteLine("Enter the set of scores (enter 0 to indicate end of set)");
number = double.Parse(Console.ReadLine());
while(number != 0)
{
total += number;
count++;
number = double.Parse(Console.ReadLine());
}
if (count != 0)
average = total / count;
Console.Beep(20000, 2000);
Console.WriteLine("The user has entered {0} scores.", count);
Console.WriteLine("The sum of scores entered = {0}", total);
Console.WriteLine("The average of scores entered = {0}", average);
}

Simply try this
static void Main(string[] args)
{
try
{
StringBuilder runningtotal = new StringBuilder();
int count = 0;
double total = 0.0;
double average = 0.0;
double number;
Console.WriteLine("Enter the set of scores (enter 0 to indicate end of set)");
number = double.Parse(Console.ReadLine());
runningtotal.Append(number.ToString());
while (number != 0)
{
total += number;
count++;
number = double.Parse(Console.ReadLine());
if (number!=0)
{
runningtotal.Append("+" + number.ToString());
}
}
if (count != 0)
average = total / count;
Console.Beep(20000, 2000);
Console.WriteLine("The user has entered {0} scores.", count);
Console.WriteLine("The sum of scores entered = {0}", total);
Console.WriteLine("The average of scores entered = {0}", average);
Console.WriteLine(runningtotal);
string[] inputs = runningtotal.ToString().Split('+');
Console.WriteLine("Running total");
int temp=0;
for (int i = 0; i <inputs.Length; i++)
{
if (temp==0)
{
Console.WriteLine("{0} = {1}",inputs[i],inputs[i]);
temp = Convert.ToInt32(inputs[i]);
}
else
{
Console.WriteLine("{0} = {1}", inputs[i], Convert.ToInt32(inputs[i]) + temp);
temp = Convert.ToInt32(inputs[i]) + temp;
}
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
Console.ReadLine();
}
Output Screenshot
Read Here

Related

Console.Redline reading second line

I have a simple program that tells the user to input n amount of students, foreach student an x amount of money is allocated. At the end, the program divides x by n, meaning the total money is divided equally by the students.
The problem is that Console.Readline() is reading the second inputted value as see below.:
This means that the user has to enter the values two times, each time Console.Readline() is called, which is obviously wrong!
Code:
static void Main(string[] args)
{
double total = 0;
int noOfStudents = 0;
try
{
Console.WriteLine("Please enter the number of students :");
noOfStudents = checkInputTypeInt(Console.ReadLine());
Console.WriteLine("Enter the students(" + noOfStudents + ") money!");
for (int i = 0; i <= noOfStudents - 1; i++)
{
double money = checkInputTypeDouble(Console.ReadLine());
total += money;
}
double dividedTotal = total / noOfStudents;
Console.WriteLine("Total divided by " + noOfStudents + " is $ " + dividedTotal.ToString("F2"));
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
private static int checkInputTypeInt(string s)
{
int numericValue = 0;
bool done = false;
while (!done)
{
if (!int.TryParse(Console.ReadLine(), out numericValue))
Console.WriteLine("The input must be between 0 and 1000!");
else if (numericValue > 100)
Console.WriteLine("The input must be between 0 and 1000!");
else
done = true;
}
return numericValue;
}
You ReadLine twice:
noOfStudents = checkInputTypeInt(Console.ReadLine());
and in checkInputTypeInt method:
if (!int.TryParse(Console.ReadLine(), out numericValue))
You should either send only the string to method like this:
noOfStudents = checkInputTypeInt(Console.ReadLine());
and in your method just check that value like:
if (!int.TryParse(s, out numericValue))
in this case you should have the while loop in your main method.
or just use readline in the called method.
Console.WriteLine("Please enter the number of students :");
noOfStudents = checkInputTypeInt(); // and you should change your method to fit no arguments.
Edit: final codes:
static void Main(string[] args)
{
double total = 0;
int noOfStudents = 0;
try
{
Console.WriteLine("Please enter the number of students :");
noOfStudents = checkInputTypeInt();
Console.WriteLine("Enter the students(" + noOfStudents + ") money!");
for (int i = 0; i <= noOfStudents - 1; i++)
{
double money = checkInputTypeDouble(Console.ReadLine());
total += money;
}
double dividedTotal = total / noOfStudents;
Console.WriteLine("Total divided by " + noOfStudents + " is $ " + dividedTotal.ToString("F2"));
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
private static int checkInputTypeInt()
{
int numericValue = 0;
bool done = false;
while (!done)
{
if (!int.TryParse(Console.ReadLine(), out numericValue))
Console.WriteLine("The input must be between 0 and 1000!");
else if (numericValue > 100)
Console.WriteLine("The input must be between 0 and 1000!");
else
done = true;
}
return numericValue;
}
OR:
static void Main(string[] args)
{
double total = 0;
int noOfStudents = -1;
try
{
Console.WriteLine("Please enter the number of students :");
do{
noOfStudents = checkInputTypeInt(Console.ReadLine());
}while(noOfStudents == -1);
Console.WriteLine("Enter the students(" + noOfStudents + ") money!");
for (int i = 0; i <= noOfStudents - 1; i++)
{
double money = checkInputTypeDouble(Console.ReadLine());
total += money;
}
double dividedTotal = total / noOfStudents;
Console.WriteLine("Total divided by " + noOfStudents + " is $ " + dividedTotal.ToString("F2"));
Console.ReadKey();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
private static int checkInputTypeInt(string s)
{
int numericValue = -1;
if (!int.TryParse(Console.ReadLine(), out numericValue))
Console.WriteLine("The input must be between 0 and 1000!");
else if (numericValue > 1000)
{Console.WriteLine("The input must be between 0 and 1000!");
numericValue = -1;
}
return numericValue;
}
Try to divide the noOfStudents and Console.ReadLine() like this:
int i = Convert.ToInt32(Console.ReadLine());
noOfStudents = i;

C# :Adapt a program to count the number of marks greater than or equal to 50

my code is where the user needs to enter a mark between and then if the mark is not between 0 and 100, it must ask again, i got that to work , but now the question states : Adapt the above program to also count the number of marks greater than or equal to 50.
How do I do this , I have tried declaring count an integer 0 but I am unsure how
to implement this.
Here is my code:
static void Main(string[] args)
{
int total = 0;
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.ReadLine();
}
First of all, I suggest extracting a method: do not cram everything into a single Main:
private static int readMark() {
Console.WriteLine("Enter your mark");
int result = 0;
while (true)
if (!int.TryParse(Console.ReadLine(), out result))
Console.WriteLine("Incorrect syntax, enter your mark again");
else if (result < 0 || result > 100)
Console.WriteLine("Mark should be in [0..100] range, enter your mark again");
else
return result;
}
Then let's read all the marks into a collection, say, an array:
static void Main(string[] args) {
int[] marks = new int[5];
for (int i = 0; i < marks.Length; ++i)
marks[i] = readMark();
}
Now it's time for the statistics. Usually we use Linq for this:
static void Main(string[] args) {
...
double average = marks.Average();
int sum = marks.Sum();
int countGreaterThan50 = marks.Count(item => item > 50);
But we can put a good old for / foreach loop for this:
static void Main(string[] args) {
...
int total = 0;
countGreaterThan50 = 0;
for (int i = 0; i < marks.Length; ++i) {
total += marks[i];
if (marks[i] > 50)
countGreaterThan50 += 1;
}
// (double) total - be careful with integer division:
// 91 / 5 == 18 when 91.0 / 5 == 18.2
double average = ((double) total) / marks.Length;
static void Main(string[] args)
{
int total = 0;
int gt50Count = 0;
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
if (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if (mark >= 50)
{
gt50Count++;
}
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Greater or equal to 50 count = " + gt50Count);
Console.ReadLine();
}
I would change the way you check if your mark is invalid to a while loop. With just that if check, if the user inserts invalid values consecutively, your code will accept it.
static void Main(string[] args)
{
int total = 0;
int marksAbove50Count = 0;
for (int x = 1; x <= 5; x++)
{
Console.WriteLine("Enter your mark");
int mark = int.Parse(Console.ReadLine());
while (mark > 100 || mark < 0)
{
Console.WriteLine("Invalid mark,Enter your mark again");
int newmark = int.Parse(Console.ReadLine());
mark = newmark;
}
total += mark;
if(mark >= 50) marksAbove50Count++;
}
Console.WriteLine("sum = " + total);
double average = (total / 5) * 1.00;
Console.WriteLine("average = " + average);
Console.WriteLine("Marks above 50 count: " + marksAbove50Count);
Console.ReadLine();
}

Dictionary.Count is not working as expected

The following line of code is not working as expected: If there are two dictionary entries it prints "2, 2" instead of "1, 2"
Console.WriteLine($"Student: {studentMap.Count} - Average Score: {average} - Letter Grade: {GetLetterGrade(average)}");
It is not listing the dictionary count like this line ↓↓↓ of code above it in the other for-loop.
Console.WriteLine($"Enter test {studentScores.Count + 1 } for student {studentMap.Count + 1 }");
namespace Program
{
class Program
{
static void Main(string[] args)
{
string totalStudents = string.Empty;
while (!IsNumeric(totalStudents))
{
Console.WriteLine("How many students will you be grading?");
totalStudents = Console.ReadLine();
if (!IsNumeric(totalStudents))
{
Console.WriteLine(string.Empty);
Console.WriteLine("Error! Please enter numeric value.");
}
}
int studentCount = Convert.ToInt32(totalStudents);
Console.WriteLine(string.Empty);
string totalScores = string.Empty;
while (!IsNumeric(totalScores))
{
Console.WriteLine("How many test scores will you enter for each student?");
totalScores = Console.ReadLine();
if (!IsNumeric(totalScores))
Console.WriteLine("Please enter a numeric value.");
}
int scoreCount = Convert.ToInt32(totalScores);
Dictionary<int, List<int>> studentMap = new Dictionary<int, List<int>>();
for (int students = 0; students < studentCount; students++)
{
List<int> studentScores = new List<int>();
for (int scores = 0; scores < scoreCount; scores++)
{
string scoreInput = string.Empty;
Console.WriteLine(string.Empty);
Console.WriteLine($"Enter test {studentScores.Count + 1 } for student {studentMap.Count + 1 }");
scoreInput = Console.ReadLine();
Console.WriteLine(string.Empty);
Console.WriteLine("--------------------");
int intScore = Convert.ToInt32(scoreInput);
studentScores.Add(intScore);
}
studentMap.Add(students, studentScores);
}
Console.WriteLine("The test results are as follows:");
Console.WriteLine(string.Empty);
for (int i = 0; i < studentMap.Count; i++)
{
List<int> studentScores = studentMap[i];
double scoreSum = studentScores.Sum();
double scoreNum = studentScores.Count();
double average = scoreSum / scoreNum;
Console.WriteLine($"Student: {studentMap.Count} - Average Score: {average} - Letter Grade: {GetLetterGrade(average)}");
}
Console.WriteLine();
Console.ReadLine();
}
static string GetLetterGrade(double average)
{
if (average >= 90)
{
return "A";
}
else if (average >= 80)
{
return "B";
}
else if (average >= 70)
{
return "C";
}
else if (average >= 60)
{
return "D";
}
else
{
return "F";
}
}
static double GetAverage(double sum, double count)
{
return sum / count;
}
static bool IsNumeric(string input)
{
int result;
return int.TryParse(input, out result);
}
}
}
You probably misunderstood the terms Dictionary<>.Count and index. Indexes start at 0 and Count property represents the number of items in the dictionary.
So, if you have 1 item in your Dictionary<>, it's index is 0 and Dictionary<>.Count is 1.

do/while and if/else problems

I have to put in an extra "test score" to get an answer.
(i.e i have to enter six 5' to get 25)
I can't get the do/while & if statements to loop if there is more than one number outside the "while" range. I haven't been coding for very long, a couple weeks so try and break down the answers. Thanks for the help!
Here is my code
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int i;
do
{
i = Convert.ToInt32(Console.ReadLine());
if (i < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
if (i > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (i < 0 || i > 100);
for (i = 0; i < n; i++)
{
scores[i] = int.Parse(Console.ReadLine());
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}",sum);
Console.ReadLine();
Put the do block that does the input validation inside the for loop:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
for (int i = 0; i < n; i++)
{
int input = -1;
do
{
input = Convert.ToInt32(Console.ReadLine());
if (input < 0)
{
Console.WriteLine("Please enter a value greater than 0");
}
else if (input > 100)
{
Console.WriteLine("Please enter a value less than 100");
}
} while (input < 0 || input > 100);
scores[i] = input;
}
int sum = 0;
foreach (int d in scores)
{
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
n is the number of tests, meaning the amount of scores counter i should be the same as the amount of tests. Also prefer Convert.ToInt32 to int.Parse since it throws exceptions in case it isn't able to make the conversion.
Console.Write("Enter the number of tests: ");
int n = Convert.ToInt32(Console.ReadLine());
int sum = 0, i = 0, score = 0;
int[] scores = new int[n];
Console.WriteLine("----------------------------------------");
do {
Console.WriteLine("Please enter the test score #" + (i + 1));
score = Convert.ToInt32(Console.ReadLine());
if (score < 0) {
Console.WriteLine("Please enter a value greater or equal to 0");
}
else if (score > 100)
{
Console.WriteLine("Please enter a value less or equal to 100");
}
else {
scores[i] = score;
i++;
}
} while (i < n);
foreach (int d in scores) {
sum += d;
}
Console.WriteLine("The sum of all the scores is {0}", sum);
Console.ReadLine();
Just for the potential learning opportunity, and and not as a direct answer to your question, here is the way I would do this exercise:
Console.Write("Enter the number of tests: ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("----------------------------------------");
Console.WriteLine("Please enter the test scores");
int AskForInteger()
{
while (true)
{
if (int.TryParse(Console.ReadLine(), out int i) && i >= 0 && i <= 100)
{
return i;
}
Console.WriteLine("Please enter a value between 0 and 100 inclusive");
}
}
int[] scores =
Enumerable
.Range(0, n)
.Select(x => AskForInteger())
.ToArray();
Console.WriteLine("The sum of all the scores is {0}", scores.Sum());
Console.ReadLine();
There are two options:
a. Start at 1 rather than 0 --> for (i = 1; i < n; i++)
b. Lower the value of n by 1 --> for (i = 1; i < n-1; i++)
Good luck

Sum of All Odd numbers C#

I have an assignment to input random numbers from the keyboard that is different from 0 and random number k. I need to find the sum of the odd numbers + k(if k is also odd). Also when typing the numbers only when 0 is being typed the typing of numbers is interrupted. This is what I've got so far!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main()
{
int k;
int min;
int max;
int odd = 0;
Console.WriteLine("Enter the value of k: ");
k = int.Parse(Console.ReadLine());
Console.WriteLine("Enter minimum integer: ");
min = int.Parse(Console.ReadLine());
Console.WriteLine("Enter maximum integer: ");
max = int.Parse(Console.ReadLine());
Console.Write("Odd: ");
for (int x = min; x <= max; x++)
{
if (x % 2 != 0)
{
Console.Write(x);
Console.Write(" + ");
odd += x;
}
}
Console.WriteLine();
Console.Write("Odd Numbers + K: ");
Console.WriteLine();
{
if (k % 2 !=0)
{
Console.Write(k);
Console.Write(" + ");
odd += k;
}
}
Console.Write("= ");
Console.Write(odd + "\n");
}
}
This code does what you need. It checks the bounds min and max. It finishes when zero is entered and it also keeps the total sum of the odd numbers.
Replace your static void Main() function with this one.
static void Main()
{
//int k;
int min;
int max;
int odd = 0;
Console.WriteLine("Enter minimum integer: ");
min = int.Parse(Console.ReadLine());
Console.WriteLine("Enter maximum integer: ");
max = int.Parse(Console.ReadLine());
Console.WriteLine("Enter your number: ");
bool userIsTyping = true;
while (userIsTyping)
{
Console.WriteLine("Enter another number: ");
int userNumber = int.Parse(Console.ReadLine());
if (userNumber == 0)
{
userIsTyping = false;
}
else if (userNumber > max)
{
Console.WriteLine("The number is out of bounds: greater than max.");
}
else if (userNumber < min)
{
Console.WriteLine("The number is out of bounds: less than min.");
}
else
{
if (userNumber % 2 != 0)
{
odd += userNumber;
Console.WriteLine("Current Total: " + odd.ToString());
}
else
{
Console.WriteLine("That is not an odd number.");
}
}
}
Console.WriteLine("The final result is: " + odd.ToString());
Console.ReadLine();
}

Categories

Resources