C Primer Plus 6
一、C控制语句---循环
1、编程练习
(1)嵌套循环,打印字符。
#include<stdio.h>
int main(void)
{
int i,j;
for(i = 1;i<=5;i++){
for(j = 0;j<i;j++)
printf("$");
printf("\n");
}
getchar();
return 0;
}
(2)使用嵌套循环,按照递增格式打印字母
#include<stdio.h>
int main(void)
{
int i,j;
char c;
for (i = 1;i<=6;i++)
{
for(j = 0,c='F';j<i;j++,c--)
printf("%c",c);
printf("\n");
}
getchar();
return 0;
}
(3)嵌套循环打印字母
#include<stdio.h>
int main(void)
{
int i,j;
char c = 'A';
for(i=1;i<=6;i++)
{
for(j = 0;j<i;j++,c++)
printf("%c",c);
printf("\n");
}
getchar();
return 0;
}
(4)打印整数,平方,立方
#include<stdio.h>
int main(void)
{
int start,end;
printf("Please enter the start number:\n");
scanf("%d",&start);
printf("Please enter the end number:\n");
scanf("%d",&end);
printf(" ori: square: cubic:\n");
for(int i=start;i<=end;i++)
{
printf("%6d,%10d,%10d",i,i*i,i*i*i);
printf("\n");
}
getchar();
return 0;
}
(5)编写一个程序,单词读入字符数组中,倒叙打印单词。
#include<stdio.h>
#include<string.h>
#include<windows.h>
int main(void)
{
char word[30];
printf("Please enter the words:\n");
scanf("%s",&word);
printf("The word your enter is:%s\n",word);
printf("The reverse word you enter is:");
printf("%d\n",strlen(word));
for (int i=strlen(word)-1;i>=0;i--)
{
printf("%c",word[i]);
}
system("pause");
return 0 ;
}
(6)输入两个浮点数,进行相关计算。
#include<stdio.h>
int main(void)
{
float x,y;
printf("Please enter the two float data(seprate by blank):");
while(scanf("%f %f",&x,&y)==2)
{
printf("The answer is %f\n",(x-y)/(x*y));
printf("Please enter the two float data(seprate by blank:)");
}
printf("The program end!\n");
getchar();
return 0;
}
(7)将上题用函数实现
#include<stdio.h>
float calc(float x,float y);
int main(void)
{
float x,y;
printf("Please enter the two float data(seprate by blank):");
while(scanf("%f %f",&x,&y)==2)
{
printf("The answer is:%f\n",calc(x,y));
printf("Please enter the two float data(seprate by blank):");
}
printf("The program end!\n");
getchar();
return 0;
}
float calc(float x,float y)
{
float result;
result = (x-y)/(x*y);
return result;
}
(8)编写程序,创建一个包含8个元素的int类型数组,分别把数组元素设为2的前8次幂,使用for循环设置数组元素的值,使用do—while循环显示数组元素的值。
#include<stdio.h>
int main(void)
{
int data[8];
data[0] = 2;
for(int i = 1;i<8;i++)
{
data[i] = data[i-1]*2;
}
int i = 0;
do{
printf("%d",data[i++]);
}while(i<8);
printf("\nDone!\n");
getchar();
return 0;
}