引言
C语言的一些基本例题 全部例题来自于C语言王道训练营 链接如下
B站链接. 书籍:《跟“龙哥”学C语言编程》
1.一维数组的存储及函数传递
下面展示一些 可运行的代码 。
#include<stdio.h>
#include<stdlib.h>
#define N 5
void print(int b[], int len)
{
int i;
for (int i = 0; i < len; i++)
{
printf("%-3d", b[i]);
}
b[4] = 20;
printf("\n");
}
int main()
{
int j = 10;
int a[N] = { 1,2,3,4,5 };
int i = 3;
a[5] = 20;
a[6] = 21;
a[7] = 22;
print(a, N);
printf("a[4]=%d\n", a[4]);
system("pause");
}
运行结果
1 2 3 4 5
a[4]=20
请按任意键继续. . .
2.二维数组的存储与传递
下面展示一些 可运行的代码 。
#include<stdio.h>
#include<stdlib.h>
void print(int b[][4],int row)
{
int i, j;
for (int i = 0; i < row;i++)
{
for (j = 0; j < sizeof(b[0]) / sizeof(int); j++)
{
printf("b[%d][%d]=%-3d",i,j,b[i][j]);
}
printf("\n");
}
b[2][3] = 999;
printf("+++++++++输出完成+++++++++++\n");
}
int main()
{
int a[][4] = { 1,3,5,7,2,4,6,8,9,11,13,15 };
float b[4] = { 1,2,3,4 };
int c[3][4] = { {1},{5,9} };
print(a, 3);
print(c, 3);
printf("a[2][3]=%d\n", a[2][3]);
system("pause");
return 0;
}
运行结果
b[0][0]=1 b[0][1]=3 b[0][2]=5 b[0][3]=7
b[1][0]=2 b[1][1]=4 b[1][2]=6 b[1][3]=8
b[2][0]=9 b[2][1]=11 b[2][2]=13 b[2][3]=15
+++++++++输出完成+++++++++++
b[0][0]=1 b[0][1]=0 b[0][2]=0 b[0][3]=0
b[1][0]=5 b[1][1]=9 b[1][2]=0 b[1][3]=0
b[2][0]=0 b[2][1]=0 b[2][2]=0 b[2][3]=0
+++++++++输出完成+++++++++++
a[2][3]=999
请按任意键继续. . .
3.字符数组初始化及传递
下面展示一些 可运行的代码 。
#include<stdio.h>
#include<stdlib.h>
void print(char c[])
{
int i = 0;
while (c[i])
{
printf("%c", c[i]);
i++ ;
}
printf("\n");
}
int main()
{
char c[5] = { 'h','e','l','l','o'};
char d[5] = "how";
char a[20];
char b[20];
printf("%s----%s\n", c, d);
gets(b);
puts(b);
scanf("%s%s", c, d);
print(c);
print(d);
scanf("%s", a);
printf("a=%s\n", a);
system("pause");
return 0;
}
运行结果
hello烫烫烫蘃?----how
how are you
how are you
hello world
hello
world
The King and the Pharaoh
a=The
请按任意键继续. . .
4.str系列字符串操作函数的使用
下面展示一些 可运行的代码 。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int mystrlen(char c[])
{
int i = 0;
while (c[i++]);
return i - 1;
}
int main()
{
int len;
char c[20];
char d[100] = "world";
while (gets(c) != NULL)
{
puts(c);
len = strlen(c);
printf("len=%d\n", len);
len = mystrlen(c);
printf("mylen=%d\n", len);
strcat(c, d);
puts(c);
strcpy(d, c);
puts(d);
printf("c&d=%d\n",strcmp(c, d));
}
system("pause");
return 0;
}
运行结果
hello
hello
len=5
mylen=5
helloworld
helloworld
c&d=0
^Z
请按任意键继续. . .
5.mem系列操作函数
下面展示一些 可运行的代码 。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int a[5] = { 1,2,3,4,5 };
int b[5];
int i;
memcpy(b, a, sizeof(a));
for (i = 0; i < 5; i++)
{
printf("%-3d", b[i]);
}
printf("\n");
system("pause");
return 0;
}
运行结果
1 2 3 4 5
请按任意键继续. . .
总结
第一次发表一篇完整的博客,对于一些遗漏,读者不要太过深究~ 比较适合新手打基础大佬请绕路~ 希望这些可以帮助你更好的理解C语言 马上就考研了 我居然还在纠结一些基础 真是闲的闲的闲的闲*10000! 过几天在更新后几章的内容 欢迎大家评论、收藏、点赞 !!!
|