循环控制结构的应用(乘法口诀、判断闰年和输出素数)
一、乘法口诀
1.代码片:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0;
int n=0;
printf("请输入乘法口诀的大小:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
int j=0;
for(j=1;j<=i;j++)
{
printf("%-2d*%-2d=%-5d",i,j,i*j);
}
printf("\n");
}
system("pause");
return 0;
}
(2)运行结果:
二、输出1000–2000之间的闰年
(1)什么是闰年?
满足下列条件中的其中一个就是润年:
1.能被四整除而不能被100整除;
2.能被400整除。
(2)代码片
#include <stdio.h>
#include <stdlib.h>
int main()
{
int year;
int count=0;
for (year=1000;year<=2000;year++)
{
if (year%4==0 && year%100!=0)
{
printf("%d ",year);
count++;
}
else if (year%400==0)
{
printf("%d ",year);
count++;
}
/* if ((year%4==0) && (year%100!=0) || (year%400==0))
{
count++;
printf("%d ",year);
}*/
}
printf("\ncount=%d\n",count);
system("pause");
return 0;
}
(3)运行结果:
三、输出100–200之间的素数
(1)什么是素数?
素数,又称质数,一个大于1的整数,除了1和此数本身外,没法被其他自然数整除的数即为素数。换句话说,只有两个正因数(1和自己)的自然数即为素数。
(2)代码片
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0;
int count=0;
for (i=101;i<=200;i+=2)
{
int j=0;
for (j=2;j<=sqrt(i);j++)
{
if (i%j==0)
break;
}
if (j>sqrt(i))
{
printf("%d\n",i);
count++;
}
}
printf("\ncount=%d\n",count);
system("pause");
return 0;
}
(3)运行结果: