This is the problem:
Write a console-based application that allows the user to
enter any number of integer values continuously (in any
order) until the user enters 999. Display the sum of the values
entered, not including 999.
This is what I have done
int number = 1;
double sum;
const int LIMIT = 999;
while( number < LIMIT )
{
Console.WriteLine("{0}", number);
number += 1;
}
My question is how can i display the sum of the values entered?
Loading
Mamta MPosted Jan 2, 2012, 11:04 PM
The logic you have used so far is totally wrong.
As per your question, you want to add up the numbers entered by the user,
not the numbers from 1 to 999, whereas your code is printing numbers from 1 to 999.
So here's how you can modify the logic.
1. Begin a loop.
2. Accept number from user.
3. Is it 999? Yes, then exit out of the loop.
4. If no, then accumulate the sum.
5. Repeat till user enters 999.
6. Outside the loop, display the accumulated sum.
The code for the above is:
using System;
class Program
{
static void Main(string[] args)
{
int number = 1;
int sum=0;
do{
number = int.Parse(Console.ReadLine());
if(number!=999)
{
sum+=number;
}
else
break;
}
while( number != 999);
// Now sum has accumulated the sum of all numbers excluding 999
Console.WriteLine("The sum is {0}", sum);
}
}
Prime bPosted Jan 2, 2012, 11:11 PM
Prime bPosted Jan 2, 2012, 11:00 PM
int number = 0;
double sum;
const int LIMIT = 999;
while( number < LIMIT )
{
Console.WriteLine("{0}", number);
number += 1;
sum = number + number - 1;
Console.WriteLine("{0}", sum);
}
But for some reason it just starts at like 800