Hi

I would like to write program that calculate the sum of all integers from a minimum number up to the maximum number.by using the following formula?

sum = 1/2 * number of integer * (minimum numbers + maximum number)

How can I do it?

I'm happy to do the psudo-code for you as this program is really simple.Although I won't be writing the code. I suggest you write some code following the below steps and once you get stuck, just raise another quetion with the code you've achieved.

make these variables:
1-sum (perhaps global but it doesn't matter in this case)
2-min_num ( it takes in user input)
**3-max_num **(it takes in user input)

then step 4 -> do some checking to see the variables (min_num & max_num) are not empty and contain some values. You'll need to parse them as integers or whatever type you're expecting from your users such as float. It might be a good idea to display a message if users are trying to use your calculator but they aren't entering anything or entering some text which is not acceptable.

5- Use an if-statement to compare min_num < max_num

6- inside your if-statement block.. do your formula. Here where you use the sum to store the result in then return it to users. And if you want to go a little nuts with the result you can say if sum <= 0, then you can return a message to your users saying.. The total is less than or equal to zero.

What is number of integer?

I hope this helps.

Thank Sir
I don't know why I get ziro 0

user input :min_num: 2
user Input max_num: 5

And I should get 14 but I get 0 why?
I thing I have to use forloop to get the total Number of intgers
total of integer 2, 3, 4, 5 equal, 1/24(2 + 5) = 2*7 = 14.

`if (min_num < max_num)
            {
                Number of intgers= min + max;
                sum = 1 / 2 * Number of intgers * (min_num + max_num);
            }

            txtSum.Text = sum.ToString();`

Edited 3 Years Ago by tony75

Thank Sir
I still get Zero? Idon't know why?

user input :min_num: 2
user Input max_num: 5

I thing I have to use forloop to add one number from min_num to max_num the total Number of intgers? ist right

sum = 1/2 * number of integer * (minimum numbers + maximum number)
total of integer 2, 3, 4, 5 equal, 1/2 4(2 + 5) = 2*7 = 14.

'if (min_num < max_num)
{
Number of intgers= max_num - min_num +1 ;
sum = 1 / 2 * Number of intgers * (min_num + max_num);
}
txtSum.Text = sum.ToString();`

You get zero because you use 1 / 2. This is integer division and will give the correct result of zero! Use your formula as I did.

Try to change the data type of result to double and this will give you a fractional number E.g 1/2 = 0.5 rather than 0

This question has already been answered. Start a new discussion instead.