C language basic programming questions (1)

content

1. Judgment prime

2. Determining leap years

3. Greatest Common Divisor

4. Count the number of 9s

5. Score summation

6. Find the maximum value

7. Multiplication formula table

8. String reverse order (recursive implementation)

9. Calculate the sum of each bit of a number (recursive implementation)

10. Recursive realization of n to the power of k

11. Array operations

12. Swap arrays

13. Find the number of different bits in the binary of two numbers

14. Print odd and even digits of integer binary

15. Calculate the sum

16. Print the number of daffodils (enhanced version)

17. Print the rhombus

18. Drinking soda problems

19. Adjust odd-even order

20. strcpy simulation implementation


1. Judgment prime

Topic content:

To determine whether a number is a prime number, print the prime numbers between 100 and 200 and calculate how many prime numbers there are.

#include <stdio.h>
#include <math.h>

//试除法
int main()
{
	int i = 0;
	int j = 0;
	int count = 0;
	for (i = 101; i <= 200; i+=2) //由于偶数一定不是素数 所以判断奇数即可
	{
		//sqrt是一个库函数,对i开平方 需要头文件<math.h>
		for (j = 2; j <= sqrt(i); j++) 
		{
			if (i % j == 0)
			{
				break;
			}
		}
		if (j > sqrt(i)) //上面循环有两种情况会退出:1:i % j == 0 2:j > sqrt(i) 情况2才能说明是素数
		{
			printf("%d ", i);
			count++;
		}
}
	printf("\n100--200共有:%d个素数\n", count);
	return 0;
}

Note: If i = a * b, then one of the factors (a or b) must be less than or equal to the root i 

For example: 16 = 2 * 8 also = 4 * 4 where both 2 and 4 are less than or equal to the root sign 16

So: To judge whether it is a prime number (find a small factor), it only needs the range of j to be between [ 2, sqrt(i)]

2. Determining leap years

Topic content:

Print leap years between 1000 and 2000.

#include <stdio.h>

int main()
{	
//判断闰年的规则:(满足1或2即可)
//1.能被4整除且不能被100整除
//2.能被400整除
	int year = 0;
	int count = 0;
	for (year = 1000; year <= 2000; year++)
	{
		if (((year % 4 == 0) && (year % 100 != 0)) || year % 400 == 0)
		{
			printf("%d ", year);
			count++;
		}
	}
	printf("\n共有%d个闰年",count);
	return 0;
}

3. Greatest Common Divisor

Topic content:

Given two numbers, find the greatest common divisor of the two numbers

//辗转相除法
#include <stdio.h>

int main()
{	
	int a = 0;
	int b = 0;
	int c = 0;
	scanf("%d %d", &a, &b);
	while (c = a % b)
	{
		a = b;
		b = c;
	}
	printf("最大公约数为:%d",b);
	return 0;
}

//暴力求解
#include <stdio.h>
//先找到两个数中的最小值min(因为最大公约数最大能到min)
//暴力解出最大公约数
int main()
{	
	int a = 0;
	int b = 0;
	int min = 0;
	int i = 0;

	scanf("%d %d", &a, &b);
	if (a > b)
		min = b;
	else
		min = a;
	for (i = min; i > 0; i--)
	{
		if ((a % i == 0) && (b % i == 0))
			break;
	}
	
	printf("最大公约数为:%d",i);
	return 0;
}

4. Count the number of 9s

Topic content:

Write a program to count how many numbers 9 appear in all integers from 1 to 100

#include <stdio.h>

int main()
{
	int i = 0;
	int count = 0;
	for (i = 1; i <= 100; i++)
	{
		if (i / 10 == 9)  //判断十位是否为9
			count++;
		if (i % 10 == 9)  //判断个位是否为9
			count++;
	}
	printf("\n1--100共有:%d个9\n", count);
	return 0;
}

5. Score summation

Topic content:

Calculate the value of 1/1-1/2+1/3-1/4+1/5 ... + 1/99 - 1/100 and print the result

//不用逻辑判断的代码
#include <stdio.h>

int main()
{
    int i = 0;
    double sum = 0.0;
    int flag = 1;
    for (i = 1; i <= 100; i++)
    {
         sum += flag * 1.0 / i;
         flag *= -1;
    }
    printf("%lf", sum);
}


//常规思路代码
#include <stdio.h>

int main()
{
    int i = 0;
    double sum = 0.0;
    for (i = 1; i <= 100; i++)
    {
        if (0 == i % 2)
        {
            sum -= 1.0 / i;
        }
        else
            sum += 1.0 / i;
    }
    printf("%lf", sum);
}

Note: The division operator / When both sides are integers, it performs integer division, such as: 1/2 = 0, but as long as there is a floating point number on both sides of the operand, it performs the division of floating point numbers

6. Find the maximum value

Topic content:

Find the largest value among 10 integers

#include <stdio.h>

int main()
{
    int arr[10] = { 0 };
    int sz = sizeof(arr) / sizeof(arr[0]);
    int i = 0;

    for(i = 0; i < sz; i++)
    {
        scanf("%d", &arr[i]);
    }
    int max = arr[0]; //易出错的一步
    for (i = 0; i < 10; i++)
    {
        if (arr[i] > max)
            max = arr[i];
    }
    printf("max = %d", max);
    return 0;
}

Note: When defining the maximum value, let it be equal to the first number in the array, not 0 (in order to prevent all negative numbers in the array)

7. Multiplication formula table

Topic content:

Output the 9*9 multiplication formula table on the screen

#include <stdio.h>

int main()
{
    int i = 0;
    //行数
    for (i = 1; i <= 9; i++)
    {
        int j = 0;
        //打印一行的多少列
        for (j = 1; j <= i; j++)
        {
            //打印一项
            printf("%d*%d = %-2d ", i, j, i * j);//如果不是%-2d会存在"错位"的现象
        }
        printf("\n");
    }

    return 0;
}

Pay attention to the phenomenon of "misalignment": use %2d (right-aligned) or %-2d (left-aligned) to solve

8.  String reverse order (recursive implementation)

Topic content:

Write a function reverse_string(char * string) (recursive implementation)

Implementation : Arrange the characters in the parameter string in reverse order instead of printing them in reverse order.

for example:

char arr[] = "abcdef"; the contents of the array after reverse order become: fedcba

Take abcdef as an example:

Recursive idea: The characters 'a' and 'f' at both ends are transposed, and the remaining string "bcde" in the middle participates in the next recursion

For example, the specific steps of the first step are:

① Create tmp storage 'a'

②'f' replaces the position of 'a'

3 Replace the original position of 'f' with '\0' (the purpose of this is to find the position of the penultimate element e, because the way the strlen function calculates the length is to encounter the termination of '\0', so that the middle of the reverse order can be reversed. remaining strings )

④ When the middle string is reversed, put 'a' into the position where 'f' used to be

Note: For the steps of reversing the intermediate string, when the length of the intermediate string is greater than 1, it is necessary for them to continue to change positions and participate in the next recursion

//递归版本
#include <stdio.h>
#include <string.h>

void reverse_string(char arr[])
{
	char tmp = arr[0];         //①
	int len = strlen(arr);
	arr[0] = arr[len - 1];    //②
	arr[len - 1] = '\0';      //③
	//中间字符串的逆序
	if (strlen(arr + 1) > 1)  //注
		reverse_string(arr + 1);
	arr[len - 1] = tmp;       //④
}
int main()
{
	char arr[100] = { 0 };
	//scanf("%s", arr);//有问题,遇到空格时就终止了
	gets(arr);//读取一行,有空格也会读取
	reverse_string(arr);
	printf("%s", arr);
	return 0;
}


//非递归版本
#include <stdio.h>
#include <string.h>

void reverse_string(char arr[])
{
	int left = 0;
	int right = strlen(arr) - 1;
	
	while (left < right)
	{
		char tmp = arr[left];
		arr[left] = arr[right];
		arr[right] = tmp;
		left++;
		right--;
	}

}
int main()
{
	char arr[100] = { 0 };
	//scanf("%s", arr);
	gets(arr);
	reverse_string(arr);
	printf("%s", arr);
	return 0;
}

9. Calculate the sum of each bit of a number (recursive implementation)

Topic content:

Write a recursive function DigitSum(n) that takes a non-negative integer and returns the sum of the numbers that make it up

For example, calling DigitSum(1729) should return 1+7+2+9 whose sum is 19

Input: 1729, Output: 19

Recursive idea:

DigitSum(1719)  ==> DigitSum(1719/10) + (1719%10)

#include <stdio.h>

int DigitSum(int n)
{
	if (n > 9)
		return DigitSum(n / 10) + n % 10;

	else		
	return n;
}
int main()
{
	int n = 0;
	scanf("%d", &n);
	int sum = DigitSum(n);
	printf("%d", sum);
	return 0;
}

10. Recursive realization of n to the power of k

Topic content:

Write a function to implement n to the power of k, using recursion.

Recursive idea: n ^ k = n * (n ^ (k-1))

#include <stdio.h>

double Pow(int n, int k)
{
	if (k == 0)
		return 1.0;
	else if (k > 0)
		return (double)n * Pow(n, k - 1);
	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", ret);
	return 0;
}

11. Array operations

Topic content:

Create an integer array and complete the operation on the array

  1. Implement the function init() to initialize the array to all 0s
  2. Implement print() to print each element of the array
  3. Implement the reverse() function to invert the elements of an array.

Requirement: Design the parameters of the above functions by yourself and return the value.

#include <stdio.h>

void init(int *a, int sz)
{
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		*(a + i) = 0;
	}
}

void print(int* a, int sz)
{
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%d ", *(a + i));
	}
	printf("\n");
}

void reverse(int* a, int sz)
{
	int left = 0;
	int right = sz - 1;
	while (left < right)
	{
		int temp = a[left];
		a[left] = a[right];
		a[right] = temp;
		left++;
		right--;
	}
}


int main()
{
	int arr[5] = { 1, 2, 3, 4, 5 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	init(arr,sz);
	print(arr,sz);
	int brr[5] = { 1, 2, 3, 4, 5 };
	reverse(brr,sz);
	print(brr, sz);
	return 0;
}

Note: Try not to have redundant operations when writing functions (such as: initialization function, then initialize it, no need to print it out), in addition, reversing an array requires reversing the array elements instead of just printing them in reverse order

12. Swap arrays

Topic content:

Swap the contents of array A with the contents of array B. (the same size as the array)

#include <stdio.h>

void SwapArr(int* arr1, int* arr2, int sz)
{
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		int temp = arr1[i];
		arr1[i] = arr2[i];
		arr2[i] = temp;
	}
}

int main()
{
	int arr1[] = { 1, 3, 5, 7, 9 };
	int arr2[] = { 2, 4, 6, 8, 0 };
	int sz = sizeof(arr1) / sizeof(arr1[0]);
	SwapArr(arr1, arr2, sz);
    return 0;
}

13. Find the number of different bits in the binary of two numbers

Topic content:

Programming implementation: How many bits are different in the binary representation of two int (32-bit) integers m and n? 

Input example:

1999 2299

Example output: 7

#include <stdio.h>


//方法一:
int get_diff_bit1(int m, int n)
{
	//一个数与1按位与,可知从右往左第一位是0还是1
	//eg:11 - 十进制
	//00000000000000000000000000001011 - 二进制
	//00000000000000000000000000000001 - 和1按位与 结果为1,若最右是0,则结果为1
	int i = 0;
	int count = 0;
	for (i = 0; i < 32; i++)
	{
		if (((m >> i) & 1) != ((n >> i) & 1))
			count++;
	}
	return count;
}


//方法二:
//要求m与n之间有多少位不同,就相当于求 m^n后二进制序列里有多少个1(因为异或相同为0相异为1)
//又已知a & (a - 1)可以使a从左往右第一个1变成0,所以代码如下:
int get_diff_bit2(int m, int n)
{
	int i = 0;
	int count = 0;
	int tmp = m ^ n;
	while (tmp)
	{
		tmp = tmp & (tmp - 1);
		count++;
	}
	return count;
}

int main()
{
	int m = 0;
	int n = 0;
	scanf("%d%d", &m, &n);
	
	int count = get_diff_bit2(m, n);

	printf("%d\n", count);
}

14. Print odd and even digits of integer binary

Topic content:

Get all the even and odd bits in an integer binary sequence and print out the binary sequence respectively

#include <stdio.h>

int main()
{
	int m = 0;
	scanf("%d", &m);
	//eg:11
	//00000000000000000000000000001011

	//偶数位
	int i = 0;
	for (i = 31; i >= 1; i -= 2)
	{
		printf("%d ", (m >> i) & 1);
	}
	printf("\n");
	//奇数位
	for (i = 30; i >= 0; i -= 2)
	{
		printf("%d ", (m >> i) & 1);
	}
	return 0;
}

15. Calculate the sum

Topic content:

Find the sum of the first 5 terms of Sn=a+aa+aaa+aaaa+aaaaa, where a is a number,

For example: 2+22+222+2222+22222

#include <stdio.h>

int main()
{
	int a = 0;
	int n = 0;
	int i = 0;
	scanf("%d%d", &a, &n);
	int b = 0;
	int sum = 0;

	for (i = 0; i < n; i++)
	{
		b = b * 10 + a;
		sum += b;

	}
	printf("%d\n", sum);
	
	return 0;
}

16. Print the number of daffodils (enhanced version)

Topic content:

Find all "daffodils" between 0 and 100000 and output.

"Daffodil number" refers to an n-digit number, and the sum of the n-th power of each number is indeed equal to the number itself, such as: 153=1^3+5^3+3^3, then 153 is a "daffodil number".

int main()
{
	int i = 0;

	for (i = 0; i <= 100000; i++)
	{
		//判断i是否为自幂数
		//1. 计算i的位数 - n
		int tmp = i;
		int count = 1;
		int sum = 0; //*易错点*,每次循环开始时sum要归0,不能写在循环外面
		while (tmp /= 10)
		{
			count++;
		}
		//2.获得i的每一位,计算其每一位的n次方和
		tmp = i;
		while (tmp)
		{
			sum += pow(tmp % 10, count);//pow为求幂的库函数,需要头文件math.h
			tmp /= 10;
		}
		//3.比较并打印
		if (i == sum)
		{
			printf("%d ", i);
		}
	}
	return 0;
}

17. Print the rhombus

Topic content:

Output a diamond on the screen in C language.

#include <stdio.h>

int main()
{
	//打印一个菱形
	int line = 0; //行数
	int i = 0;

	scanf("%d", &line); //假设为6
	//菱形上半部分打印line行
	for (i = 0; i < line; i++)
	{
		//打印一行
		//先打印空格,再打印* 
		//第一行打印line - 1个空格,第二行line - 2个空格...
		int j = 0;
		for (j = 0; j < (line - 1 - i); j++)
		{
			printf(" ");
		}
		for (j = 0; j < (2 * i + 1); j++)
		{
			printf("*");
		}
		printf("\n");
	}
	//下半部分打印line - 1行
	for (i = 0; i < line - 1; i++)
	{
		 //打印一行
		//先打印空格,再打印*
		int j = 0;
		for (j = 0; j < i + 1; j++)
		{
			printf(" ");
		}
		for (j = 0; j <(line - 1 - i) * 2 - 1; j++)
		{
			printf("*");
		}
		printf("\n");
	}
	return 0;
}

18. Drinking soda problems

Topic content:

Drink soda, 1 bottle of soda is 1 yuan, 2 empty bottles can be exchanged for a bottle of soda, give 20 yuan, how much soda can be (programmed).

#include <stdio.h>

int main()
{
	int money = 0;
	int total = 0;  //总共换了多少瓶汽水
	int empty = 0;  //现在手里有多少空瓶

	scanf("%d", &money); //20
	total += money; //用钱买汽水
	empty = money;  //由汽水变空瓶

	while (empty >= 2)
	{
		total += empty / 2;//空瓶换来的汽水
		empty = empty / 2 + empty % 2;//*盘点手里的空瓶数
	}
	printf("total = %d\n", total);
	
	return 0;
}

19. Adjust odd-even order

Topic content:

Take an array of integers and implement a function to adjust the order of the numbers in the array so that all odd numbers in the array are in the first half of the array and all even numbers are in the second half of the array.

Idea: Double pointer: find an even number from front to back in the array, find an odd number from back to front, swap, and move the pointer to the middle

#include <stdio.h>

//简单的版本
void move_arr1(int *arr, int sz)
{
	int left = 0;
	int right = sz - 1;
	while (left < right)
	{
		if (arr[left] % 2 == 0)
		{
			if (arr[right] % 2 == 1)
			{
				int tmp = arr[left];
				arr[left] = arr[right];
				arr[right] = tmp;
			}
			else
			{
				right--;
			}
		}
		else
		{
			left++;
		}
	}
}

//更易理解的版本,但更复杂
//该方法要单独考虑数组全为奇数或全为偶数的情况:
//若全是奇数,left会一直++,出现越界的情况

void move_arr2(int* arr, int sz)
{
	int left = 0;
	int right = sz - 1;
	
	while (left < right)
	{
		//从左边找一个偶数
		while ((left < right) && arr[left] % 2 == 1)
		{
			left++;
		}
		//从右边找一个奇数
		while ((left < right) && arr[right] % 2 == 0)
		{
			right--; 
		}
		if (left < right)
		{
			int tmp = arr[left];
			arr[left] = arr[right];
			arr[right] = tmp;
		}
	}
}

int main()
{
	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	move_arr1(arr , sz);
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%d ", *(arr + i));//验证
	}
	return 0;
}

20. strcpy simulation implementation

Topic content:

Simulate the library function strcpy

#include<stdio.h>
#include<assert.h>

char* my_strcpy(char* dest, const char* src) 
                //const为了保证拷贝的数组不发生变化,防止输错了的时候改变了原数组的值
{
	assert(dest && src); //assert:断言(当dest或src为空时,会报错),需要头文件<assert.h>                    
	char* ret = dest;
	while (*dest++ = *src++)
	{
		; //一举两得,既将arr1赋值了hello\0,且赋值\0后,循环条件判定为假,终止循环
	}
	return ret;
}

//简化前的代码
void my_strcpy2(char* dest, char* src)
{
	assert(dest != NULL);//断言
	assert(src != NULL);//断言
	while (*src != '\0')
	{
		*dest = *src;
		dest++;
		src++;
	}
	*dest = *src;//处理'\0'

int main()
{
	char arr1[20] = "xxxxxxxxxxxxx";
	char arr2[] = "hello";
    my_strcpy(arr1, arr2);
	printf("%s", arr1);
	printf("%s\n",my_strcpy(arr1, arr2));
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_62934529/article/details/123215709