C语言for语句如何用来遍历? 在C语言中,for语句遍历数组、链表和其他数据结构时尤为重要。初始化、条件判断、递增/递减,在遍历过程中,这三部分构成了for语句的核心。下面将详细描述如何使用for语句进行遍历,并重点讲述如何通过条件判断控制循环。
一、遍历数组
数组是C语言中最常见的数据结构之一。我们通常通过for语句来遍历数组,并对每个元素进行操作。
1. 基本遍历
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
在这段代码中,初始化部分是int i = 0
,条件判断部分是i < n
,递增部分是i++
。通过这些部分的组合,for语句可以遍历数组中的每一个元素。
2. 遍历并修改数组元素
有时我们需要在遍历过程中修改数组的元素。通过for语句,我们可以轻松实现这一点。
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++) {
arr[i] *= 2; // 将每个元素乘以2
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
二、遍历链表
链表是一种更复杂的数据结构,使用for语句遍历链表需要更多的注意事项,尤其是在条件判断部分。
1. 单链表的遍历
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
for (; n != NULL; n = n->next) {
printf("%d ", n->data);
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printList(head);
return 0;
}
在这个示例中,for语句的条件判断部分n != NULL
确保了链表的遍历直到最后一个节点。
2. 双向链表的遍历
双向链表的遍历可以利用for语句的灵活性,从头到尾或从尾到头遍历。
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void printList(struct Node* n) {
struct Node* last;
printf("Forward Traversal:n");
for (; n != NULL; n = n->next) {
printf("%d ", n->data);
last = n;
}
printf("nBackward Traversal:n");
for (; last != NULL; last = last->prev) {
printf("%d ", last->data);
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
head->prev = NULL;
second->data = 2;
second->next = third;
second->prev = head;
third->data = 3;
third->next = NULL;
third->prev = second;
printList(head);
return 0;
}
三、遍历多维数组
多维数组的遍历通常需要嵌套for语句。每一层for语句对应一个维度。
1. 二维数组的遍历
#include <stdio.h>
int main() {
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("n");
}
return 0;
}
2. 三维数组的遍历
三维数组的遍历在二维数组的基础上增加了一层for语句。
#include <stdio.h>
int main() {
int arr[2][2][2] = {
{
{1, 2},
{3, 4}
},
{
{5, 6},
{7, 8}
}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", arr[i][j][k]);
}
printf("n");
}
printf("n");
}
return 0;
}
四、遍历字符串
字符串在C语言中本质上是一个字符数组。我们可以使用for语句遍历字符串中的每一个字符。
1. 基本字符串遍历
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
for (int i = 0; str[i] != '