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:
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:
sum
It must be initialized when defining, otherwise thesum += i
final 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!