C语言编程练习题:第一期

练习题1: 编写一个程序,计算并输出两个整数之和。

复制代码
#include <stdio.h>

int main() {
    int num1, num2;
    
    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);
    
    int sum = num1 + num2;
    printf("The sum of %d and %d is %d\n", num1, num2, sum);
    
    return 0;
}

练习题2: 编写一个程序,判断用户输入的年份是否为闰年。闰年的条件是:能被4整除但不能被100整除,或者能被400整除。

复制代码
#include <stdio.h>

int main() {
    int year;
    
    printf("Enter a year: ");
    scanf("%d", &year);
    
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        printf("%d is a leap year.\n", year);
    } else {
        printf("%d is not a leap year.\n", year);
    }
    
    return 0;
}

练习题3: 编写一个程序,计算并输出给定整数数组的所有元素之和。

复制代码
#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 0;
    
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    
    printf("The sum of all elements in the array is %d\n", sum);
    
    return 0;
}

练习题4: 编写一个程序,实现字符串反转功能。

复制代码
#include <stdio.h>
#include <string.h>

void reverse(char* str) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++) {
        char temp = str[i];
        str[i] = str[len - i - 1];
        str[len - i - 1] = temp;
    }
}

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    
    str[strcspn(str, "\n")] = '\0'; // Remove trailing newline
    
    reverse(str);
    printf("Reversed string: %s\n", str);
    
    return 0;
}

练习题5: 编写一个程序,找出给定整数数组中的最大值和最小值。

复制代码
#include <stdio.h>

int main() {
    int arr[] = {9, 7, 8, 6, Ⅰ1, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int max = arr[0], min = arr[0];
    
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    
    printf("The maximum value in the array is %d\n", max);
    printf("The minimum value in the array is %d\n", min);
    
    return 0;
}
相关推荐
phltxy5 小时前
C语言操作符详解
java·c语言·算法
RuoZoe5 小时前
从 2026 年 3 月 1 日开源,到 26.10.9:Jalium UI 半年时间到底走了多远?
c语言·c++
aqiu1111115 小时前
【LeetCode 902】最大为 N 的数字组合 - 详细题解与数位组合思路
数据结构·算法·leetcode·蓝桥杯·数位dp
辰烨chenye6 小时前
LeetCode Hot 100 题解 · 哈希篇
算法·leetcode·哈希算法
罗西的思考6 小时前
DreamZero 与 DreamDojo:世界模型与策略的分层协同综合分析与对比
人工智能·算法·机器学习
玖玥拾7 小时前
LeetCode 219 存在重复元素 II
算法·leetcode·哈希算法·散列表
知无不研8 小时前
c语言中循环的介绍与简单应用
c语言·开发语言·算法·循环·for·while
a187927218319 小时前
【算法】动态规划第四篇:背包收官——min 哨兵、计数世界与组合排列分水岭
算法·leetcode·动态规划·dp·01背包·算法讲解·决策合并
HRTOS9 小时前
HRTOS 4.0 驱动库:06_Storage 存储设备驱动——24C02 EEPROM与I²C驱动开发
c语言·驱动开发·嵌入式硬件·51单片机