while statement-to repeat it again - c#

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.

Related

school homework - grade calculation

i have got questions.
my problem is The user is asked to enter 20 exam grades. If the grades entered are less than 0 or greater than 100, you should be asked to enter again. How can I do that?
int not;
bool test = true;
for (int i = 0; i < 20; i++)
{
Console.Write((i + 1) + (".Not:"));
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
test = false;
Console.Write("Try again!");
}
else
{
test = true;
}
}
I want to use bool while doing this. would be glad if you help. thank you in advance
i changed code but i used goto. I dont want use to goto. How can i use bool doing this ?
int not;
int temp = 0;
for (int i = 0; i < 20; i++)
{
Console.Write("Add Not : ");
backtoAdd:
not = Convert.ToInt32(Console.ReadLine());
if (not < 0 || not > 100)
{
Console.WriteLine("Try Again!");
goto backtoAdd;
}
Console.WriteLine((i+1)+". Not : "+not);
temp = temp + not;
}
Console.Write("sum of not : "+temp);
Console.ReadKey();
As you mentioned it can be done with a while loop and condition to stop the loop. You can simplify it, I have added comments in the code example:
// declarations
int counter = 0;
int maxExamGradesInputCount = 20;
int highestGrade = 100;
int lowestGrade = 0;
// as long as counter is not equal to maxExamGradesInputCount continue
while (counter != maxExamGradesInputCount)
{
// we give input
string? input = Console.ReadLine();
// we try to parse our input
var parsed = int.TryParse(input, out var grade);
// if our input is parsed correctly
if (parsed)
{
// we check if the input value between the given range
if (grade < lowestGrade || grade > highestGrade)
{
Console.WriteLine("Try Again!");
}
else
{
// if with in range count
counter++;
}
}
}

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;

how to write a console application that calculates the sum of a given number of integers

Write a console application that calculates the sum of a given number of integers.
The numbers are entered one per line, and the application will read one by one until the user writes the character instead of a number. When the user has typed x, the application knows that all the numbers in the string have been entered and displays their amount.
If the first thing the user enters is the x character, the application will return 0.
Example:
For input:
2
5
-3
1
X
The console will display:
5
and this is my code
string[] answer = new string[10];
int sum = 0
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Can anyone tell me why is not working?
First of all, the working code (I didn't focus on X but on any char that isn't a number):
int n;
int sum = 0;
while (int.TryParse(Console.ReadLine(), out n))
{
sum += n;
}
Console.Write(sum );
Console.ReadKey();
Secondly, your code doesn't work because your array is full of 'null'-s when you try to parse the content of its first cell in 'answer[i]'
Here's a dumb (a bit) fix for your code:
string[] answer = new string[10];
//HERE
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Another problem with your code is you don't stop the iteration once "x" is entered, but continue until the end of the array (until it's been 10 times).
Here's kind of a complete fix for your code:
string[] answer = new string[10];
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
break;
}
sum += Int32.Parse(answer[i]);
}
Console.WriteLine(sum);
Console.Read();
Few issues:
I think order of your code instructions is not correct. First time when you parse your array element, its not yet initialized.
int sum = 0 is missing ; at the end.
You should always use TryParse instead of Parse
Try the following code:
string[] answer = new string[10];
int sum = 0, number;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
Console.WriteLine(sum);
break;
}
if(Int32.TryParse(answer[i], out number))
sum += number;
}
I gave you your terminating 'x'
var answer = Console.ReadLine();
var sum = 0;
while (answer != "x")
{
if (Int32.TryParse(answer, out var value))
{
sum += value;
}
answer = Console.ReadLine();
}
Console.WriteLine(sum);
You should check for "x" first since int.Parse("x") throws exception:
Wrong order (current code):
sum += Int32.Parse(answer[i]); // <- this will throw exception on "x" input
if (answer[i] == "x") {
...
}
...
Right order:
if (answer[i] == "x") {
...
}
else
sum += Int32.Parse(answer[i]);
...
in order to check for syntax errors (e.g. when user inputs "bla-bla-bla") I suggest int.TryParse instead of int.Parse and let's get rid of the array why should we collect the items (esp. with unwanted restriction of 10 items)?
// long: we don't want overflow, e.g. 2000000000, 1000000000
long sum = 0;
while (true) {
// Trim() - let's be nice and allow user put leading/trailing spaces
string input = Console.ReadLine().Trim();
if (string.Equals("x", input, StringComparison.OrdinalIgnoreCase))
break;
if (int.TryParse(input, out var item))
sum += item;
else {
//TODO: Incorrect input, neither integer nor "x" (e.g. "abracadabra")
}
}
Console.WriteLine(sum);
Console.Read();

C# Displaying every other number from a user in a console app

I need to write a console app that asks the user how many number (double) to enter. After accepting that many numbers, display every other number entered. There always seems to be an error when I try to use a double. I also get this error "System.IndexOutOfRangeException was unhandled
HResult=-2146233080
Message=Index was outside the bounds of the array."
after the the for loop has gone through the last loop for this line
myArrai1[i] = int.Parse(Console.ReadLine());
in the first for loop
this all the code I have been able to try to brainstorm with.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
int i = 0;
for (i = 1; i <= number; i++)
{
Console.WriteLine("Enter Number " + i.ToString() + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
for (i = 0; i < number; i++)
{
Console.WriteLine("Every other number entered: ");
Console.WriteLine(myArrai1[i += 2]);
}
Console.ReadLine();
}
}
}
Not too far off, main changes to fix fix this was loop#1 was set to 0 index to prevent out of range and loop#2 was simplified by intervaling at 2 of ++.
The rest of the changes were aesthetic; I changed the input Console.WriteLine to just Console.Write to keep the input on the same line, and moved the Every Other Line statement to precede the output display loop instead of being written on every iteration.
Console.Write("Enter Item Count: ");
int number = int.Parse(Console.ReadLine());
int[] myArrai1 = new int[number];
for (int i = 0; i < number; i++) {
Console.Write("Enter Number " + (i + 1) + ": ");
myArrai1[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Every other number entered: ");
for (int j = 0; j < number; j = j + 2) {
Console.WriteLine(myArrai1[j]);
}

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();

Categories