本文主要是介绍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 newlinereverse(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;
}
这篇关于C语言编程练习题:第一期的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!