When input is 0 stop taking values - c#

I need code, that takes inputs from user and then adds them together-simple. But I can't find a way, to take inputs until 0 is pressed and than add the numbers together..
So far, I made it take 10 values, but like I said it needs to be custom.. Thanks for your help.
int[] myarray = new int[10];
for (int i = 0; i < 10; i++)
{
myarray[i] = Convert.ToInt32(Console.ReadLine());
}
int a = 0;
for (int j = 0; j < 10; j++)
{
a = a + myarray[j];
}
Console.WriteLine(a);
Console.ReadLine();

The code below is not limited to 10 inputs, you can give as many input as you like
int sum=0, input;
do
{
input = Convert.ToInt32(Console.ReadLine());
sum += input;
}
while(input != 0);
Console.WriteLine(sum);
Console.ReadLine();

Check the input before adding it, and break out of the loop if it is 0:
int input = Convert.ToInt32(Console.ReadLine());
if(input == 0)
{
break;
}
myarray[i] = input;

As you don't know the length of the array, I'd recommend using a list. I've also added a tryparse to cope with dodgy user input. You can use Sum() on the list to avoid writing out another loop.
IList<int> myList = new List<int>();
string userInput = "";
int myInt = 0;
while (userInput != "0")
{
userInput = Console.ReadLine();
if(Int32.TryParse(userInput, out myInt) && myInt > 0)
{
myList.Add(myInt);
}
}
Console.WriteLine(myList.Sum());
Console.ReadLine();

When you have an unknown size array you should use a list.
var ls = new List<int>();
while(true)
{
var input = Convert.ToInt32(Console.ReadLine());
if(input == 0)
break;
ls.Add(input);
}
Lists by MSDN

You could use something like this :
while(true)
{
int input = Convert.ToInt32(Console.ReadLine());
if(input == 0)
break;
//do you math here
}

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++;
}
}
}

Making a program that sums up only even numbers entered from console

In one of my classes I was given an assignment to write a simple program that combines multiple numbers entered from the console, but only adding up the even ones. I was able to do the summing up part pretty easily but I can't figure out how to check for even numbers! If anyone can figure out how or explain for a beginner how to do it would be greatly appreciated.
Here's the full code so far:
using System;
namespace Test_3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
Console.WriteLine("The sum of the numbers is " + sum);
}
}
}
You seem to already know how to get the even numbers but here is how to apply it!
Console.WriteLine("Amount of numbers n = ");
var n = int.Parse(Console.ReadLine());
Console.WriteLine("Enter numbers:");
var sum = 0;
for (int i = 0; i < n; i++)
{
var num = int.Parse(Console.ReadLine()); //first read a number from the console
if (num % 2 == 0) //then check if it is even
{
sum = sum + num; //if it is, then add it to sum
}
}
Console.WriteLine("The sum of the numbers is " + sum);
You seem not to get the idea of an if-clause, let me explain this, using the following pieces of code:
Your code:
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
}
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
This calculates the sum of all numbers (you check whether a number is even or not, but you don't use that information).
My proposal: (you check if a number is even, and you use that information)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
else
{
}
}
Another one, how to calculate the sum of the odd numbers? (Here you check if a number is even, but you use the case where it is not)
for (int i = 0; i < n; i++)
{
if (sum%2 == 0)
{
}
else
{
var num = int.Parse(Console.ReadLine());
sum = sum + num;
}
}
So, you see? You can use if-clauses to filter out what you want to do when a condition is met or when a condition is not met, that's the whole idea behind it.
You need to check whether the variable num is divisible by two instead of the sum. The code you have checks if the sum is even and if so does nothing since you didn't add anything to the if statement. Instead, you should be doing if ( num % 2 == 0) .
You also need to move where num is declared to the top of the for loop and move the part where you add to the sum to the inside of the conditional (The if statement).

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# How do I use a variable outside of a loop that changes from string to int inside the loop?

The code:
string[] numbers = new string[2];
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = Console.ReadLine();
if (int.TryParse(numbers[i], out int numberTry) && i == 0)
Console.WriteLine("That would be a number yes.");
else if (int.TryParse(numbers[i], out numberTry))
Console.WriteLine("Lovely work! That is indeed two numbers!");
else
{
Console.Clear();
Console.WriteLine("That's not a number. I am dissapointed.");
Console.ReadKey();
Environment.Exit(0);
}
}
My problem here is that I can't use numbers[] outside of the loop as an int because it chancges from a string to an int inside of the loop. I need to be able to send it with a method as an int to perform a operation on numbers[0] and numbers[1].
Thanks in advance!
Could you try this. It should work.
int[] numbers = new int[2];
for (int i = 0; i < numbers.Length; i++)
{
var number = Console.ReadLine();
if (int.TryParse(number, out int numberTry) && i == 0)
{
Console.WriteLine("That would be a number yes.");
numbers[i] = numberTry;
}
else if (int.TryParse(number, out numberTry))
{
Console.WriteLine("Lovely work! That is indeed two numbers!");
numbers[i] = numberTry;
}
else
{
Console.Clear();
Console.WriteLine("That's not a number. I am dissapointed.");
Console.ReadKey();
Environment.Exit(0);
}
}
Console.ReadKey();

Is there a way to enter number without showing them immediately?

I want to enter 10 numbers, and then show them in 1 line like this:
1,4,5,2,456,23,... and so on..
and it keeps writing them as I am entering them, and in the end when it's supposed to show all numbers in 1 line it shows only the last one.
I know it's possible with random numbers but when I enter them on my own I don't know how not to show them at all or keep them in 1 line and if it is even possible?
int a;
int x;
Console.WriteLine("a:");
a = int.Parse(Console.ReadLine());
x = 10;
for (int i = 0; i < x; i++)
{
a = int.Parse(Console.ReadLine());
}
Console.ReadKey();
you can use
Console.ReadKey(true)
it reads a key from console and does not show it.
you can use this to read word from console without showing it
public static string ReadHiddenFromConsole()
{
var word = new StringBuilder();
while (true)
{
var i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (i.Key == ConsoleKey.Backspace)
{
if (word.Length > 0)
{
word.Remove(word.Length - 1, 1);
Console.Write("\b \b");
}
}
else
{
word.Append(i.KeyChar);
Console.Write("*");
}
}
return word.ToString();
}
You can use this code:
static void Main(string[] args)
{
int length = 10;
int[] myNumbers = new int[length];
for (int i = 0; i < length; i++)
{
Console.Write("Enter number:" );
myNumbers[i] = Convert.ToInt32(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("Your numbers: {0}", string.Join(",", myNumbers));
}
i dont know how to write them at the end all in 1 line?
Well you need to save them as they are entered:
int num;
var nums = new List<int>();
while (nums.Count < 10)
{
Console.Write("Enter: ");
if (int.TryParse(Console.ReadLine(), out num))
{
nums.Add(num);
Console.Clear();
}
}
Console.WriteLine(string.Join(", ", nums));

Categories