C语言循环嵌套定义及程序举例

时间:2026-01-16

C语言循环嵌套定义及程序举例

第十二次 上机任务

循环的嵌套

一、循环的嵌套

1、含义:一个循环体内又包含另一个完整的循环结构称为循环的嵌套。内嵌的循环中还可以嵌套循环,这就是多层循环。

2、三种循环(while循环、do-while循环和for循环)可以互相嵌套。

3、形式:

下面几种都是合法的形式:

(1) while( ) (2) do (3) for(;;)

{… {… {

while( ) do for(;;)

{…} {… } {… } } while( ); }

} while( );

(4) while( ) (5) for(;;) (6) do

{… {… {…

do{…} while( ) for(;;){ }

while( ) { } …

{…} … }

} } while( )

1、输出如下图形:

******

******

******

******

2、输出九九乘法表

#include "stdio.h"

main()

{

int i,j,k;

for(i=1;i<=9;i++)

{

for(j=1;j<=i;j++)

{ * ** *** ****

C语言循环嵌套定义及程序举例

k=j*i;

printf("%d*%d=%d ",j,i,k);

}

printf("\n");

}

getch();

}

3、一百个铜钱买了一百只鸡,其中公鸡一只5钱、母鸡一只3钱,小鸡一钱3只,问一百只鸡中公鸡、母鸡、小鸡各多少)。 #include "stdio.h"

main()

{

int x,y,z;

for(x=1;x<=20;x++)

{

for(y=1;y<=33;y++)

{

for(z=3;z<=99;z+=3)

{

if((5*x+3*y+z/3==100)&&(x+y+z==100))/*是否满足百钱和百鸡的条件*/ printf("cock=%d,hen=%d,chicken=%d\n",x,y,z);

}

}

}

getch();

}

C语言循环嵌套定义及程序举例

例1:判断m是不是素数。

#include <stdio.h>

#include <math.h>

main()

{ int m,i,k;

scanf("%d",&m);

k=sqrt(m);

for (i=2;i<=k;i++)

if(m%i==0) break;

if(i>k)

printf("%d is a prime number\n",m);

else

printf("%d is not a prime number\n",m);

getch();

}

例2:把100~200之间的不能被3整除的数输出。

#include <stdio.h>

main()

{ int n;

for (n=100;n<=200;n++)

{

if (n%3==0)

continue;

printf("%d ",n);

}

getch(); }

1、 小红今年12岁,她父亲比她大20岁,编一程序,计算出她的父亲在几年后

比她年龄大一倍,到那时他们两人的年龄各为多少?

#include <stdio.h>

main()

{ int x,y,i;

x=12;

y=32;

i=0;

while(y!=2*x)

{

x++;

y++;

i++;

}

printf("%d年后爸爸的年龄是小红的2倍,此时小红的年龄为%d,爸爸的年龄为%d\n",i,x,y);

C语言循环嵌套定义及程序举例

getch();

}

2、

{ int a,n,s,p,i;

scanf("%d,%d",&a,&n);

s=a;

p=a;

for (i=1;i<n;i++)

{

p=p*10+a;

s=s+p;

}

printf("p=%d\n",p);

printf("s=%d",s);

getch();

}

3、译密码。为使电文保密,往往按一定规律将其转换成密码,收报人再按约定的规律将其译回原文。

思路:可以按以下规律将电文变成密码:

将字母A变成字母E,a变成e,即变成其后的第4个字母,W变成A,X变成B,Y变成C,Z变成D。

#include <stdio.h>

main()

{ char c;

while((c=getchar())!='\n')

{

if((c>='a'&& c<='z')||(c>='A' && c<='Z'))

{ c=c+4;

if (c>'Z'&& c<='Z'+4|| c>'z')

c=c-26;

}

printf("%c\n",c);

}

getch();

}

C语言循环嵌套定义及程序举例.doc 将本文的Word文档下载到电脑

    精彩图片

    热门精选

    大家正在看

    × 游客快捷下载通道(下载后可以自由复制和排版)

    限时特价:4.9 元/份 原价:20元

    支付方式:

    开通VIP包月会员 特价:19元/月

    注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
    微信:fanwen365 QQ:370150219