1.实现一个函数,打印乘法口诀表,口诀表的行数和列数自己指定,
输入9,输出99口诀表,输入12,输出1212的乘法口诀表。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int i = 0;
int num = 0;
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
int j = 0;
for (j = 1; j <= i; j++)
{
printf("%d * %d = %d ", j, i, (i * j));
if (i == j)
{
printf("\n");
}
}
}
}
2.实现一个函数判断year是不是润年
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int year = 0;
scanf("%d", &year);
if (year % 4 == 0)
{
if (year % 100 != 0 || year % 400 == 0)
{
printf("是闰年\n");
}
}
else
printf("不是闰年\n");
return 0;
}
3.函数二分查找
#include<stdio.h>
#include<string.h>
int binary_search(int arr[], int key, int sz)
{
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (key < arr[mid])
{
right = mid - 1;
}
else if (key > arr[mid])
{
left = mid + 1;
}
else
return mid;
}
return -1;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int key = 7;
int sz = sizeof(arr) / sizeof(arr[0]);
int num = binary_search(arr, key, sz);
if (num != -1)
{
printf("找到了:%d\n", num);
}
else
printf("找不到!\n");
return 0;
}
4.(函数递归)定义一个整型变量,输入1234,输出1 2 3 4
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
void print(unsigned int n)
{
if (n > 9)
{
print(n / 10);
}
printf("%d ", n % 10);
}
int main()
{
unsigned int x;
scanf("%u", &x);
print(x);
return 0;
}
5.(函数递归)n的k次方
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
double Pow(int n, int k)
{
if (k > 0)
{
return n * Pow(n, k - 1);
}
else if (k == 0)
return 1.0;
else
return 1.0 / (Pow(n, -k));
}
int main()
{
int n = 0;
int k = 0;
scanf("%d %d", &n, &k);
double ret = Pow(n, k);
printf("%lf\n", ret);
return 0;
}
6.(函数递归)字符串逆序输出
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int my_strlen(char* arr)
{
int count = 0;
while (*arr != '\0')
{
count++;
arr++;
}
return count;
}
void change(char* arr[])
{
int left = 0;
int right = my_strlen(arr)-1;
while (left < right)
{
char tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left++;
right--;
}
}
int main()
{
char arr[] = "abcdef";
change(arr);
printf("%s\n", arr);
return 0;
}
7.(函数递归)写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,
例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int DigitSum(int n)
{
if (n > 9)
{
return DigitSum(n / 10) + n % 10;
}
else
return n;
}
int main()
{
int num = 1234;
int sum = DigitSum(num);
printf("%d\n", sum);
return 0;
}
8.冒泡排序
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
void bubble_sort(int arr[], int sz)
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int tmp = 0;
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
int main()
{
int arr[] = { 9,8,7,6,5,4,3,2,1 };
int sz = sizeof(arr) / sizeof(arr[0]);//数组元素个数
bubble_sort(arr, sz);
return 0;
}