请写出C语言下包含字符串比较、循环、分支(含switch)、函数调用、递归、指针、结构、链表等的例子程序sample.c
时间: 2023-09-16 09:16:20 浏览: 87
以下是一个简单的示例程序,演示了C语言中字符串比较、循环、分支(含switch)、函数调用、递归、指针、结构、链表等的使用:
```
#include <stdio.h>
#include <string.h>
// 定义一个结构体表示链表节点
struct Node {
int value;
struct Node* next;
};
// 递归函数,计算阶乘
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
// 字符串比较
char str1[] = "hello";
char str2[] = "world";
if (strcmp(str1, str2) < 0) {
printf("%s comes before %s\n", str1, str2);
} else if (strcmp(str1, str2) > 0) {
printf("%s comes after %s\n", str1, str2);
} else {
printf("%s is the same as %s\n", str1, str2);
}
// 循环和分支
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
sum += i;
}
}
printf("The sum of even numbers from 1 to 10 is %d\n", sum);
// switch语句
int dayOfWeek = 2;
switch (dayOfWeek) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Weekend\n");
break;
}
// 函数调用
int n = 5;
int fact = factorial(n);
printf("%d! = %d\n", n, fact);
// 指针
int x = 10;
int* ptr = &x;
printf("The value of x is %d\n", x);
printf("The value of x through a pointer is %d\n", *ptr);
// 结构体
struct Node node1 = { 1, NULL };
struct Node node2 = { 2, NULL };
node1.next = &node2;
printf("The value of the first node is %d\n", node1.value);
printf("The value of the second node is %d\n", node1.next->value);
// 链表
struct Node* head = &node1;
struct Node* tail = &node2;
for (int i = 3; i <= 5; i++) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->value = i;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
printf("The values of the nodes in the list are: ");
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
return 0;
}
```
阅读全文