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;
}
相关推荐
norlan_jame2 小时前
C-PHY与D-PHY差异
c语言·开发语言
ZPC82102 小时前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82102 小时前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David2 小时前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱2 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone2 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩2 小时前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
czy87874752 小时前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
蜡笔小马3 小时前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_531237173 小时前
C语言-数组练习进阶
c语言·开发语言·算法