c语言10个经典小程序

avatar
作者
筋斗云
阅读量:1

  1. Hello World
#include <stdio.h>  int main() {     printf("Hello, World!\n");     return 0; } 
  1. 计算两数之和
#include <stdio.h>  int main() {     int num1 = 5, num2 = 10;     int sum = num1 + num2;      printf("The sum of %d and %d is %d\n", num1, num2, sum);      return 0; } 
  1. 判断奇偶数
#include <stdio.h>  int main() {     int num = 6;      if(num % 2 == 0) {         printf("%d is an even number\n", num);     } else {         printf("%d is an odd number\n", num);     }      return 0; } 
  1. 找出最大数
#include <stdio.h>  int main() {     int num1 = 10, num2 = 20, num3 = 15;     int max;      max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);      printf("The largest number is %d\n", max);      return 0; } 
  1. 计算阶乘
#include <stdio.h>  int main() {     int num = 5;     int factorial = 1;      for(int i = 1; i <= num; i++) {         factorial *= i;     }      printf("Factorial of %d is %d\n", num, factorial);      return 0; } 
  1. 判断素数
#include <stdio.h>  int main() {     int num = 7;     int isPrime = 1;      for(int i = 2; i <= num / 2; i++) {         if(num % i == 0) {             isPrime = 0;             break;         }     }      if(isPrime) {         printf("%d is a prime number\n", num);     } else {         printf("%d is not a prime number\n", num);     }      return 0; } 
  1. 反转数组
#include <stdio.h>  int main() {     int arr[] = {1, 2, 3, 4, 5};     int n = sizeof(arr) / sizeof(arr[0]);      printf("Original array: ");     for(int i = 0; i < n; i++) {         printf("%d ", arr[i]);     }      printf("\nReversed array: ");     for(int i = n-1; i >= 0; i--) {         printf("%d ", arr[i]);     }      return 0; } 
  1. 斐波那契数列
#include <stdio.h>  int main() {     int n = 10;     int first = 0, second = 1, next;      for(int i = 0; i < n; i++) {         if(i <= 1) {             next = i;         } else {             next = first + second;             first = second;             second = next;         }          printf("%d ", next);     }      return 0; } 
  1. 冒泡排序
#include <stdio.h>  void bubbleSort(int arr[], int n) {     for(int i = 0; i < n-1; i++) {         for(int j = 0; j < n-i-1; j++) {             if(arr[j] > arr[j+1]) {                 int temp = arr[j];                 arr[j] = arr[j+1];                 arr[j+1] = temp;             }         }     } }  int main() {     int arr[] = {64, 34, 25, 12, 22, 11, 90};     int n = sizeof(arr) / sizeof(arr[0]);      bubbleSort(arr, n);      printf("Sorted array: ");     for(int i = 0; i < n; i++) {         printf("%d ", arr[i]);     }      return 0; } 
  1. 矩阵乘法
#include <stdio.h>  int main() {     int mat1[2][2] = {{1, 2}, {3, 4}};     int mat2[2][2] = {{5, 6}, {7, 8}};     int res[2][2];      for(int i = 0; i <

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!