Reputation: 79
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();
Upvotes: 2
Views: 924
Reputation: 593
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();
Upvotes: 1
Reputation: 3967
You could use something like this :
while(true)
{
int input = Convert.ToInt32(Console.ReadLine());
if(input == 0)
break;
//do you math here
}
Upvotes: 0
Reputation: 3240
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);
}
Upvotes: 0
Reputation: 18068
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();
Upvotes: 6