C language branch statement and loop statement classic questions and error-prone questions

Hello everyone, I am deep fish~

Table of contents

Foreword:

1. switch statement

2. Output from big to small

3. Print prime numbers

4. Print leap year

 5. Greatest common divisor

(1) Solution 1: The method of rolling and dividing

(2) Problem solution 2: more phase deduction method

6. Multiplication table

 7. Find the maximum value

 8. Sum of Fractions

 Summarize:

Conclusion:


Foreword:

This article is suitable for students who are learning branch statements and loop statements for the first time. These programming questions are some classic questions. If you have done it, see if there is a second method, and then see which method is the best. Welcome Exchange and learn in the comment area

1. switch statement

topic:

The statement about switch is incorrect: ( )

  A. The default clause in the switch statement can be placed anywhere

  B. The expression after the case in the switch statement can only be an integer constant expression

  C. The case clause must precede the default clause in the switch statement

  D. The case expression in the switch statement does not require order

answer:

The correct answer is: C

ACD.case and default expressions can be placed anywhere, but it is better to put case first and default after

B. The expression after the case in the switch statement can only be an integer constant expression . The integer constant expression means that the operands in the expression are all integer types. The integer type here is not only int type, but also char , short, long and other types, these types are also behind the switch

2. Output from big to small

topic:

Write code to output three integer numbers in descending order.

For example:

Input: 2 3 1

Output: 3 2 1

Solution: Idea : always let a>b>c, if the condition is not satisfied, exchange the size , so you need to compare three groups, a and b, a and c, b and c, three if statements to solve.

But if there are multiple integers, you need bubble sorting, or qsort function. If you want to learn, you can read C language programming introduction to brush questions (4) Question 4: Compete for the top five

#include<stdio.h>
int main()//从大到小输出
{
	int a = 0;
	int b = 0;
	int c = 0;
	//输入
	scanf("%d %d %d", &a, &b, &c);
	//比较并换位:始终让a>b>c
	if (a < b)
	{
		//交换a和b
		int tmp = a;
		a = b;
		b = tmp;
	}
	if (a < c)
	{
		int tmp = a;
		a = c;
		c = tmp;
	}
	if (b < c)
	{
		int tmp = b;
		b = c;
		c = tmp;
	}
	//输出
	printf("%d %d %d", a, b, c);
	return 0;
}

3. Print prime numbers

topic:

Write a code: print prime numbers between 100 and 200

Solution: The idea is to generate a number between 100 and 200, and then divide it by the divisor j. If the divisor i is divisible, jump out of the loop directly. If j is greater than sqrt(i) and has not been divisible, i is a prime number

Pay attention to a few points:

<1>Because the digits of prime numbers can only be 1, 3, 5, 7, 9, the generated dividend can be directly initialized to 1 , and then continuously add 2 ( i=i+2 ) (but note that 2 is a special case )
<2> The divisor j starts from 2 instead of 1 (any number can be divisible by 1)

<3> The divisor j to sqrt(i) (the square root of i) is not evenly divisible, which means it is a prime number

<4>Print the prime number outside the loop, if j is greater than sqrt(i), it is a prime number

#include<stdio.h>
#include<math.h>
int main()//打印100~200之间的素数
{
	int i = 0;//被除数
	int j = 0;//除数
	//素数个位只能是以1,3,5,7,9
	for (i = 101; i <= 200; i = i + 2)
	{
		//判断是否是素数
		for (j = 2; j <= sqrt(i); j++)//注意这里除数j是从2开始的
		{
			//如果i被整除,直接跳出循环
			if (i % j == 0)
				break;
		}
		//如果没有j可以整除i,即j>sqrt(i),就是素数
		if (j > sqrt(i))
			printf("%d ", i);
	}
	return 0;
}

4. Print leap year

topic:

Print leap years between 1000 and 2000

Solution: Judgment condition: divisible by 4, but not divisible by 100, and then divisible by 400

                       ((year % 4 == 0) && (year % 100 != 0))|| (year % 400 == 0)

#include<stdio.h>
int main()//打印1000年到2000年之间的闰年
{
	int year = 0;
	//生成年
	for (year = 1000; year <= 2000; year++)
	{
		//判断:能被4整除,但是不能被100整除,再闰或者能被400整除
		if (((year % 4 == 0) && (year % 100 != 0))|| (year % 400 == 0))
			//输出
			printf("%d ", year);
	}

	return 0;
}

Running results : no 1100, 1300, 1400, 1500, 1700, 1800, 1900

 5. Greatest common divisor

topic:

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

For example:

Input: 20 40

Output: 20

(1) Solution 1: The method of rolling and dividing

Idea: (There is no need to consider the size relationship between a and b here. If b>a enters a cycle, a will be greater than b

The remainder of two integers a%b=c;

If c==0 then b is the greatest common divisor;

If c!=0 then let a=b,b=c;

Then continue a%b to see if it is 0, if it is 0, output b directly, if it is not 0, recycle

Example:

a=28,b=21                                                     a=21,b=28

c=a%b=7(c!=0)                                      c=a%b=21(c!=0)

a=b=21;                                                         a=b=28

b=c=7; b=c=21 (at this time a and b are exchanged)

c=a%b=0

Directly output b=7 (greatest common divisor)

#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;
}

(2) Problem solution 2: more phase deduction method

Ideas:

If a>b, then a=ab;

If b>a, then b=ba;

Then check whether a is equal to b, if they are equal, the greatest common divisor is a,

                                 If not equal continue to loop a=ab or b=ba

Example:

a=28,b=21

a=a-b=7(b>a)

b=b-a=14(b>a)

b=b-a=7(a==b)

directly output a

#include<stdio.h>
int main()//更相减损法
{
	int a = 0;
	int b = 0;
	int i = 0;
	//输入
	scanf("%d %d", &a, &b);
	//求最大公约数
	while (a != b)
	{
		if (a > b)
			a = a - b;
		if (b > a)
			b = b - a;
	}
	//当a==b时输出a或b
	printf("%d", a);
	return 0;
}

6. Multiplication table

topic:

Output 9*9 multiplication table on the screen

Problem solution: Nested loop problem: i and j represent a multiplier respectively, and remember to wrap at the end of an i

%-2d here :

%2d indicates that the output int type value is output with a fixed bit width of 2 bits, and if it is less than 2 bits, a space is filled in front;

%-2d means to output the output int type value with a fixed bit width of 2 digits. If there are less than 2 digits, the number is in the front and the space is filled in the back

#include<stdio.h>
int main()//输出9*9乘法口诀表
{
	int i = 0;//乘数1
	for (i = 1; i <= 9; i++)
	{
		int j = 0;//乘数2
		for (j = 1; j <= i; j++)
		{
            //输出
			printf("%d*%d=%-2d ", i, j, i * j);
		}
		printf("\n");//换行
	}
	return 0;
}

Program result:

 7. Find the maximum value

topic:

Find the largest value among 10 integers

Solution: This question is the same as the highest score method of Question 7 of Introduction to C Language Programming (4) , except that the number here is relatively large and the array input, the highest score is only three numbers, just input directly, there is no difference in essence

#include<stdio.h>
int main()//求10 个整数中最大值
{
	int arr[10] = { 0 };
	int i = 0;
	//输入数组
	for (i = 0; i < 10; i++)
	{
		scanf("%d", &arr[i]);
	}
	//比较
	int max = arr[0];//首先认定第一个数为最大
	//从第二个数开始比较,然后比max大,就让这个数为max
	for (i = 1; i < 10; i++)
	{
		if (arr[i] > max)
			max = arr[i];
	}
	//输出
	printf("%d", max);
	return 0;
}

 8. Sum of Fractions

topic:

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

Solution to the problem: This question is similar to the C language programming introduction to brushing questions (4). The first question calculates the average score sum/5.0 and the third question online shopping flag*50 has the same effect. Pay attention to how to change the symbol here, flag=-flag

#include<stdio.h>
int main()//计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值,打印出结果
{
	int i = 0;
	double sum = 0.0;
	int flag = 1;
	//计算
	for (i = 1; i <= 100; i++)
	{
		sum += 1.0 / i*flag;
		flag = -flag;
	}
	//输出
	printf("%lf", sum);
	return 0;
}

Program result:

 Summarize:

1. In the switch statement, what follows case and switch is not necessarily only int type, but also char, short, long type, but not double, float type

2. The number is output from large to small:

If the number is less, always let a>b>c , if not, exchange positions

If the number is large, use bubble sort or qsort function

3. Print the prime numbers between 100-200:

The generated number i can be initialized to 1, then i=i+2

j is initialized to 2 , j only needs to go tosqrt (i)

How to end the judgment, j>=sqrt(i) can output i

4. Judgment of leap year: (((year%4==0)&&(year%100!=0))||(year%400==0))

5. Greatest common divisor:

(1) Rolling and dividing method: c=a%b a=b b=c

(2) The more detrimental method: a! =b a=ab b=ba

6. Print the multiplication table: understand %-2d

7. Find the maximum value of several numbers: let the first number be max, and then traverse and compare

8. Score calculation: use the method of 1.0/i and *flag

Conclusion: There is still glory in the other side, and the youth is not afraid of the long years

I feel that the author's writing is not bad, or when I have gained a little, I would like to trouble you to move your little hands and give me a one-click three-link, thank you very much

Guess you like

Origin blog.csdn.net/qq_73017178/article/details/131797474