The C language while loop realizes the sum of 1~100 and its expansion (a must-see for college students)

Use while loop to calculate the sum from 1 to 100 

#include<stdio.h>
int main(){
//	用while循环 计算从1~100的和 
	int sum=0,i=1;
	while(i<=100){
		sum+=i;
		i++;
	}
	printf("1到100的和是:%d",sum);
	return 0;
}

The above code uses a while loop to control the loop by controlling the variable i

If we change the auto-increment rule of i++ to i+=2

Then the result of the whole program becomes to calculate the sum of odd numbers from 1 to 100

code show as below

#include<stdio.h>
int main(){
//	用while循环 计算从1~100的奇数和 
	int sum=0,i=1;
	while(i<=100){
		sum+=i;
		i+=2;
	}
	printf("1到100的奇数和是:%d",sum);
	return 0;
}

In the same way, the circular operation of the product can also be realized

code show as below

#include<stdio.h>
int main(){
//	用while循环 计算从1~10的乘积 
	int res=1,i=1;
	while(i<=10){
		res*=i;
		i++;
	}
	printf("1到10的乘积是:%d",res);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_63987141/article/details/129127150