Experiment 2-3-1 Find the sum of 1 to 100 (10 points)

This question requires writing a program to calculate the value of the expression 1 + 2 + 3 +… + 100.

Input format:

There is no input for this question.

Output format:

Output in the following format:

sum = 累加和

Code:

# include <stdio.h>
# include <stdlib.h>

int main() {
    
    
    int sum = 0,i;
    for (i=1;i<=100;i++) {
    
    
        sum += i;
    }
    printf("sum = %d",sum);
    return 0;
}

Submit screenshot:

Insert picture description here

Problem-solving ideas:

This is actually just a simple exercise for just getting in touch with loops, but you need to pay attention to two points:

  • sumIt must be initialized when defining, otherwise the sum += ifinal result in the loop may be incorrect, or even an error may be reported directly
  • Pay attention to the start and end positions of the loop and the termination conditions. The boundary must be clarified, and the judgment conditions of the loop must be reasonable, otherwise it will be difficult to overcome an infinite loop!

Guess you like

Origin blog.csdn.net/weixin_43862765/article/details/114387848