参考资料

  1. 简单c语言程序代码
  2. c语言代码最简单
  3. c语言基础知识入门代码
  4. c语言基础知识入门书籍推荐
  5. C语言代码格式化工具 有哪些
  6. c语言简单编程代码入门
  7. C++代码格式化工具 有哪些
  8. c语言基础知识入门自学

C语言基础知识入门代码

1. Hello World程序

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

2. 变量和数据类型

#include <stdio.h>

int main() {
    // 基本数据类型
    int age = 25;
    float height = 1.75f;
    double weight = 68.5;
    char grade = 'A';
    
    printf("Age: %d\n", age);
    printf("Height: %.2f meters\n", height);
    printf("Weight: %.1f kg\n", weight);
    printf("Grade: %c\n", grade);
    
    return 0;
}

3. 运算符

#include <stdio.h>

int main() {
    int a = 10, b = 3;
    
    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 num = 10;
    
    // if-else语句
    if (num > 0) {
        printf("Number is positive\n");
    } else if (num < 0) {
        printf("Number is negative\n");
    } else {
        printf("Number is zero\n");
    }
    
    // switch语句
    switch(num) {
        case 0:
            printf("Zero\n");
            break;
        case 10:
            printf("Ten\n");
            break;
        default:
            printf("Other number\n");
    }
    
    return 0;
}

5. 循环结构

#include <stdio.h>

int main() {
    // for循环
    printf("For loop:\n");
    for(int i = 0; i < 5; i++) {
        printf("%d ", i);
    }
    printf("\n");
    
    // while循环
    printf("While loop:\n");
    int j = 0;
    while(j < 5) {
        printf("%d ", j);
        j++;
    }
    printf("\n");
    
    // do-while循环
    printf("Do-while loop:\n");
    int k = 0;
    do {
        printf("%d ", k);
        k++;
    } while(k < 5);
    printf("\n");
    
    return 0;
}

6. 数组

#include <stdio.h>

int main() {
    // 一维数组
    int numbers[5] = {1, 2, 3, 4, 5};
    
    printf("Array elements:\n");
    for(int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");
    
    // 二维数组
    int matrix[2][3] = {
        {1, 2, 3},
        {4, 5, 6}
    };
    
    printf("Matrix:\n");
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

7. 函数

#include <stdio.h>

// 函数声明
int add(int a, int b);

int main() {
    int result = add(5, 3);
    printf("5 + 3 = %d\n", result);
    return 0;
}

// 函数定义
int add(int a, int b) {
    return a + b;
}

8. 指针基础

#include <stdio.h>

int main() {
    int num = 10;
    int *ptr = &num;
    
    printf("Value of num: %d\n", num);
    printf("Address of num: %p\n", &num);
    printf("Value of ptr: %p\n", ptr);
    printf("Value pointed by ptr: %d\n", *ptr);
    
    return 0;
}

9. 结构体

#include <stdio.h>
#include <string.h>

// 定义结构体
struct Student {
    char name[50];
    int age;
    float gpa;
};

int main() {
    // 创建结构体变量