版权声明:转载请注明 https://blog.csdn.net/qq_34720818/article/details/86666217
循环结构程序设计
前言
在计算机解决实际问题时,往往需要重读执行特定的一系列步骤或操作,就要用到循环结构。需要执行的一系列操作的次数,有的是事先知道的,称为计数器控制的循环;有的是事先不知道的,由特定条件来控制,称为条件控制的循环。
1、基础知识
2、示例代码
1、while循环
//从键盘上输入一个整数,输出该数字的位数
int num,i=0;
printf("please input a number\n");
scanf("%d",&num);
while(num%10!=0)
{
i++;
num=num/10;
printf("the number,missing a last bite,is : %d",num);
printf("\n");
}
printf("the number bite is : %d\n",i);
2、do-while循环和for循环
//输入一批学生成绩,计算其平均值,并统计不及格的人数
int score[100],i,j=0,sum=0,flag=0;
float avarage=0;
printf("are you continue to put student's score,which input else num if you don't continue and input -1 \n");
do
{
printf("please input student's score\n");
scanf("%d",&score[j]);
i=score[j];
j++;
}while(i!=-1);
j--;
printf("put student's score are the follows:\n");
for(int k=0;k<j;k++)
{
printf("%d ",score[k]);
sum+=score[k];
if(score[k]<60)
flag++;
}
printf("\n");
avarage=sum/j;
printf("put student's avarage of score is : %f, all students are %d and score<60 have %d 人\n",avarage,j,flag);
3、break和continue
//求1-10的偶数项之和
int sum=0;
for(int i=0;i<20;i++)
{
if(i%2!=0)
continue//结束本次循环
if(i>10)
break;//结束整个循环
sum+=i;
}
printf("the sum of even number is %d\n",sum);
4、goto语句
//goto语句称为无条件转向语句
int i=0;
flag:printf("please perform the task1\n");
printf("please perform the task2\n");
if(i<1)
{
i++;
goto flag;
}
5、嵌套循环
//输出100-200之间的所有素数
printf("printf the 素数 all of the number from 100 to 200\n");
int num=0;
for(int i=100;i<=200;i++)
{
for(int j=2;j<=i-1;j++)
if(i%j==0)
break;
if(j==i)
printf("%d ",i);
}
printf("\n");