- 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.

11th Sep 2021, 8:28 PM
elly paul
elly paul - avatar
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.
11th Sep 2021, 8:43 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Please show your attempt before we can help.
11th Sep 2021, 8:39 PM
Kamil Hamid
Kamil Hamid - avatar
+ 1
You do not need any if/else. You can just use: print((1+N)*N//2)
11th Sep 2021, 11:09 PM
Coding Cat
Coding Cat - avatar
+ 1
Try N*(N+1)/2 To calculate sum of number from 1 to N
12th Sep 2021, 8:42 AM
Rahul Yadav
Rahul Yadav - avatar
+ 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.
16th Sep 2021, 1:50 PM
PBOL
+ 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
16th Sep 2021, 6:00 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
@ChaoticDawg I got it now! Thanks for the help! :)
18th Sep 2021, 3:27 PM
PBOL
- 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)
11th Sep 2021, 10:01 PM
elly paul
elly paul - avatar