While loop doesnt function when calculatin all positive numbers c# - c#

I am making a while loop. The purpose of the loop is to take all the positive numbers and calculating the average. It works most of the time but not always. Can someone help? here is the code:
double count = 0;
int sum = 0;
int input = -1;
while (input != 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
if (input < 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
}
}
if (input == 0)
{
Console.Write($"Average of all positive numbers is: { (sum += input) / count:0.00} ");
}

The second if is redundant it should work just like this
while (input != 0) {
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
}
Your problem was when you enter a negative number it gives you the option to enter another, but then you enter a new iteration of the while loop and it asks you to enter another number. Removing the second if should fix your problem. Hope i helped :)

This code does not throw exceptions when non numeric data is entered
int count = 0;
long sum = 0;
int input;
Console.Write("Enter a number: ");
while (int.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter a number: ");
if (input > 0)
{
sum += input;
count++;
}
}
Console.Write($"Average of all positive numbers is: {sum} / {Math.Max(count,1.0)} = {Math.Round( sum / Math.Max(count,1.0), 2)}.");

Related

Find the sum of user input (only the positive integers) C#

Find the sum of user input (only the positive integers). The code I wrote calculates them in weird way and i got confused. Thanks in advance.
Console.WriteLine("Enter numbers lenght: ");
int lenght = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int input = 0;
for(int i = 0; i < lenght; ++i)
{
Console.WriteLine("Enter a number: ");
input = Convert.ToInt32(Console.ReadLine());
if(input >= 0)
{
sum = input + input;
}
}
Console.WriteLine("The sum of the positive numbers is: " + sum);
sum = input + input; is wrong,
change it to :
sum = sum + input;
or
sum += input;

C#. How to count digits entered from input?

This is a code which multiplies numbers, user enters.
string x;
double t, s = 1;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
t = Convert.ToDouble(x);
s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.ReadLine();
It shows the result at the end, but how to make it show a total count of numbers entered?
For example: I enter 1, 2 and 3. So total count is 3.
string x;
double t, s = 1;
int count = 0;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
t = Convert.ToDouble(x);
s *= t;
count++;
}
Console.WriteLine("The result is: {0}", s);
Console.WriteLine("The count is: {0}", count);
Console.ReadLine();
It is good to use TryParse to avoid FormatException
Char.IsDigit returns true is current char is digit (obviously)
Example:
string x;
double t, s = 1;
int digitCount = 0;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
if (!Double.TryParse(x, out t))
continue;
foreach (var c in x)
if (Char.IsDigit(c))
digitCount++;
s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.WriteLine("The count of digits is: {0}", digitCount);
Console.ReadLine();
Why not a variable for counter?
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
int i=0;
while ((x = Console.ReadLine()) != "")
{
i++;
t = Convert.ToDouble(x);
s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.ReadLine();
You have to count the loop iteration for that use a counter variable:
int loopCounter=0;
while ((x = Console.ReadLine()) != "")
{
t = Convert.ToDouble(x);
s *= t;
loopCounter++;
}
Console.WriteLine("The count is: {0}", loopCounter);
You could try counting the number of characters in the string input (x).
int temp=x.Length();

C# Programming arrays

I am writing a program that takes the scores of homework assignments, puts them in a array, then averages them. But I need to make it so that these grades range from 1-10. I am not sure how to make it only accept Numbers 1-10. Everything else is complete.
Here is what i have so far:
namespace AverageScore
{
class AverageScore
{
//prompt user to enter the size of the array
public int GetNum()
{
Console.WriteLine("Please enter how many scores you want to save!");
string strNum = Console.ReadLine();
int num = int.Parse(strNum);
return num;
}
static void Main(string[] args)
{
AverageScore scoreObject = new AverageScore();
int arraySize = scoreObject.GetNum();
//define a double array to save scores
double[] scoreArray = new double[arraySize];
string inValue = "";
double sum = 0,
intValue;
Console.WriteLine("Please enter all homework scores");
int counter = 0;
while (counter < arraySize)
{
inValue = Console.ReadLine();
while (double.TryParse(inValue, out intValue) == false)
{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Array.Sort(scoreArray);
double lowest= scoreArray[0];
double highest = scoreArray[arraySize-1];
sum = sum - lowest - highest;
double average = sum / arraySize;
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
Console.Read();
}
}
}
so your problem is to restrict a input to 1-10 correct?
Why not just:
public int InputGrade()
{
Console.Clear();
Console.WriteLine("Please enter a grade [1-10]");
var grade = -1;
if (!Int32.TryParse(Console.ReadLine(), out grade))
return InputGrade();
if (grade < 1 || grade > 10)
return InputGrade();
return grade;
}
then you should be able to use it like this and it is cleaner:
while (counter < arraySize)
{
var grade = InputGrade();
sum += grade;
scoreArray[counter++] = grade;
}
recommendation
Indeed you should refactor the input from the calculation part - you code will get much more cleaner and more readable:
IEnumberable<int> InputGrades()
{
var count = GetNum();
var grades = new List<int>();
for (var i = 0; i < count; i++)
grades.Add(InputGrade());
return grades;
}
void OutputScores(IEnumerable<int> grades)
{
var scores = grades.Cast<doulbe>().ToArray();
var lowest = scores.Min();
var highest = scores.Max();
var average = scores.Average();
Console.WriteLine("The average grade of the scores is" + average);
Console.WriteLine("The Lowest Score is" + lowest);
Console.WriteLine("The Highest Score is" + highest);
}
Adjust the while loop condition to check that the number is in range (added a simple string format to present the previous invalid entry):
while (double.TryParse(inValue, out intValue) == false || intValue < 1.0 || intValue > 10.0**)
{
Console.WriteLine(String.Format("Invalid input = {0} stored in intValue", intValue));
inValue = Console.ReadLine();
}
This should do it:
while (counter < arraySize){
inValue = Console.ReadLine();
while (true){
if(double.TryParse(inValue ,out intValue) {
if(intValue >=1 && intValue <=10){
break;
}else{
Console.WriteLine("Input must be in the range 1-10");
inValue = Console.ReadLine();
}
}else{
Console.WriteLine("Invalid input = 0 stored in intValue");
inValue = Console.ReadLine();
}
}
sum += intValue;
scoreArray[counter] = intValue;
counter++;
}
Uses a loop to check if the value entered is correct:
while (int.Parse(inValue) < 1 || int.Parse(inValue) > 10) inValue = Console.ReadLine();

Not using a duplicate number when using a decrement

I am trying to write a program using a loop with a decrement and not to be able to use the same number twice. If using the same number, I would want a "invalid number" displayed. It is a number system set up to read numbers between 10 and 100. If it goes over 100, "invalid number" is displayed. This is what I have so far:
string userNumber;
int userNumberInt;
int previousNumber = 0;
for (int counter = 0; counter <= 10; counter++)
{
Console.WriteLine("Enter your number");
userNumber = Console.ReadLine();
userNumberInt = Convert.ToInt32(userNumber);
if ((userNumberInt <= 100) && (userNumberInt >= 10))
{
Console.WriteLine("Your number is " + userNumber);
previousNumber = userNumberInt;
}
else if
(previousNumber == userNumberInt)
{
Console.WriteLine("Number is invalid.");
}
// number is invalid
else
// number is valid
{
Console.WriteLine("Invalid number.");
counter--;
}
}
Console.ReadLine(); // for last enter key
}
}
}
With your use of previous, the same numbers could be entered. For example, the first number entered could be 12, so 12 becomes previousNumber. Then when you enter 12 again you'll display "invalid number" which is good, but you enter 13, then 13 becomes the previousNumber and now you can enter 12 again. So what you should do is store all of your valid numbers in a list and check if your userInput is in the list so that you're not using duplicate numbers.
public static void Main(string[] args)
{
List<int> validInputs = new List<int>();
for (int counter = 0; counter <= 10; counter++)
{
Console.Write("Enter a number: ");
string stringInput = Console.ReadLine();
int numberInput;
if (int.TryParse(stringInput, out numberInput))
{
if ((10 <= numberInput && numberInput <= 100) &&
validInputs.Contains(numberInput) == false)
{
Console.WriteLine("Number is valid");
validInputs.Add(numberInput);
}
else
{
// This is not a valid number cause it's not in the range or it's a duplicate
Console.WriteLine("Invalid number");
counter--;
}
}
else
{
// This is not a valid number
Console.WriteLine("Invalid number");
counter--;
}
}
}

while statement-to repeat it again

Everything is allright except the while statement.If you guys can help me that would be great.When the user write "Y" to do it again, he see: max value is: bla bla.
the user has to give a new positive number instead of to see the maximum value over and over again.
Console.WriteLine("Please give a positieve number. if you enter a negatieve number its not going to work");
int invoer = 0, max = 0;
string repeat = "";
do
{
for (int i = 1; invoer >= 0; i++)
{
Console.Write(i + "> ");
invoer = int.Parse(Console.ReadLine());
if (max < invoer)
{
max = invoer;
}
}
Console.WriteLine("Maximum value is: " + max);
Console.WriteLine("do you want to try again? y/n: ");
repeat = Console.ReadLine();
} while (repeat == "y" || repeat == "Y");
Im guessing at what this is supposed to be doing....
{
//Console.WriteLine("Please give a positive number. if you enter a negative number its not going to work");
int invoer;
int max;
string repeat;
do
{
//they have given a negative number and wish to try again
Console.WriteLine("Please give a positive number.\nIf you enter a negative number its not going to work");
invoer = 0;
max = 0;
repeat = "";
for (int i = 1; invoer >= 0; i++)
{
Console.Write(i + "> ");
invoer = int.Parse(Console.ReadLine());
if (max < invoer)
{
max = invoer;
}
}
Console.WriteLine("Maximum value is: " + max);
Console.WriteLine("do you want to try again? y/n: ");
repeat = Console.ReadLine();
} while (repeat == "y" || repeat == "Y");
}
I'm not 100% sure what you're trying to do, but it looks like you need to move your deceleration of invover and max into your do loop.

Categories