第一章:C语言简介
1.1 C语言的历史与发展
C语言由Dennis Ritchie在1972年发明,最初是为了编写Unix操作系统。自那时以来,C语言已经成为最流行的编程语言之一,广泛应用于系统编程、嵌入式系统、操作系统、游戏开发等领域。C语言以其高效、灵活和可移植性而闻名。
1.2 C语言的特点
- 高效性:C语言直接与硬件操作相关,因此执行速度快。
- 灵活性:C语言允许程序员直接访问内存,控制硬件资源。
- 可移植性:C语言编写的程序可以在不同的操作系统和硬件平台上运行。
第二章:C语言基础语法
2.1 数据类型
C语言中有以下基本数据类型:
int:有符号整数。float:单精度浮点数。double:双精度浮点数。char:字符。
2.2 变量和常量
变量是存储在内存中的数据,而常量是具有固定值的标识符。
int age = 25;
const float PI = 3.14159;
2.3 运算符
C语言中的运算符包括算术运算符、赋值运算符、比较运算符、逻辑运算符等。
int a = 5, b = 3;
int sum = a + b; // 算术运算符
int is_equal = (a == b); // 比较运算符
第三章:控制流
3.1 条件语句
条件语句用于根据条件执行不同的代码块。
if (age > 18) {
printf("你可以投票。\n");
} else {
printf("你还不能投票。\n");
}
3.2 循环语句
循环语句用于重复执行代码块。
for (int i = 0; i < 5; i++) {
printf("循环次数:%d\n", i);
}
3.3 跳转语句
跳转语句包括goto、break和continue。
int i = 0;
while (i < 10) {
if (i == 5) {
goto label;
}
printf("i的值:%d\n", i);
i++;
}
label:
printf("跳出循环。\n");
第四章:函数
4.1 函数定义
函数是执行特定任务的代码块。
void sayHello() {
printf("你好,世界!\n");
}
4.2 函数调用
函数调用是指执行函数中的代码。
sayHello(); // 调用函数
4.3 参数和返回值
函数可以接受参数,并返回值。
int add(int a, int b) {
return a + b;
}
int sum = add(3, 4); // 调用函数并接收返回值
第五章:实战案例
5.1 计算器程序
以下是一个简单的计算器程序,可以执行加、减、乘、除运算。
#include <stdio.h>
int main() {
int num1, num2;
char operator;
printf("请输入两个数字和一个运算符(+、-、*、/):");
scanf("%d %d %c", &num1, &num2, &operator);
switch (operator) {
case '+':
printf("结果是:%d\n", num1 + num2);
break;
case '-':
printf("结果是:%d\n", num1 - num2);
break;
case '*':
printf("结果是:%d\n", num1 * num2);
break;
case '/':
if (num2 != 0) {
printf("结果是:%f\n", (float)num1 / num2);
} else {
printf("除数不能为0。\n");
}
break;
default:
printf("无效的运算符。\n");
}
return 0;
}
5.2 简单的图书管理系统
以下是一个简单的图书管理系统,可以添加、删除和查找图书。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char title[100];
char author[100];
int year;
} Book;
Book library[100];
int bookCount = 0;
void addBook(const char *title, const char *author, int year) {
if (bookCount < 100) {
strcpy(library[bookCount].title, title);
strcpy(library[bookCount].author, author);
library[bookCount].year = year;
bookCount++;
} else {
printf("图书库已满。\n");
}
}
void deleteBook(const char *title) {
int i;
for (i = 0; i < bookCount; i++) {
if (strcmp(library[i].title, title) == 0) {
break;
}
}
if (i < bookCount) {
for (; i < bookCount - 1; i++) {
library[i] = library[i + 1];
}
bookCount--;
printf("图书已删除。\n");
} else {
printf("未找到该图书。\n");
}
}
void findBook(const char *title) {
int i;
for (i = 0; i < bookCount; i++) {
if (strcmp(library[i].title, title) == 0) {
printf("找到图书:%s\n", library[i].title);
return;
}
}
printf("未找到该图书。\n");
}
int main() {
// 添加图书
addBook("C程序设计语言", "Kernighan & Ritchie", 1978);
addBook("算法导论", "Thomas H. Cormen", 1990);
// 查找图书
findBook("C程序设计语言");
// 删除图书
deleteBook("C程序设计语言");
return 0;
}
通过以上实战案例,你可以进一步了解C语言编程的基础知识和应用场景。希望这些教程能帮助你轻松入门C语言编程。
