- 1
Take a number N as input and output the sum of all numbers from 1 to N (including N). Sample Input 100 Sample Output 5050
You can iterate over a range and calculate the sum of all numbers in the range. Remember, range(a, b) does not include b, thus you need to use b+1 to include b in the range.
8 Answers
+ 6
elly paul
Please don't duplicate your questions.
Also, please show your attempt at a solution to the problem.
The question wants you to write a program that takes a number N as an input and then use a loop to add all of the numbers from 1 to N together, totalling them up and then output the total. Please attempt to do this first and post your try if you continue to have issues.
Areas to review: input(), int(), variables, for loop, range(), print()
Note: there is a much faster way to calculate the sum of all numbers from 1 to N using the Guass formula, but you should learn the intended method first.
+ 2
Please show your attempt before we can help.
+ 1
You do not need any if/else. You can just use:
print((1+N)*N//2)
+ 1
Try N*(N+1)/2
To calculate sum of number from 1 to N
+ 1
@ ChaoticDawg
I've been stuck on this one to be honest.
For the sake of learning and using the 'for loop', how can we use this to solve the problem?
All that I seem to be able to get with the 'for loop' is the counts itself.
int N = Convert.ToInt32(Console.ReadLine());
for (int sum = 0; sum <= N; sum ++)
Console.WriteLIne(sum);
---------------------------------------------------
I would still think you'd have to skip the for loop and use N*(N+1)/2
But i feel like im missing something obvious.
Can anyone help? :)
Thanks in advance.
+ 1
PBOL
Create your variable to hold the sum outside of and prior to the for loop.
Loop from 1 to N. Add the current count of the loop to the sum with each iteration of the loop.
After the loop output the sum.
Pseudocode:
total = 0
loop i from 1 to N
total += i
print total
+ 1
@ChaoticDawg
I got it now! Thanks for the help! :)
- 1
People thanks to your help and motivation I finally got it rightN = int(input())
if N%2==0:
print ((N//2)*(1+N))
else:
print (((N+1)//2)*N)