C语言作为一种历史悠久且广泛使用的编程语言,它的语法简洁、执行效率高,因此非常适合初学者学习和使用。本篇文章将带领大家通过50个经典实例,逐步深入学习C语言编程,并通过实战来提升编程技能。
实例1:Hello World程序
C语言的入门通常从编写“Hello World”程序开始。这是一个简单的程序,用于输出“Hello, World!”到控制台。
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
实例2:变量和常量
在C语言中,变量用于存储数据,常量则是固定不变的值。
#include <stdio.h>
int main() {
int age = 25; // 整数变量
float pi = 3.14; // 浮点变量
const char name[] = "John"; // 字符串常量
return 0;
}
实例3:数据类型转换
当进行数学运算时,可能会遇到不同数据类型之间的转换。
#include <stdio.h>
int main() {
int num = 5;
float result = num + 3.5f; // 自动转换为浮点数
printf("Result: %f\n", result);
return 0;
}
实例4:条件语句
使用if语句进行条件判断。
#include <stdio.h>
int main() {
int number = 10;
if (number > 5) {
printf("Number is greater than 5\n");
} else {
printf("Number is not greater than 5\n");
}
return 0;
}
实例5:循环结构
循环结构用于重复执行某段代码。
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Loop number: %d\n", i);
}
return 0;
}
实例6:函数定义与调用
函数是C语言中的基本组成部分,用于组织代码并提高可重用性。
#include <stdio.h>
void printMessage() {
printf("This is a function.\n");
}
int main() {
printMessage();
return 0;
}
实例7:数组操作
数组是一组具有相同数据类型的元素集合。
#include <stdio.h>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("Array element: %d\n", numbers[i]);
}
return 0;
}
实例8:指针简介
指针是C语言中非常重要的概念,用于存储和访问内存地址。
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a; // ptr指向变量a的地址
printf("Value of a: %d\n", *ptr); // 通过指针访问a的值
return 0;
}
实例9:结构体定义与使用
结构体用于组合多个不同数据类型的元素。
#include <stdio.h>
typedef struct {
char name[50];
int age;
} Person;
int main() {
Person p1;
strcpy(p1.name, "John");
p1.age = 25;
printf("Name: %s, Age: %d\n", p1.name, p1.age);
return 0;
}
实例10:函数指针
函数指针是指向函数的指针,可以用来调用函数。
#include <stdio.h>
void sayHello() {
printf("Hello, World!\n");
}
int main() {
void (*funcPtr)() = sayHello;
funcPtr(); // 通过函数指针调用函数
return 0;
}
实例11:动态内存分配
使用malloc和free函数进行动态内存分配。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(10 * sizeof(int)); // 分配10个整数的内存空间
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < 10; i++) {
ptr[i] = i;
}
for (int i = 0; i < 10; i++) {
printf("Array element: %d\n", ptr[i]);
}
free(ptr); // 释放分配的内存
return 0;
}
实例12:文件操作
使用fopen、fclose、fputs和fgets函数进行文件操作。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w"); // 打开文件进行写入
if (file == NULL) {
printf("File opening failed\n");
return 1;
}
fputs("Hello, World!\n", file); // 写入内容
fclose(file); // 关闭文件
file = fopen("example.txt", "r"); // 打开文件进行读取
if (file == NULL) {
printf("File opening failed\n");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), file)) {
printf("%s", buffer); // 读取内容并输出
}
fclose(file); // 关闭文件
return 0;
}
实例13:字符串处理
使用strlen、strcpy、strcat和strcmp函数进行字符串操作。
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char str3[50];
strcpy(str3, str1); // 复制字符串
strcat(str3, str2); // 连接字符串
printf("Result: %s\n", str3); // 输出结果
return 0;
}
实例14:位运算
使用位运算符进行位操作。
#include <stdio.h>
int main() {
int a = 5; // 101
int b = 3; // 011
printf("AND: %d\n", a & b); // 001
printf("OR: %d\n", a | b); // 111
printf("XOR: %d\n", a ^ b); // 110
printf("NOT: %d\n", ~a); // 110
return 0;
}
实例15:结构体数组和指针
使用结构体数组和指针进行操作。
#include <stdio.h>
typedef struct {
int id;
char name[50];
} Student;
int main() {
Student students[3] = {
{1, "John"},
{2, "Jane"},
{3, "Bob"}
};
Student *ptr = &students[0]; // 指向结构体数组的首元素
for (int i = 0; i < 3; i++) {
printf("ID: %d, Name: %s\n", ptr[i].id, ptr[i].name);
}
return 0;
}
实例16:递归函数
递归函数用于重复调用自身,实现循环逻辑。
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int number = 5;
printf("Factorial of %d: %d\n", number, factorial(number));
return 0;
}
实例17:链表操作
链表是一种动态数据结构,用于存储元素序列。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void insertAtHead(Node **head, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void freeList(Node *head) {
Node *current = head;
while (current != NULL) {
Node *next = current->next;
free(current);
current = next;
}
}
int main() {
Node *head = NULL;
insertAtHead(&head, 3);
insertAtHead(&head, 2);
insertAtHead(&head, 1);
printList(head);
freeList(head);
return 0;
}
实例18:队列操作
队列是一种先进先出(FIFO)的数据结构。
#include <stdio.h>
#include <stdlib.h>
typedef struct Queue {
int front;
int rear;
int size;
int *items;
} Queue;
Queue *createQueue(int capacity) {
Queue *queue = (Queue *)malloc(sizeof(Queue));
queue->front = 0;
queue->rear = -1;
queue->size = capacity;
queue->items = (int *)malloc(queue->size * sizeof(int));
return queue;
}
void enqueue(Queue *queue, int item) {
if ((queue->rear + 1) % queue->size == queue->front) {
printf("Queue is full\n");
return;
}
queue->rear = (queue->rear + 1) % queue->size;
queue->items[queue->rear] = item;
}
int dequeue(Queue *queue) {
if (queue->front == queue->rear) {
printf("Queue is empty\n");
return -1;
}
int item = queue->items[queue->front];
queue->front = (queue->front + 1) % queue->size;
return item;
}
void freeQueue(Queue *queue) {
free(queue->items);
free(queue);
}
int main() {
Queue *queue = createQueue(5);
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
printf("Dequeued: %d\n", dequeue(queue));
printf("Dequeued: %d\n", dequeue(queue));
freeQueue(queue);
return 0;
}
实例19:栈操作
栈是一种后进先出(LIFO)的数据结构。
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack {
int top;
int size;
int *items;
} Stack;
Stack *createStack(int capacity) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->top = -1;
stack->size = capacity;
stack->items = (int *)malloc(stack->size * sizeof(int));
return stack;
}
void push(Stack *stack, int item) {
if (stack->top == stack->size - 1) {
printf("Stack is full\n");
return;
}
stack->top++;
stack->items[stack->top] = item;
}
int pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty\n");
return -1;
}
int item = stack->items[stack->top];
stack->top--;
return item;
}
void freeStack(Stack *stack) {
free(stack->items);
free(stack);
}
int main() {
Stack *stack = createStack(5);
push(stack, 1);
push(stack, 2);
push(stack, 3);
printf("Popped: %d\n", pop(stack));
printf("Popped: %d\n", pop(stack));
freeStack(stack);
return 0;
}
实例20:二叉树遍历
二叉树是一种常用的数据结构,用于存储具有父子关系的元素。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *left;
struct Node *right;
} Node;
Node *createNode(int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void preOrder(Node *root) {
if (root != NULL) {
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(Node *root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}
void postOrder(Node *root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->data);
}
}
void freeTree(Node *root) {
if (root != NULL) {
freeTree(root->left);
freeTree(root->right);
free(root);
}
}
int main() {
Node *root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Pre-order traversal: ");
preOrder(root);
printf("\n");
printf("In-order traversal: ");
inOrder(root);
printf("\n");
printf("Post-order traversal: ");
postOrder(root);
printf("\n");
freeTree(root);
return 0;
}
实例21:动态规划
动态规划是一种用于求解复杂问题的算法思想。
#include <stdio.h>
int lcs(char *X, char *Y) {
int m = strlen(X);
int n = strlen(Y);
int L[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
L[i][j] = 0;
} else if (X[i - 1] == Y[j - 1]) {
L[i][j] = L[i - 1][j - 1] + 1;
} else {
L[i][j] = (L[i - 1][j] > L[i][j - 1]) ? L[i - 1][j] : L[i][j - 1];
}
}
}
return L[m][n];
}
int main() {
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";
printf("Length of LCS is %d\n", lcs(X, Y));
return 0;
}
实例22:图算法
图是一种用于表示对象及其关系的抽象数据结构。
#include <stdio.h>
#include <stdlib.h>
typedef struct Graph {
int numVertices;
int **edges;
} Graph;
Graph *createGraph(int numVertices) {
Graph *graph = (Graph *)malloc(sizeof(Graph));
graph->numVertices = numVertices;
graph->edges = (int **)malloc(numVertices * sizeof(int *));
for (int i = 0; i < numVertices; i++) {
graph->edges[i] = (int *)malloc(numVertices * sizeof(int));
for (int j = 0; j < numVertices; j++) {
graph->edges[i][j] = 0;
}
}
return graph;
}
void addEdge(Graph *graph, int src, int dest) {
graph->edges[src][dest] = 1;
graph->edges[dest][src] = 1; // 无向图
}
void freeGraph(Graph *graph) {
for (int i = 0; i < graph->numVertices; i++) {
free(graph->edges[i]);
}
free(graph->edges);
free(graph);
}
void printGraph(Graph *graph) {
for (int i = 0; i < graph->numVertices; i++) {
for (int j = 0; j < graph->numVertices; j++) {
printf("%d ", graph->edges[i][j]);
}
printf("\n");
}
}
int main() {
int numVertices = 4;
Graph *graph = createGraph(numVertices);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printGraph(graph);
freeGraph(graph);
return 0;
}
实例23:排序算法
排序算法用于将一组元素按照特定顺序排列。
”`c
#include
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i <
