C语言学习系列十二——循环结构程序设计

 循环程序实现要点

  • 哪些操作需要反复执行——循环体
  • 在什么情况下执行——循环控制条件

  三种循环语句 

  • for语句(实现给定了循环次数)
  • while
  • do while(先经循环体运算一次)
例4-8-1
#include
int main()
{
	int i,mark,max,n;
	
	printf("Enter n:" );
	scanf("%d",&n);
	printf("Enter %d marks",n);
	scanf("%d" , &mark);
	max=mark;
	
	for(i=1; i
例4-8-2
#include
int main()
{
	int mark,max;
	
	printf("Enter marks: ");
	scanf("% d",&mark);
	
	max=mark;
	
	while(mark>=0){
		if(max
例4-9
#include
int main()
{
	int x;
	
	printf("Enter x:");
	scanf("%d",&x);
	while(x !=0){
		printf("%d",x%10);
		x=x/10; 
	} 
	
	return 0;
}
Enter x:12345
54321
例4-10
#include
#include
int main()
{
	int count,i,m,n;
	
	count=0;
	for(m=2; m<=100;m++){
		n=sqrt(m);
		for(i=2; i<=n; i++)
		if(m%i==0)             //如果m是素数 
		break;
		
	if(i>n){
		printf("%6d",m);
		count++;
		if(count%10==0)
			printf("\n");
			
	}

	}
	printf("\n");
	
	return 0;
	
 } 
     2     3     5     7    11    13    17    19    23    29
    31    37    41    43    47    53    59    61    67    71
    73    79    83    89    97
例4-11
#include
int main()
{
	int i,x1,x2,x;
	
	
	x1=1;
	x2=1;
	printf("%6d%6d",x1,x2);
	for(i=1; i<=8; i++){
		x=x1+x2;
		printf("%6d",x);
		x1=x2;
		x2=x; 
	}
	
	printf("\n");
	
	return 0;
}

     1     1     2     3     5     8    13    21    34    55
例4-12
#include
int main()
{
	
	int child,men,women;
	
	for(men=0; men<=45; men++)
	 for(women=0;women<=45;women++)
	 	for(child=0;child<=45;child++)
	 		if(men+women+child==45&&men*3+women*2+child*0.5==45)
	 			printf("men=%d,women=%d,child=%d\n",men,women,child);
	 			
	 			
	return 0;
}
men=0,women=15,child=30
men=3,women=10,child=32
men=6,women=5,child=34
men=9,women=0,child=36

或者是
#include
int main()
{
	
	int child,men,women;
	
	for(men=0; men<=15; men++)
	 for(women=0;women<=22;women++){ 
	 	child=45-women-men;
	 	for(child=0;child<=45;child++)
	 		if(men+women+child==45&&men*3+women*2+child*0.5==45)
	 			printf("men=%d,women=%d,child=%d\n",men,women,child);
	 		} 
	 			
	 			
	return 0;
} 
men=0,women=15,child=30
men=3,women=10,child=32
men=6,women=5,child=34
men=9,women=0,child=36

 

你可能感兴趣的:(C语言)