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;
}
相关推荐
春风解人意1 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip
政企项目老覃4 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
是隼人4 小时前
buuctf-pwn inndy_echo(32位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
淡海水4 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR4 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵5 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽5 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2085 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
刃神太酷啦5 小时前
Redis 进阶核心:持久化 (RDB/AOF)、事务与主从复制全解析----《Hello Redis!》(5)
linux·c语言·数据库·c++·redis·缓存·bootstrap