Calculate the sum of the numbers from 1 to 100
Threads: Calculate the sum of the numbers from 1 to 100
Hello everyone, if the total 2 numbers a and b, it is quite simply the then, however, to calculate the total number of consecutive multiple threads all we like how? We found that the nature of the numbers 1 to 100 is continuous, we can use loop to do this.
/* * Calculate sum of number from 1 to 100 */ #include <stdio.h> int main() { int i; int sum = 0; for(i = 1; i <= 100; i++) { sum = sum + i; } printf("sum = %d\n", sum); return 0; }
All pretty simple is not it! However if you look closely, you can remember anymore summing consecutive numbers using the arithmetic formula.
The formula sums the following arithmetic sequence:
S = a1 + the2 + … + then = [n*(the1 + then)] / 2
So we can use this formula to calculate the total without resorting to loop again.
Exercise 1: Calculate the sum of the numbers from 1 to 500 without using the loop
Exercise 2: Calculate the sum of the numbers from 1 to n. N input from the keyboard
Exercise 3: Calculating the total 1² + 2² + 3² + … + 100².
Recent Comments