引言:C语言,编程的基石
C语言,作为一门历史悠久且广泛应用的编程语言,一直是学习编程的首选。它以其简洁、高效和强大的功能,被广泛应用于操作系统、嵌入式系统、网络编程等领域。掌握C语言,不仅能够帮助你更好地理解编程原理,还能为后续学习其他编程语言打下坚实的基础。本文将为你带来100个经典C语言例题详解,助你轻松突破编程难题。
第一部分:基础语法与数据类型
例题1:变量定义与赋值
#include <stdio.h>
int main() {
int a = 10;
printf("a = %d\n", a);
return 0;
}
例题2:数据类型转换
#include <stdio.h>
int main() {
int a = 5;
float b = 3.14;
printf("a + b = %.2f\n", a + b);
return 0;
}
例题3:运算符的使用
#include <stdio.h>
int main() {
int a = 10, b = 5;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
return 0;
}
第二部分:控制结构
例题4:条件语句
#include <stdio.h>
int main() {
int a = 10;
if (a > 5) {
printf("a > 5\n");
} else {
printf("a <= 5\n");
}
return 0;
}
例题5:循环结构
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
第三部分:函数与数组
例题6:函数定义与调用
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int a = 10, b = 5;
printf("a + b = %d\n", add(a, b));
return 0;
}
例题7:二维数组的使用
#include <stdio.h>
int main() {
int arr[3][3];
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
arr[i][j] = i * 3 + j;
}
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
第四部分:指针与字符串
例题8:指针的使用
#include <stdio.h>
int main() {
int a = 10;
int *p = &a;
printf("a = %d, *p = %d\n", a, *p);
return 0;
}
例题9:字符串处理
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello, world!";
char str2[100];
strcpy(str2, str1);
printf("str1 = %s, str2 = %s\n", str1, str2);
return 0;
}
第五部分:结构体与文件操作
例题10:结构体定义与使用
#include <stdio.h>
struct Student {
char name[50];
int age;
float score;
};
int main() {
struct Student stu1;
strcpy(stu1.name, "Alice");
stu1.age = 20;
stu1.score = 90.5;
printf("Name: %s, Age: %d, Score: %.2f\n", stu1.name, stu1.age, stu1.score);
return 0;
}
例题11:文件操作
#include <stdio.h>
int main() {
FILE *fp;
char str[100];
fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("File not found!\n");
return 0;
}
while (fgets(str, sizeof(str), fp)) {
printf("%s", str);
}
fclose(fp);
return 0;
}
结语:C语言,编程之路的起点
通过以上100个经典C语言例题详解,相信你已经对C语言有了更深入的了解。掌握C语言,你将能够更好地应对各种编程难题。在今后的学习过程中,请不断积累经验,不断挑战自己,相信你会在编程的道路上越走越远。祝你好运!
