The sum of 1 to 100 is required for the basic tutorial of C language

  • 2020-05-30 20:50:42
  • OfStack

Problem: find 1+2+3+... + 98 + 99 + 100
(1) solve by mathematical method
(2) write C language program for solution

Solution:
(1) mathematical methods


S = 1+2+3+ ... +98+99+100
 = (1+100) + (2+99) + (3+98) +  ...  + (49+52) + (50+51)
 = 101 * 50
 = 5050

(2) C language programming


#include <stdio.h>

int main()
{
  int sum = 0; //  initialise 
  for(int i = 1; i <= 100; i++)
  {
    sum = sum + i;
  }
  
  printf("total is %d\n", sum);
}

Operation results:

total is 5050

Analysis:
(1) the first cycle

i = 1, sum = sum + i = 0 + 1 = 1, here the value of sum on the right is 0, after assigning 1 to sum on the left, the latest value of sum becomes 1

(2) the second cycle

i = 2, sum = sum + i = 1 + 2 = 3, the value of sum on the right here has been changed to 1 by the previous step. After assigning 3 to sum on the left, the latest value of sum

Is 3

(3) the third cycle

i = 3, sum = sum + i = 3 + 3 = 6, the value of sum on the right here has been changed to 3 by the previous step. After assigning the calculated value of 6 to sum on the left, the latest value of sum becomes 6

(4) the fourth cycle

i = 4, sum = sum + i = 6 + 4 = 10, and the value of sum on the right here has been changed to 6 by the previous step. After assigning the calculated value of 10 to sum on the left, the latest value of sum becomes 10

(5)...... After doing this 100 times, you get 5050

New knowledge:

sum = sum + i can be written as sum += i, either by adding sum and i and assigning the new value to sum.
Use += for future programming.
Reason: the C language is compiled by the compiler, and the two methods are completely equivalent if the compiler does not turn on optimization. When the compiler turns on optimization, += will probably execute 1 point faster. (a little impression of this first, do not need to know in depth)

Homework:
(1) debug the above program. Each time you run to the close curly brace, hover the mouse over sum and observe the value of sum.
The above program will loop 100 times, when debugging, loop about 10 times to step out.

(2)
Change sum = sum + i to sum += i, and run the result


#include <stdio.h>

int main()
{
  int sum = 0; //  initialise 
  for(int i = 1; i <= 100; i++)
  {
    sum += i;
  }
  
  printf("total is %d\n", sum);
}

(3) write the program by heart on a piece of paper.


Related articles: