sumOfOneToN(int n)
{
if(n <= 1)
return n;
else
return( n + sumOfOneToN( n - 1 ) );
}
Numbers from 1 to n can be summed up in Perl using the code below: BEGIN { $/ = "n"; $ = "n"; } LINE: while (defined($_ = )) { chomp $_; $sum += $_; } sub END { print $sum; } -e syntax OK
to print the sum of first ten numbers:- void main() {int i,sum; sum=0; while(i<=10) sum=sum+i; i=i+1; } printf("The sum is : %d",sum); }
int sum = 0; int i; for(i = 0; i < n; ++i) { sum += i; }
1. Design an algorithm to compute sum of the squares of n numbers?
Sum = n/2[2Xa1+(n-1)d] where n is last number, a1 is the first number & d is the common difference between the numbers, here d=2 for the even /odd numbers. Sum = n/2 [2Xa1+(n-1)2]
#include #define NUM 100 //since prog is to be written for adding 100 naturalint main(){int i,sum=0;for(i=1;i
If you want to sum up numbers 1 to N, you can do it this way. Sum = (N+1)*(N/2).The reason this works: say you want to sum up 1 through 10. You have 10+1, 9+2, ..., 6+5. Each of these equals 11 [N+1]. You added 11 five times (N/2). Sum of 1 to 102 = (102+1)*(102/2) = 103*51 = 5253. You can check it by summing up the numbers with a spreadsheet.
let the three numbers be: n-1, n, n+1 their sum is equal to 3n 468=3n which means that n=156 the three numbers are 155, 156, 157
The sum of the first n cubed numbers is: [n*(n+1)/2]2 which is the same as the square of the sum of the first n numbers.
Sum of first n numbers = n/2(n +1) = 500 x 1001 = 500500
The sum of the first "n" numbers is equal to n(n+1)/2.
to print the sum of first ten numbers:- void main() {int i,sum; sum=0; while(i<=10) sum=sum+i; i=i+1; } printf("The sum is : %d",sum); }
The sum of a sequence is given by sum = n/2(2a + (n-1)d) where: n = how many a = first number of sequence d = difference between terms of sequence. For the first 22 odd numbers these are: n = 22 a = 1 d = 2 → sum = 22/2(2×1 + (22 - 1)×2)) = 22² = 484 The sum of the first n odd numbers is always n²: sum = n/2(2×1 + (n-1)2) = n/2(1 + (n-1))×2 = n(n) = n²
To sum numbers 1 through N, use this formula: (1 + N)*N/2, so (1+35)*35/2 = 630.
n*(n+1)=sum 100*(100+1)=10100
int sum = 0; int i; for(i = 0; i < n; ++i) { sum += i; }
Sum of first n natural numbers is (n) x (n + 1)/2 Here we have the sum = 100 x (101)/2 = 50 x 101 = 5050
1. Design an algorithm to compute sum of the squares of n numbers?