- 1

C#: For the Loop 16.3 Help

I need some guidance for the problem below. Been stuck on it for about an hour now. The program you are given takes a positive number N as input. Complete the program to calculate the sum of all numbers from 1 to N inclusive. Sample Input 4 Sample Output 10

30th Jan 2022, 4:45 PM
Kenny Huynh
3 Answers
0
The sum from 1 to 4 is 1+2+3+4=10... So use a for from 1 to n+1..
30th Jan 2022, 6:20 PM
Cristian Baeza Jimenez
Cristian Baeza Jimenez - avatar
0
Or use a recursive method: int Sum(int N){ if(N <= 1){ return 1; } return N + Sum(N - 1); }
30th Jan 2022, 11:44 PM
khabz01
khabz01 - avatar
0
Or use the Gauss method n*(n+1)/2....with your example 4*(4+1)/2=10
31st Jan 2022, 3:06 AM
Cristian Baeza Jimenez
Cristian Baeza Jimenez - avatar