"Aha C Language - Logic Challenge" study notes

"Aha C Language - Logic Challenge" study notes

Chapter 1 The Dream Sets Sail

Section 1 Let the computer speak

1. Basic knowledge

1) Two ways for computers to “speak”

Display on the screen
and make sounds through speakers
2) The computer "speaks" and displays on the screen

Format: printf("");

Notice:

Add "f" to
printf. Add brackets () after printf.
Double quotation marks "" are what you want the computer to "say".
All symbols must be entered in the English symbol environment.
Semicolon; indicates the end of the statement.
3) Language framework

frame:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    
    

	return 0;
}

4) Let the computer "pause"

Statement:

system("pause");

1
form:
"Please press any key to continue..." is a prompt output by system("pause");.

5) Line break

Statement: "\n"

Section 2 is more colorful

1. Set the background color and text color of the command line

Format:
system("color background color number + text color number/text color number");

Detailed usage:

color + two one-digit numbers - the first number: background color - the second number: text color
color + one one-digit number - only set the text color - the background color is still the default color
Note:
one-digit number It is hexadecimal - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f

Example

#include<stdio.h>
#include<stdlib.h>
int main()
{
    
    
	system("color f5");
	printf("wa wa wa");
	system("pause");
	
	return 0;
}

2. Related color codes

0=black 8=grey  
1=blue 9=light blue
2=green a=light green   
3=lake blue b=light light green  
4=red c=light red   
5=purple d=lilac   
6=yellow e =light yellow   
7=white f=bright white

Section 3 Let the computer do addition

1. Process

Input - storage - calculation - output

2. Basic knowledge

1) Assignment number

Symbol: =

Function: Assign the content on the right to the left

2) "Little House"

Format:

int a,b,c;

Function:
Store numerical values.

Function:
Store numerical values.

3) Code display
int a,b,c;
a=1;
b=2;
c=a+b;

Process:
① Calculate a+b first;
② Assign the value of a+b to c on the left of "=".

4) "Debt collector"

Code:

printf("%d",c);

Function:
"retrieve" the value in "little house" c on the right side of the comma.

5) Complete code for addition
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a,b,c;
	a = 1;
	b = 2;
	c = a + b;
	printf("%d", c);
	
	system("pause");

	return 0;

Section 4 The Home of Numbers - Variables

1. Basic knowledge

1) Decimal = floating point number

2) Variables

"Little house" is also called a variable.

3) Variable type/data type

int: the type used to store integers;
float: the type used to store decimals.

4) Assignment rules

There is and can only be one value stored in a variable.
What is stored in a variable is always the value assigned last time.
5) "=+" two operators

a = a + 1;
1
Function: Increase the value in variable a by 1 based on the original value.

Section 5 Data Output——I will do whatever I say

1. Basic knowledge

1) Output the entire arithmetic equation

Code display:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a,b,c;
	a-1;
	b=2;
	c=a+b;
	printf("%d+%d=%d",a,b,c);//相当于a+b=c
	
	system("pause");
	return 0;
}

Analysis:
%d "collects debt" from the variables after the quotation marks in this order.

2) Attention

  • The printf statement will only output the part inside the double quotes, and the part outside the double quotes only serves as a supplementary explanation for the part inside the double quotes.
  • Usually the number of "%d"s inside double quotes is equal to the number of variables behind them.

Section 6 Data Entry - Whatever I say, it’s okay

1. Basic knowledge

1) Let the computer "listen" to you.
Enter the statement: scanf("%d%f", variable);

2) Address character, referred to as "address character"
symbol: &

Why does the input statement have &, but the output statement does not
? Answer: When reading data, the computer needs to store the read value in the small house a (variable a). At this time, it needs to know the address of the small house in order to accurately place the value. input; but when outputting, the value is already in a, so it can be output directly to the screen.

3) Two ways of writing input sentences

写法一:
scanf("%d",&a);
scanf("%d",&b);

写法二:
scanf("%d%d",&a,&b);

Note:
The second way of writing is simpler. There is no space between the two "%d", and "&a" and "&b" are separated by commas.

4) Read two numbers from the keyboard and output the complete code for the sum of the two numbers.

#include<stdio.h>.
#include<stdlib.h>
int main()
{
    
    
	int a,b,c;
	scanf("%d%d",&a,&b);
	c=a+b;
	printf("%d+%d=%d",a,b,c);
	
	system("pause");
	return 0;
}

Chapter 7 How many types of houses are there?

1. Basic knowledge

1) Commonly used data types in C language

Data type name What kind of data is used to store
int integer
float floating point number
double Very large and small floating point numbers
char character

2) The difference between float and double

Scanf uses "%f" to read float type data, and "%lf" to read double type data.
Double can be expressed more accurately than float
. Note:

printf("%.15f", a);

The ".15" between "%" and "f" in the code means retaining 15 decimal places (rounded).

3) Character data type - char

Format:

char a = 'x';

Function:
Store a character.

Note:
Single quotes, not double quotes.

Logic challenge 1: Exchange the numbers in the small house
Method 1: (Temporary variable method)
Key:

t = a;
a = b;
b = t;

Complete code:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a, b, t;
	scanf("%d%d", &a, &b):

    t = a;
    a = b;
    b = t;

	printf("%d %d", a, b);

	system("pause");
	return 0;
}

By creating a temporary variable t, temporarily storing the value of variable a, then assigning the value of b to a, and then assigning the value of t (the original value of a) to b, thereby completing the exchange.

Method 2: (Difference method)
Key:

a = b - a;//a与b的差值
b = b - a;//b = a;b减去差值就为a
a = a + b;//a再加上差值就为b,然后将b的值赋给a

Complete code:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a, b;
	
	scanf("%d%d", &a, &b);
	
	a = b - a;
	b = b - a;
	a = b + a;
	
	printf("%d %d", a, b);
	
	return 0;
}

Chapter 8 Oh my God! How can you understand this?

1. Code specifications
  • Use Tab to adjust code format
2. Types and functions of comments
  • "//" - single line comment
  • "/**/" - multi-line comments
  • Explain what this line of code does
  • not needed for now

Chapter 2 The battle has just begun

Section 1 Greater than, less than or equal to

1. Relational operators
== equal
> more than the
< less than
>= greater or equal to
<= less than or equal to
!= not equal to

Section 2 Determining positive numbers

1. Algorithm

Essence:
methods and steps to solve problems.

2. Conditional statement (if statement)

Question:
How to determine whether a number is positive, negative, or 0, and output "yes", "no", and "0" if the conditions are met.

Three expression methods of if statement:

//1
if (a>0) {
    
    printf("yes");}
//2
if (a>0) printf("yes");//当且仅当条件成立时只需执行一条语句才可省略{}
//3
if (a>0)
	printf("yes");

3. Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a;//第一步,创建一个变量用来存储将要判断的整数 
	
	scanf("%d", &a);//第二步,输入一个整数
	
	if(a > 0) printf("yes");//第三步,判断输入的整数是否为正数,若是,则输出yes
	if(a < 0) printf("no");//第四步,判断输入的整数是否为负数,若是,则输出no
	if(a == 0) printf("0");//第五步,判断输入的整数是否为0,若是,则输出0 
	
	return 0;
} 

Section 3 Even Number Judgment

1. Basic knowledge

1) Problem
Determine whether a number is even
2) Analysis
An even number is a number that can be divided by 2. If the remainder of a number divided by 2 is 0, then the number is an even number.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a;
	
	scanf("%d", &a);
	
	if(a % 2 == 0) printf("yes");
	if(a % 2 != 0) printf("no");
	
	return 0;
} 

2. Let’s find fault together

1) Question
: Determine whether a number is a multiple of 7.
2) Analyze
that a multiple of 7 is a number that can be divisible by 7. If the remainder of a number divided by 7 is 0, then the number is a multiple of 7.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a;
	
	scanf("%d", &a);
	
	if(a % 7 == 0) printf("yes");
	if(a % 7 != 0) printf("no");
	
	return 0;
} 

3. Go one step further and give it a try

1) Question
: How to determine whether the end of a number is 0? If yes, output yes (eg 120), if not, output no (eg 1234).
2) Analysis
If the remainder of a number divided by 10 is 0, then the end of the number is 0.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a;
	
	scanf("%d", &a);
	
	if(a % 10 == 0) printf("yes");
	if(a % 10 != 0) printf("no");
	
	return 0;
} 

4) Expand

If you want to know the single digit of a number, just use the number %10. The remainder is the single digit of the number. (Taking from back to front)
Example:
The single digit of 1234 is equal to:
1234 % 10 == 4

Section 4 Artifact else

1. Basic knowledge

1) Grammar format

if (条件)
{
    
    
	语句 1;
	语句 2;
	语句 ……;
}
else
{
    
    
	语句 1;
	语句 2;
	语句 ……;
}

When the condition is true, the statement after if is executed; when the condition is false, the statement after else is executed.

2. Let’s find fault together

1) Question
to determine whether the end of a number is 7
2) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a;
	
	scanf("%d", &a);
	
	if(a % 10 == 7) printf("yes");
	else printf("no");
	
	return 0;
} 

3. Go one step further and give it a try

1) Question:
Type a positive integer from the keyboard and let the computer determine whether the number is a single digit (1~9). If yes, output yes, otherwise output no.
2) Analysis
If a number is a single digit, then the number divided by 10 is always 0. Otherwise, the number is not a single digit.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a;
	
	scanf("%d", &a);
	
	if(a / 10 == 0) printf("yes");
	else printf("no");
	
	return 0;
} 

Chapter 5 Please tell me who is older

1. Basic knowledge

1) Question
: How to let the computer determine which of two numbers is greater?
2) Analysis
Define three variables, a and b are used to store the two input numbers, and c is used to store the larger of a and b.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a, b, c;
	
	scanf("%d%d", &a, &b);
	
	if(a > b)
	{
    
    
		c = a;
	}
	else
	{
    
    
		c = b;
	}
	
	printf("%d", c);
	
	return 0;
} 

2. Go one step further and give it a try

1) Question
: Enter two positive integers from the keyboard and let the computer determine whether the second number is a divisor of the first number. If yes, output yes, if not, output no.
2) Analysis
of divisors, also known as factors. When an integer a is divided by an integer b (b≠0), the quotient is exactly an integer without a remainder. We say that a can be divided by b, or b can divide a. a is called a multiple of b, and b is called a divisor of a.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a, b;//定义两个变量 
	
	scanf("%d%d", &a, &b);//输入两个数	
	
	if(a % b == 0)//如果a能被b整除,则a是b的倍数,b是a的约数,输出yes 
	{
    
    
		printf("yes"); 
	} 
	else
	{
    
    
		printf("no");
	}
	
	return 0;
} 

Logic Challenge 2: What to do with 3 numbers

1. Basic knowledge

1) Question
: Compare the sizes of three numbers and output the largest number
2) Method

//方法一:创建新变量存储较大的值
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a, b, c, d;//a,b,c用来存放输入的值,d用来存放较大的值
	
	scanf("%d%d%d", &a, &b, &c);
	
	if(a > b)
	{
    
    
		d = a;
	}
	else 
	{
    
    
		d = b;
	}
	if(c > d)
	{
    
    
		d = c;
	}
	
	printf("%d", d);//输出d——最大的值
	 
	return 0;
}

//方法二:先分别比较a和b,以及a和c的关系,再b,再c……
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a, b, c;
	
	scanf("%d%d%d", &a, &b, &c);
	
	if(a >= b && a >= c) printf("%d", a);
	if(b >= a && b >= c) printf("%d", b);
	if(c > a && c > b) printf("%d", c);//若 if(c >= a && c >= b) printf("%d", c);则会输出两次值 
	 
	return 0;
}

2. Go one step further and give it a try

1) Question:
Enter a year (integer) from the keyboard and determine whether the year is a leap year. If yes, output yes; if not, output no.
2) Analyze
the judgment of leap year.
It can be divisible by 4, but not by 100.
It is divisible by 4 and also divisible by 400.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a;
	
	scanf("%d", &a);
	
	if((a % 4 == 0 && a % 100 != 0) || (a % 4 == 0 && a % 400 == 0))
	{
    
    
		printf("yes");
	}
	else
	{
    
    
		printf("no");
	}
	 
	return 0;
}

Logic Challenge 3: I want to sort

1. Basic knowledge

Question:
How to input any three numbers from the keyboard and sort these three numbers from large to small?
Complete code:
1) Method 1: Direct method

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a, b, c;
	scanf("%d%d%d", a, b, c);
	if(a >= b && a >= c) printf("%d %d %d", a, b, c);
	if(a >= c && c > b) printf("%d %d %d", a, c, b);
	if(b > a && a >= c) printf("%d %d %d", b, a, c);
	if(b >= c && c > a) printf("%d %d %d", b, c, a);
	if(c > a && a >= b) printf("%d %d %d", c, a, b);
	if(c > b && b > a) printf("%d %d %d", c, b, a);
	
	return 0;
}

2) Method 2: transposition method

Analysis: First compare variable a with variable b and variable c. If the values ​​in b and c are greater than the value in a, they are exchanged with a. After two comparisons, the value in variable a is the largest. Then compare b and c. If b<c, exchange them to ensure that b is the second largest. Finally, the largest number is placed in small house a, the second largest number is placed in small house b, and the smallest number is placed in small house c.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a, b, c, t;
	scanf("%d%d%d", &a, &b, &c);
	if(a < b)
	{
    
    
		t = a;
		a = b;
		b = t;
	}
	if(a < c)
	{
    
    
		t = a;
		a = c;
		c = t;
	}
	if(b < c)
	{
    
    
		t = b;
		b = c;
		c = t;
	}
	printf("%d %d %d", a, b, c);
	
	return 0;
}

2. Let’s find fault together

Two ways to judge odd number a:

  • a % 2 != 0
  • a % 2 == 1

Section 6 Operator Summary

basic operators

name effect
+ add
- reduce
* take
/ remove
> more than the
< less than
== equal
>= greater or equal to
<= less than or equal to
!= not equal to
&& and
or
! No

Section 7 1 > 2 Is it right or not?

if (1)
{
    
    
	printf("yes");
}
else
{
    
    
	printf("no");
}//输出yes

if (-5)
{
    
    
	printf("yes");
}
else
{
    
    
	printf("no");
}//输出yes

if (0)
{
    
    
	printf("yes");
}
else
{
    
    
	printf("no");
}//输出no

Summary:
In C language, when discussing the truth or falsehood of a certain number, only 0 is false, and the rest are considered true.

Chapter 8 Annoying Nesting

Question:
How to find the largest number among three numbers

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a, b, c;
	scanf("%d%d%d", &a, &b, &c);
	if(a >= b)
	{
    
    
		if(a >= c)
		{
    
    
			printf("%d", a);
		}
		else
		{
    
    
			printf("%d", c);
		}
	}
	else//a < b
	{
    
    
		if(b >= c)
		{
    
    
			printf("%d", b);
		}
		else
		{
    
    
			printf("%d", c);
		}
	} 
	
	return 0;
}

Simplified version:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a, b, c;
	scanf("%d%d%d", &a, &b, &c);
	if(a >= b)
		if(a >= c) 
			printf("%d", a);
		else 
			printf("%d", c);
	else//a >= b 不成立的情况
		if(b >= c) 
			printf("%d", b);
		else 
			printf("%d", c);
		
	return 0;
}

Summarize:

  • Else matching adopts the proximity principle
  • if-else "compound statement" is essentially an if-else statement from the outside

Section 9 Summary of if-else syntax

Summary:
1. When the relational expression in the brackets of if() is established, the content in {} after if() will be executed. When it is not established, the content in {} after else will be executed.

if (关系表达式)
{
    
    
	语句;
	语句;
	……
}
else
{
    
    
	语句;
	语句;
	……
}

2. When there is only one statement within {}, {} can be omitted.

if (关系表达式)
	语句;
else
	语句;

Chapter 4 The heavyweight players appear

Chapter 1 The never-ending cry

1. Basic knowledge

1) Question
How to make a computer do repetitive things.
2) while statement

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	system("color 2");
	while(1)
	{
    
    
		printf("wa");
	}
	
	return 0;
}

The program will print "wa" endlessly.

3) Grammar

When the relational expression in () after while is true, that is, the content in {} is executed only when the relational expression is true.
If there is only one statement in {}, then {} can be omitted.
If a number is judged to be true or false, as long as This number is true if it is not 0

Section 2 I’ll say it as many times as I want

1. Basic knowledge

1) Question
How to make the computer repeat a specified number of times.

Suppose we ask the computer to print 1~100, we want the relational expression to be true for the first 100 times, and then it will not be true for the 101st time.

2) Analysis
Create a new "variable" to constant the number of loops.

3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a = 1;
	while(a <= 100)
	{
    
    
		printf("%d ", a);
		a = a + 1;
	}
	
	return 0;
}

Section 3 if says to while: I am very important to you

1. Basic knowledge

1) Question
: How to make the computer output all numbers from 1 to 100 that are not divisible by 3?

2) Analysis
If you want not to print every time you encounter a multiple of 3, you only need to judge the value of variable a before each printing.

3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a = 1;
	while(a <= 100)
	{
    
    
		if (a % 3 != 0)
			printf("%d ", a);
		a = a + 1;
	}
	
	return 0;
}

2. Go further
1) For the question,
everyone gathers in a circle and starts counting from 1. However, whenever they encounter a multiple of 7 or a number with 7 at the end, they must clap and cannot report. Whoever makes a mistake will be punished. punish.
2) Analysis

  • Two if conditional judgments - multiples of 7 - numbers containing 7 at the end
  • A number with 7 at the end actually means that the ones digit of this number is 7, that is, the remainder after dividing this number by 10 is 7

3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a = 1;
	while(a <= 100)
	{
    
    
		if (a % 7 == 0 || a % 10 == 7)
			printf("%d ", a);
		a = a + 1;
	}
	
	return 0;
}

Section 4 Summation! Seek peace! ! Seek peace! ! !

1. Basic knowledge

1) Question
: How to let the computer find the sum of all numbers from 1 to 100?

2) Analysis
Create a new variable i - the worker who carries the apples - only takes 1 apple at first, then 2 apples, and then 3 apples...
Variable a - a very big fruit basket - —Put 1 apple in the first time, 2 apples in the second time, 3 apples in the third time...

3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a = 0;//初始值为0,刚开始水果篮子里什么都没有 
	int i = 1;
	while(i <= 100)
	{
    
    
		a = a + i;//装苹果的a 
		i = i + 1; //搬运苹果的i 
	}
	printf("%d", a);
	
	return 0;
}

2. Let’s find the differences together.
1) Question
: Find the value of 1×2×3×4×5×6×7×8×9×10

2) Analyze
cumulative multiplication.

3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a = 1;//a的初始值要为1,不然0乘以任何数还是0 
	int i = 1;
	while(i <= 10)
	{
    
    
		a = a * i;
		i = i + 1;
	}
	printf("%d", a);
	
	return 0;
}

3. Go further and give it a try
1) Question
: Enter an integer n (1<=n<=9) and find the factorial of n.

2) Analysis

Positive integer factorial: multiply from 1 times 2 times 3 times 4 to the required number.
3) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    	
	int a = 1;
	int i = 1;
	int n;
	scanf("%d", &n);
	
	while(i <= n)
	{
    
    
		a = a * i;
		i = i + 1;
	} 
	
	printf("%d", a);
	
	return 0;
}

Note:
Prompt text cannot be entered in the scanf statement. For example, scanf("Please enter the factorial number of n: %d", &n); is wrong!

Logic Challenge 4: The 60-second countdown begins

1. Basic knowledge

1) Question
: How to set a 60s countdown?

2) Basic syntax
Sleep():
Prerequisite: Add #include<windows.h> at the beginning of the code.
Format: Sleep - means "waiting"; () - "waiting" time, the unit is milliseconds.

system("cls"):
Function: "Clear screen" statement to clear all content on the screen.

3) Complete code

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	int a = 60;
	system("color 0a");//设置成黑底绿字 
	while(a >= 1)
	{
    
    
		system("cls");//每次显示之前先清一次屏
		printf("%d", a);//输出倒计时时间
		Sleep(1000);//“等待”1s
		
		a = a - 1; 
	}
	
	return 0;
}

2. Go further and give it a try
1) Question
Please try to write a two-minute countdown. It looks like: 2:00 1:59 …… 1:00 0:59 0:58 …… 0:02 0:01 0:00
2) Analyze
and design two loop bodies, the first loop is a countdown of 1: hour, Second loop 0: countdown of hours. And first show 2:00 separately
3) Complete code

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	system("color f5");//白底紫字 
	int a = 59;
	printf("2:00");
	Sleep(1000);
	while(a >= 0)//第一次1:59~1:00之间的循环 
	{
    
    
		system("cls");
		if(a < 10)
		{
    
    
			printf("1:0%d", a);
		}
		else
		{
    
    
			printf("1:%d", a);
		}
		
		Sleep(1000);
		
		a = a - 1; 
	}
	
	a = 59;//初始化a的值 
	while(a >= 0)//第二次0:59~0:00之间的循环 
	{
    
    
		system("cls");
		if(a < 10)
		{
    
    
			printf("0:0%d", a);
		}
		else
		{
    
    
			printf("0:%d", a);
		}
		
		Sleep(1000);
		
		a = a - 1;
	}
	
	return 0;
}

Section 6: This is a bit confusing - loop nesting is coming

1. Question 1 - Print 3 rows and 5 columns of asterisks

1) Analysis:
A total of 15 asterisks need to be output, and a new line needs to be printed every 5 asterisks.

2) Method

Method 1: Control printing line breaks through if statements
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	int a = 1;
	while(a <= 15)
	{
    
    
		printf("*");
		if(a % 5 == 0)//如果变量a的值恰好是5的倍数,换行
			printf("\n");
		a = a + 1;
	}
	
	return 0;
}

Method 2: Loop nesting
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a = 1;
	while(a <= 3)
	{
    
    
		int b = 1;//每行开始都要初始化b的值
		while(b <= 5)
		{
    
    
			printf("*");
			b = b + 1;
		}
		printf("\n");//每一行输入完5个星号后,换行 
		a = a + 1;
	}
	
	return 0;
}

analyze:

There are two while loops, one is the outer loop and the other is the inner loop. The inner loop is nested in the outer loop. The inner loop
is part of the outer loop. Every time the outer loop loops, the inner loop will loop from beginning to end
to control the outer loop. The variable that controls the number of loops is a, and the outer loop is called a while a loop.
The variable that controls the number of loops in the inner loop is b, and the inner loop is called a while b loop.

2. Question 2 - Printing stepped asterisks

1) Analysis
: Print a few asterisks at the first line of printing, and change the inner loop condition to b <= a.

2) Complete code

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a = 1;
	while(a <= 5)
	{
    
    
		int b = 1;//每行开始都要初始化b的值
		while(b <= a)
		{
    
    
			printf("*");
			b = b + 1;
		}
		printf("\n");//每一行输入完a个星号后,换行 
		a = a + 1;
	}
	
	return 0;
}

1) Please try to use a while loop to print the following graphics

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int n, a = 1;
	scanf("%d", &n);
	
	while(a <= n)
	{
    
    
		int b = 1;
		while(b <= a)
		{
    
    
			printf("%d ", a);//每行输出的是当前行数 
			b = b + 1;
		}
		printf("\n");
		a = a + 1;
	}
	
	return 0;
}

Please try to print the following graphic using while loop

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int n, a = 1, cnt = 1;//用来统计目前已输出的数字个数 
	scanf("%d", &n);
	
	while(a <= n)
	{
    
    
		int b = 1;
		while(b <= a)
		{
    
    
			printf("%d ", cnt);//输出目前是第几个数字 
			b = b + 1;
			cnt = cnt + 1;
		}
		printf("\n");
		a = a + 1;
	}
	
	return 0;
}

Analysis:
The output is the number of numbers currently output, so you can create a new variable cnt that counts the number of times.
Like the previous output of variable a, variable a represents the number of rows. The question requires that the number of output columns and the number of rows are consistent, so variable a can be output directly.
Also like the previous countdown of 60s, the number of cycles coincides with the countdown of 60s, so 60s can be output by outputting the number of cycles. (The function of loop variable a: ① counts the number of loops; ② represents the 60s countdown output)

Logic Challenge 5: Running Numbers

1) Question:
If you want a letter (assuming the letter is H) to run from the left to the right of the screen, that is, the letter H is at the far left of the first row of the screen (that is, the first row and the first column) in the first second. At two seconds, the letter H is in the second column of the first row of the screen, and at the third second, the letter H is in the third column of the first row of the screen, and so on.
2)
Method 1: First try

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	system("cls");
	printf("H");
	Sleep(1000);
	
	system("cls");
	printf(" H");
	Sleep(1000);
	
	system("cls");
	printf("  H");
	system("pause");
	
	return 0;
}

Analysis:
If it is 50 times, you need to copy and paste 50 times, which is too troublesome!

Method 2: Nested loops
Analysis:
The changing pattern of spaces in each loop is 0, 1, 2, which is exactly the same as the changing pattern of variable a. The value of variable a is 0 during the first loop, the value of variable a is 1 during the second loop, and the value of variable a is 2 during the third loop. That is to say, every time you loop, just print a space before printing the letter "H".

Complete code

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	int a = 0;
	while(a <= 2)
	{
    
    
		system("cls");
		int b = 1;//若b = 0,则会导致第一个字母前会出现空格 
		while(b <= a)//循环开始前,打印相应循环次数个空格数 
		{
    
    
			printf(" ");
			b = b + 1;
		}
		printf("H");
		Sleep(1000);
		
		a = a + 1;
	}
	
	return 0;
}

Use the while a loop to control how many steps the letter H needs to take, and use the while b loop to control how many spaces need to be printed in front of the letter H for each step it takes.

How many times does section 7 loop?

1. Basic knowledge

1) Code

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	int a = 1;
	while(a <= 2)
	{
    
    
		int b = 1;
		while(b <= 3)
		{
    
    
			printf("OK ");
			b = b + 1;
		}
		a = a + 1;
	} 
	
	return 0;
}

Analysis:
Two while loops, namely while a loop and while b loop, and while b loop is nested in while a loop.
Here, every time the while a loop loops, the while b loop will be executed completely from beginning to end (loop 3 times, print 3 "OK"). The while a loop here will loop twice, so the while b loop will be completely executed on both sides (printing 3 "OK" each time). Number of cycles: 2×3=6.

Logic Challenge 6: Running Man

1. Basic knowledge

1) Question
: Let the villain run from left to right and control the villain’s speed
2) Complete code

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	int a = 0;//统计循环的次数,即奔跑的次数,也是打印空格的数量
	int b;
	while(a <= 2)
	{
    
    
		system("cls");//每次输出前先进行“清屏” 
		
		b = 1;
		while(b <= a)//第一个小人的头打印0次空格,第二个小人的头打印1次空格,第三个小人的头打印2次空格
		{
    
    
			printf(" ");
			b = b + 1;
		} 
		printf(" O\n");
		
		b = 1; 
		while(b <= a)//第一个小人的身体打印0次空格,第二个小人的身体打印1次空格,第三个小人的身体打印2次空格
		{
    
    
			printf(" ");
			b = b + 1;
		} 
		printf("<H>\n");
		
		b = 1;
		while(b <= a)//第一个小人的脚打印0次空格,第二个小人的脚打印1次空格,第三个小人的脚打印2次空格
		{
    
    
			printf(" ");
			b = b + 1;
		} 
		printf("I I\n");
		
		Sleep(1000);//打印完一个小人整体后,“等待”1s——控制小人奔跑的速度 
		a = a + 1;
	}
	
	return 0;
}

Analysis:
Let the villain move to the right mainly by printing spaces on the left side of the villain. Therefore, lines 1, 2, and 3, that is, the villain's head, body, and legs, must be printed with spaces. Therefore, a while loop must be added to print spaces before the three parts of the villain's body.
Expansion:
If you want the villain to run further, just change while(a<=2) to while(a<=80). To run faster, just change it to Sleep(100).
2. Go further and give it a try
1) Question:
Can you design a "little man" and let it run from right to left?
2) Complete code

#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	int a = 20;//统计循环的次数,即奔跑的次数,也是打印空格的数量
	int b;
	while(a >= 0)
	{
    
    
		system("cls");//每次输出前先进行“清屏” 
		
		b = 1;
		while(b <= a)//第一个小人的头打印20次空格,第二个小人的头打印19次空格,第三个小人的头打印18次空格
		{
    
    
			printf(" ");
			b = b + 1;
		} 
		printf(" O\n");
		
		b = 1; 
		while(b <= a)//第一个小人的身体打印20次空格,第二个小人的身体打印19次空格,第三个小人的身体打印18次空格
		{
    
    
			printf(" ");
			b = b + 1;
		} 
		printf("<H>\n");
		
		b = 1;
		while(b <= a)//第一个小人的脚打印20次空格,第二个小人的脚打印19次空格,第三个小人的脚打印18次空格
		{
    
    
			printf(" ");
			b = b + 1;//不断地减少打印的空格数量 
		} 
		printf("I I\n");
		
		Sleep(100);//打印完一个小人整体后,“等待”1s——控制小人奔跑的速度 
		a = a - 1;
	}
	
	return 0;
}

3) Analysis
If you want the villain to run from right to left, you must specify multiple spaces at the beginning, and then continue to reduce the number of spaces in subsequent loops to achieve the effect of running from right to left.
In the above code, variable a controls the total number of steps the villain takes and the number of spaces remaining after each run. Variable b controls the number of spaces that should be printed on the left side of the villain after each run.

Section 8 for makes its grand debut

1. Basic knowledge

1) Grammar

//以打印数字1~10为例
for(int a = 1;i <= 10;a++)
{
    
    
	printf("%d", a);
}

2) Features

  • If the number of loops is known, use for
  • Use while for unknown number of loops
    2. Go further and give it a try
    1) Please try to use for loop to print the following graphics
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>

int main()
{
    
    
	for(int i = 1;i <= 5;i++)//菱形的上半部分 
	{
    
    
		for(int k = 4;k >= i;k--)//在打印星号之前打印的空格数(与行数的关系) 
		{
    
    
			printf(" ");
		}
		for(int j = 1;j <= 2 * i - 1;j++)//行数与列数的关系:列数=2*行数-1 
		{
    
    	
			printf("*");
		}
		printf("\n");
	}
	
	int t = 7;//创建一个变量,用来控制菱形下部分的循环次数 
	for(int i = 1;i <= 4;i++)//菱形的下半部分 
	{
    
    
		for(int j = 1;j <= i;j++)
		{
    
    
			printf(" ");
		}
		for(int j = 1;j <= t;j++)
		{
    
    
			printf("*");
		}
		t = t - 2;//打印完一行星号后,下一行打印星号数量减2 
		printf("\n");
	} 
	
	return 0;
}

analyze:

  • The pattern cannot be found as a whole and can be divided into several parts.
  • Find the relationship between rows and columns
  • New variables can be introduced to satisfy the rules

2. Please try to use a for loop to print a multiplication table

#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	for(int i = 1;i <= 9;i++)
	{
    
    
		for(int j = 1;j <= i;j++)//列数与行数相等 
		{
    
    
			printf("%d ×%d = %d\t", j, i, (i * j));
		}
		printf("\n");
	}
	
	return 0;
}

Chapter 5 The fun is coming later

Section 1 3 Structures of Programs

3 structures Features
sequential execution Execute each statement sequentially, line by line, from top to bottom.
Select Execute Select statements to be executed based on conditions
Loop execution When a condition is met, a statement is repeatedly executed until it exits when the condition is not met.

Section 2 is a bit long-winded.

First:

a++ == a=a+1 - Increase the value of variable a by 1 on the original basis
a-- == a=a-1 - Decrease the value of variable a by 1 on the original basis
Second :

a+=2 == a=a+2 - Increase the value of variable a by 2 on the original basis
a-=2 == a=a–2 - Decrease the value of variable a on the original basis 2
a*=2 == a=a*2 - Multiply the value of variable a by 2 on the original basis
a/=2 == a=a/2 - Multiply the value of variable a on the original basis Divide by 2
a%=2 == a=a%2 - take the value of variable a as remainder 2 based on the original value

Logic Challenge 7: Determining prime numbers is easy

1) Problem
to determine prime numbers
2) Analysis
of prime numbers (prime numbers):

A natural number greater than 1
cannot be divisible by other natural numbers except 1 and the integer itself (there are only two divisors of 1 and itself). 3) The
idea is
to determine whether a positive integer a is a prime number. You need to divide a by 2 and 2 respectively. 3, 4, 5...a-2, a-1. If all the integers from 2 to a-1 are not divisible by a, that is, no divisor can be found except 1 and a itself, then a is a prime number, otherwise it is a composite number.

4) Complete code

//#define _CRT_SECURE_NO_WARNINGS//在VS下需加入
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a, count;
	scanf("%d", &a);
	count = 0;//用来统计有几个约数 
	
	for(int i = 2;i <= (a-1);i++)//从2~a-1寻找a的约数 
	{
    
    
		if(a % i == 0)//如果a被i整除 
		{
    
    
			count++;
			printf("%d ", i);//打印出约数 
		}		
	}
	
	printf("\n");
	printf("a有%d个约数\n", count);
	
	if(count == 0)//从2~a-1均没有a的约数 
	{
    
    
		printf("a为质数\n");
	}
	else//2~a-1之间有a的约数 
	{
    
    
		printf("a为合数\n");
	}
	
	return 0;
}

Section 3 is faster: break

effect:

  • End the current loop early
  • break is used to terminate for, while or do-while loops early

Code: Optimize judgment of prime numbers

#define _CRT_SECURE_NO_WARNINGS//在VS下需加入
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a, count;
	scanf("%d", &a);
	count = 0;//用来统计有几个约数 

	for (int i = 2; i <= (a - 1); i++)//从2~a-1寻找a的约数 
	{
    
    
		if (a % i == 0)//如果i被a整除 
		{
    
    
			count++;
			break;
		}
	}

	if (count == 0)//从2~a-1均没有a的约数 
	{
    
    
		printf("%d为质数\n", a);
	}
	else//2~a-1之间有a的约数 
	{
    
    
		printf("%d为合数\n", a);
	}

	return 0;
}

Section 4continue

Problem:
Print even numbers.
Code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	for (int i = 1; i <= 100; i++)
	{
    
    
		if (i % 2 == 1)//i为奇数
		{
    
    
			continue;//为奇数则跳过之后的语句,提前进入下一次循环
		}
		printf("%d ", i);
	}

	return 0;
}

analyze:

  • i%2 == 1, indicating that i is an odd number
  • When i is an odd number, skip the subsequent print statement and enter the next loop in advance.

Summarize:

  • break causes the loop to jump out early
  • continue forces the program to enter the next cycle in advance

Logic Challenge 8: Verify Goldbach’s Conjecture

Goldbach's conjecture:
"Any even number greater than 2 can be written as the sum of two prime numbers."

Question:
Verify that all even numbers between 4 and 100 can be written as the sum of two prime numbers.

analyze:

  • Split each number k into the form a+b, and the range of a is 2~k/2
  • Determine whether a and b are prime numbers

Code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	for (int k = 4; k <= 100; k = k + 2)//4~100之间的偶数
	{
    
    
		for (int a = 2; a <= k / 2; a++)//找出其中一个质数
		{
    
    
			//判断a是否为质数
			int count1 = 0;
			for (int i = 2; i <= a - 1; i++)
			{
    
    
				if (a % i == 0)//i能被a整除,则a不是质数
				{
    
    
					count1++;
					break;//a在2~a-1之间有约数,a不是质数,提前结束当前循环,继续寻找下一个a
				}
			}
			if (count1 == 0)//如果a是质数
			{
    
    
				int b = k - a;//寻找另一个质数b
				//判断b是否为质数
				int count2 = 0;
				for (int i = 2; i <= b - 1; i++)
				{
    
    
					if (b % i == 0)//i能被b整除,则b不是质数
					{
    
    
						count2++;
						break;//b在2~b-1之间有约数,b不是质数,提前结束当前循环,继续寻找下一个a
					}
				}
				if (count2 == 0)//如果b也是质数
				{
    
    
					printf("%d = %d + %d\n", k, a, b);//a和b均为质数,打印出这个解
					break;//打印这个解并跳出循环
					//若想输出每一个偶数的所有可能的拆分方法,则注释掉break
				}
			}
		}
	}

	return 0;
}

Logic Challenge 9: Number of Daffodils

Daffodil number:
"The cube of single digits + the cube of tens digits + the cube of hundreds digits" is exactly equal to this number. For example: 153=1×1×1 + 5×5×5 + 3×3×3.

Method 1: Splicing method
Analysis:

A three-digit number must be a number from 100 to 999. The
hundreds digit is 1-9, the tens digit is 0-9, and the ones digit is 0-9
.

//#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	for (int i = 1; i <= 9; i++)//百位1~9
	{
    
    
		for (int j = 0; j <= 9; j++)//十位0~9
		{
    
    
			for (int k = 0; k <= 9; k++)//个位0~9
			{
    
    
				if (i * 100 + j * 10 + k * 1 == i * i * i + j * j * j + k * k * k)//如果"个位数的立方 + 十位数的立方 + 百位数的立方"恰好等于这个数
				{
    
    
					printf("%d\n", i * 100 + j * 10 + k);
				}
			}
		}
	}

	return 0;
}

"Splicing method", that is, enumerating all possible numbers in the hundreds, tens, and units digits, and then splicing them into a 3-digit number (hundreds digit × 100 + tens digit × 10 + units digit)

Method 2: Segmentation method
analysis:

  • How to split a number into three parts
  • Get the number in the ones, hundreds and tens digits of a number

Key points:

  • Three-digit numbers get the number in the ones place, the number in the tens place, and the number in the hundreds place
//a,b,c分别为x百位、十位、个位上的数
a = x / 100 % 10;//让原来的百位变成个位再取个位
b = x / 10 % 10;//让原来的十位变成个位再取个位
c = x / 1 % 10;//取个位

Code:

//#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int x, a, b, c;
	for (x = 100; x <= 999; x++)
	{
    
    
		a = x / 100 % 10;//百位数
		b = x / 10 % 10;//十位数
		c = x / 1 % 10;//个位数
		if (x == a * a * a + b * b * b + c * c * c)//如果"个位数的立方 + 十位数的立方 + 百位数的立方"恰好等于这个数
		{
    
    
			printf("%d ", x);
		}
	}

	return 0;
}

The "split method" splits a three-digit number x into 3 parts, namely a, b, and c, which are used to store the numbers in the hundreds, tens, and ones digits respectively.

Logic Challenge 10: Solve Mathematical Olympiad Puzzles

Question 1: Please fill in the same numbers in the two () to make the equation true:
()3×6528 = 3()×8256
Analysis:

  • Let the variable i loop from 1 to 9
  • Each loop only needs to determine whether the current i meets the conditions of this equation.
  • If it matches, output its value

Code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	for (int i = 1; i <= 9; i++)//让变量i从1到9循环
	{
    
    
		if ((i * 10 + 3) * 6528 == (3 * 10 + i) * 8256)//如果符合等式
		{
    
    
			printf("%d\n", i);
		}
	}

	return 0;
}

Question 2: In the above calculation formula, A, B, C, D, and E represent 5 different integers respectively. What are the values ​​of A, B, C, D, and E for it to be true? Please output this equation.

analyze:

  • ABCD×E = output if DCBA is established
  • The value range of ABCDE can only be 0~9
  • Five nested loops can solve

Code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	//遍历ABCDE五个数的所有组合
	for (int a = 0; a <= 9; a++)
	{
    
    
		for (int b = 0; b <= 9; b++)
		{
    
    
			for (int c = 0; c <= 9; c++)
			{
    
    
				for (int d = 0; d <= 9; d++)
				{
    
    
					for (int e = 0; e <= 9; e++)
					{
    
    
						if(a != b && a != c && a != d && a != e
								  && b != c && b != d && b != e
											&& c != d && c != e
													  && d != e)//如果ABCDE互不相等
							if ((a * 1000 + b * 100 + c * 10 + d) * e == (d * 1000 + c * 100 + b * 10 + a))//如果符合等式
							{
    
    
								//满足两个条件则按格式输出
								printf("%d%d%d%d\n", a, b, c, d);
								printf("× %d\n", e);
								printf("——\n");
								printf("%d%d%d%d\n", d, c, b, a);
							}
					}
				}
			}
		}
	}

	return 0;
}

Logic Challenge 11: Guessing Game

Question:
The computer will randomly give out an integer between 0 and 99. Every time you guess, the computer will tell you whether your guess is too high or too small, and you are required to guess it within a limited number of times.

Get random number

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main()
{
    
    
	srand((unsigned)time(NULL));//初始化随机数种子,通过当前时间获得这个随机种子

	int a = rand();//根据srand()提供的种子值,返回一个随机数

	printf("%d", a);

	return 0;
}

Complete code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main()
{
    
    
	int a, b, sum;
	sum = 6;//表示有6次猜的机会

	srand((unsigned)time(NULL));
	a = rand() % 100;//随机生成一个0~99之间的数

	while (1)
	{
    
    
		sum--;//开始猜数时,首先要消耗一次机会
		scanf("%d", &b);
		
		if (b > a)
			printf("大了,还剩下%d次机会,请继续\n", sum);
		else if (b < a)
			printf("小了,还剩下%d次机会,请继续\n", sum);
		else//b == a
		{
    
    
			printf("恭喜你,答对了!\n");
			break;
		}
		
		if (sum == 0)//猜数机会用完
		{
    
    
			printf("已经没有机会了,请重新开始吧!\n");
			break;
		}
	}

	return 0;
}

Logic Challenge 12: Are you good or bad? Turn off your phone.

grammar:

system("shutdown -s -t 50");

"shutdown" means a command to shut down or restart the computer, "-s" means shut down, "-r" means restart, and "-t 50" means shut down after 50 seconds.
Note - The shutdown procedure introduced in this section can only be used to shutdown the Windows operating system.

system("shutdown -a");

Cancel the shutdown command.

Chapter 6 Oh my god! A bunch of numbers are approaching

Section 1 Borrows array output in reverse order

Complete code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a[5];//声明一个元素个数为5的数组
	//输入0~4号元素到数组a中
	for (int i = 0; i <= 4; i++)
	{
    
    
		scanf("%d", &a[i]);
	}
	//逆序输出
	for (int i = 4; i >= 0; i--)
	{
    
    
		printf("%d ", a[i]);
	}

	return 0;
}

Logic Challenge 13: Tao Tao Picking Apples

Question:
There is an apple tree in the yard of Tao Tao's house. Every autumn, it will bear 10 apples. When the apples are ripe, Tao Tao will run to pick them. Taotao has a 30cm bench. When she cannot pick apples directly with her hands, she will step on the bench and try again.
Now we know the height of 10 apples from the ground and the maximum height that Tao Tao can reach when she straightens her hands. Please help Tao Tao calculate the number of apples she can pick. If she touches the apple, the apple will fall.

Complete code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	//输入10个苹果到地面的高度(100~200)
	int appleHigh[10];//声明一个长度为10的数组
	printf("请分别输入10个苹果距离地面的高度:\n");
	for (int i = 0; i < 10; i++)
	{
    
    
		scanf("%d", &appleHigh[i]);//分别输入10个苹果距离地面的高度
	}

	//输入陶陶把手伸直时能够达到的最大高度(100~120)
	int handHigh, bench = 30;//30cm高的板凳
	printf("请输入陶陶把手伸直时能够达到的最大高度:\n");
	scanf("%d", &handHigh);
	
	int cnt = 0;//用来记录陶陶所摘的苹果数量
	for (int i = 0; i < 10; i++)
	{
    
    
		if (appleHigh[i] <= (handHigh + bench))
			cnt++;
	}
	printf("陶陶能够摘到的苹果的数目是:%d\n", cnt);

	return 0;
}

Logic Challenge 14: A carrot and a pit

Question 1:
Enter 5 numbers from 0 to 9 from the keyboard, and then output the numbers from 0 to 9 that have not appeared before.

Complete code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a[10], t;//先创建10个“小房间”
	//1、将10个小房间中的值初始化为0
	for (int i = 0; i <= 9; i++)
		a[i] = 0;

	//2、将输入的数字对应小房间里的值改为1
	for (int i = 1; i <= 5; i++)
	{
    
    
		scanf("%d,", &t);//以此读入5个数
		a[t] = 1;//把对应的小房间改为1
	}
	
	//3、输出没有出现过的数
	for (int i = 0; i <= 9; i++)
	{
    
    
		if (a[i] == 0)
			printf("%d ", i);
	}

	return 0;
}

core:

  • For the numbers that have appeared, the values ​​in the small rooms they correspond to are all 1.
  • For numbers that have never appeared before, the values ​​in the corresponding small rooms are all 0.

Question 2:
What should you do if you now need to sort the five input numbers (range 0~9) from small to large? For example, if you input 2 5 2 1 8, the output will be 1 2 2 5 8.

Complete code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a[10], t;//先创建10个“小房间”
	//1、将10个小房间中的值初始化为0
	for (int i = 0; i <= 9; i++)
		a[i] = 0;

	//2、将输入的数字对应小房间里的值增加1,用来统计该数出现的次数
	for (int i = 1; i <= 5; i++)//循环读入5个数
	{
    
    
		scanf("%d,", &t);//把每一个数读到变量t中
		a[t]++;//t所对应的小房间中的值增加1,以此作为出现次数
	}
	
	//3、从小到大依照出现的次数输出对应的序号,从而实现将输入的数从小到大排序
	for (int i = 0; i <= 9; i++)//依次判断0~9这10个小房子
	{
    
    
		for (int j = 1; j <= a[i]; j++)//出现了几次就打印几次
			printf("%d ", i);
	}

	return 0;
}

  • Use a[i] to record the number of times a number appears
  • Output the input numbers from small to large to achieve sorting from small to large

Logic Challenge 15: Selection Sort

Question:
Sort the five numbers 77, 45, 26, 86, and 9 from small to large.

Complete sorting process:

Initial data [77 45 26 86 9]
After the first round of sorting 9 [77 45 86 26]
After the 2nd round of sorting 9 26 [77 86 45]
After the 3rd round of sorting 9 26 45 [86 77]
After the 4th round of sorting 9 26 45 77 [86]
After the 5th round of sorting 9 26 45 77 86

Complete code:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a[1000];//创建一个长度为1000的数组
	
	//1、输入要排序的数
	int n;
	scanf("%d", &n);//输入n个数
	for (int i = 0; i < n; i++)
		scanf("%d", &a[i]);
	
	//2、将5个数进行选择比较
	for (int i = 0; i < (n-1); i++)//5个数只需比较4次
	{
    
    
		for (int j = i + 1; j <= (n-1); j++)//a[i]分别与a[i+1]、a[i+2]……a[5]比较
		{
    
    
			if (a[i] > a[j])//若前面的数比后面的数大,则交换两数位置
			{
    
    
				int temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
	}
	
	//3、输出排好序的数
	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);

	return 0;
}

  • a[i] due to a[i+1], a[i+2]...a[5] ratio

Section 2 Two-dimensional Array

1. Create and print two-dimensional arrays

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a[3][4];
	int x = 0;

	for (int i = 0; i <= 2; i++)
	{
    
    
		for (int j = 0; j <= 3; j++)
		{
    
    
			a[i][j] = x;
			x++;
		}
	}

	for (int i = 0; i <= 2; i++)
	{
    
    
		for (int j = 0; j <= 3; j++)
		{
    
    
			printf("%d\t", a[i][j]);
		}
		printf("\n");//一行打印完毕需要换行
	}
	
	return 0;
}

2. Initialization of the array
Initialize all elements in the array to 0:

int a[10] = {
    
    0};

Key points:

  • The compiler will assign values ​​sequentially starting from a[0]. If there is no specific value later, it will default to 0.
  • If you only define an array without any initialization, the default value of each array element will be a random value.

Initialization of two-dimensional array:

int a[3][5] = {
    
    {
    
    1,2,3}, {
    
    4,5}};

Each bracket represents a line.

Chapter 7 You can do more with it

Section 1 The wonderful uses of characters

Simple calculator:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int a, b;
	char c;
	scanf("%d%c%d", &a, &c, &b);
	if (c == '+')
		printf("%d", a + b);
	if (c == '-')
		printf("%d", a - b);
	if (c == '*')
		printf("%d", a * b);
	if (c == '/')
		printf("%d", a / b);
	
	return 0;
}

Section 2 redundant enter key

getchar():

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	char a;
	a = getchar();
	printf("你刚才输入的字符是:%c\n", a);
	
	return 0;
}

getchar();与scanf(“%c”, &a);的作用是完全一样的。

用scanf()和getchar()来读取一个字符时,首先是将输入的字符接收到缓冲区,缓冲区是一块为用户的输入预留的内存区域。缓冲区不会自动释放,直到用户按下"Enter"键,缓冲区内的字符才会被释放,让我们的程序接收到。
也就是:

第一,只要用户还没有按下“Enter”键,用户就可以用“Backspace”键(退格键)或者“Delete”键(删除键)来纠正错误的字符输入
第二,如果用户没有按下“Enter”键,输入的字符就会一直逗留在缓冲区中,不会被我们所写的程序接收到,直到用户按下“Enter”键
getche():
作用:
按下一个键后,计算机能立马反应,而无需按下多余的“Enter”键。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include <conio.h>

int main()
{
    
    
	char a;
	a = _getche();
	printf("你刚才输入的字符是:%c\n", a);

	return 0;
}

总结:

getchar()读取一个字符,输入后等待用户按“Enter”键结束(带回显)
getche()读取一个字符,输入后立即获取字符,不用按“Enter”键结束(带回显)
getch()读取一个字符,输入后立即获取字符,不用按“Enter”键来结束(不带回显)
注意:在VS2019中需要加头文件#include <conio.h>,且将getche()改为_getche()才能达到同样的效果。

第3节 字符的本质

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	int i;
	for (int i = 0; i <= 127; i++)
	{
    
    
		printf("%d %c\n", i, i);
	}
	
	return 0;
}

计算机本质上只能存储0和1,任意整数都可以通过进制转换的方式变化成0和1的序列。所以表示字符最简单的方法就是把字符用整数来代替。字符所对应的整数就是该字符的ASCII码。

第4节 人名怎么存储呢

如何读取一行字符串:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	char a[10];
	scanf("%s", a);
	printf("%s", a);
	
	return 0;
}

此处的字符数组a(或者称作字符串a)只申请了10个空间,但只能存9个有效字符,因为最后一个需要用来存储字符串的结束标记‘\0’。

注意,a前面没有取址符“&”。(只有与“%s”配合使用来读取一行字符串时,才不需要在变量前加取址符“&”。)

问题:
第1行先输入1个人的名字,空1格后输入这个人的分数,第2行还是先输入1个人的名字,空1格后输入这个人的分数。

完整代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	char a[101], b[101];
	int x, y;

	scanf("%s", a);
	scanf("%d", &x);
	scanf("%s", b);
	scanf("%d", &y);

	if (x > y)
		printf("%s", a);
	else
	{
    
    
		if (x < y)
			printf("%s", b);
		else
			printf("%s和%s的分数相同", a, b);
	}
	
	return 0;
}

gets:
代码1:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	char a[10];
	scanf("%s", a);
	printf("%s", a);
	
	return 0;
}

代码2:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int main()
{
    
    
	char a[10];
	gets_s(a);
	printf("%s", a);
	
	return 0;
}

由此可见,用scanf进行字符串读入时,遇到空格就提前终止了,但是用gets进行读入时却可以读入一整行。

注意: VS2019使用的是新C标准,也就是C11,而VC6.0用的是老标准。 在新标准中,应该是用gets_s代替gets。

输出字符puts:

puts(a);

使用puts(a)输出时,会在末尾自动换到下一行,相当于printf(“%s\n”, a)。

字符数组赋初始值:

char a[10] = {
    
    "hello"};

在字符串的两边加上双引号和花括号就可以了。

逻辑挑战16:字母的排序

问题:
读入1行小写字母,然后将这行字母从a到z进行排序。

分析:
字符的本质是整数。所以字符的排序和整数的排序是完全一样的。

完整代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>//用strlen()函数的头文件

int main()
{
    
    
	char a[101];//假设读入的字符不超过100个
	int len;//存储字符串长度的整型变量
	gets_s(a);//输入字符串
	len = strlen(a);//通过strlen()函数获取字符串a的长度

	for (int i = 0; i < len - 1; i++)
	{
    
    
		for (int j = i + 1; j <= len - 1; j++)
		{
    
    
			if (a[i] > a[j])
			{
    
    
				char t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}
	}
		
	puts(a);//输出排完序的字符串

	return 0;
}

逻辑挑战17:字典序

问题:
如何对字符串排序呢,例如apple和pear的排序。翻字典时,apple排在pear的前面,这个就是字典序。
输入两个单词,然后按照字典序输出这两个单词。

分析:
字符的比较可以用“>、<、<=、>=、==”,但是字符串不可以。
两个字符串比较可以用函数strcmp()。strcmp(a,b)就是比较字符串a和字符串b在字典中的顺序。

如果字符串a和字符串b完全相同,返回值为0
如果字符串a在字典中比字符串b先出现,返回值小于0
如果字符串a在字典中比字符串b后出现,返回值大于0
完整代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>//用strcmp函数需此头文件

int main()
{
    
    
	char a[101], b[101];
	gets_s(a);
	gets_s(b);

	if (strcmp(a, b) <= 0)//a在b前面或a和b是同一个字符串
	{
    
    
		puts(a);
		puts(b);
	}
	else//a在b后面
	{
    
    
		puts(b);
		puts(a);
	}

	return 0;
}

第7节 多行字符

问题一:
读入5行字符串,然后将这5行字符串原封不动的输出。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>//用strcpy()、strcmp()函数必须包含

int main()
{
    
    
	char a[5][11];
	
	//输入5行字符串
	for (int i = 0; i <= 4; i++)
	{
    
    
		gets_s(a[i]);
	}

	//输出5行字符串
	for (int i = 0; i <= 4; i++)
	{
    
    
		puts(a[i]);
	}

	return 0;
}

问题二:
输入5个单词,然后把这些单词按照字典序输出。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>//用strcpy()、strcmp()函数必须包含

int main()
{
    
    
	char a[5][11], t[11];

	//输入字符串(0~4行)
	for (int i = 0; i <= 4; i++)
	{
    
    
		gets_s(a[i]);
	}
	//选择排序
	for (int i = 0; i <= 3; i++)
	{
    
    
		for (int j = i + 1; j <= 4; j++)
		{
    
    
			if (strcmp(a[i], a[j]) > 0)//如果按字典顺序字符串a[i]在a[j]的后面
			{
    
    
				//互换顺序
				strcpy(t, a[i]);
				strcpy(a[i], a[j]);
				strcpy(a[j], t);
			}
		}
	}
	//输出排序后的字符串(0~4行)
	for (int i = 0; i <= 4; i++)
	{
    
    
		puts(a[i]);
	}

	return 0;
}

  • 字符串比较函数strcmp()
  • 字符串复制函数strcpy()
  • 头文件#include<string.h>

第8节 存储一个迷宫

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>//用strcpy()、strcmp()函数必须包含

int main()
{
    
    
	char maze[7][12] = {
    
    "###########",
						"#O   #  ###",
						"# ## ##   #",
						"#  #    # #",
						"# #### ## #",
						"#       #  ",
						"###########" };

	//循环输出第0行到第6行
	for (int i = 0; i <= 6; i++)
		puts(maze[i]);

	return 0;
}

第8章 游戏时间到了

第1节 走迷宫

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include <conio.h>//用_getche()函数需包含

int main()
{
    
    
	system("color f5");//变色

	//定义迷宫
	char a[50][50] = {
    
    "##############################",
					  "#O         #   ##   # ### ####",
					  "# ###### # # #    # # ### ####",
					  "# #   ## #   # #### # ###   ##",
					  "#   # ##  ###    #  #  ## ####",
					  "##### #     # ##### ##    ####",
					  "#   # ##### #   #   # # #    #",
					  "# # #    ## # #### ## # # ####",
					  "# # # ##      ##      # # ####",
					  "# # # ####### ## ###### #   ##",
					  "# #   ##   # ## ###### ###   #",
					  "# ###### # #####  #        # #",
					  "#        # #     ##### ### #  ",
					  "# ######## ##### # ### ### # #",
					  "#     # ## ##### ###       ###",
					  "##### # ## #      ######## # #",
					  "#     # ## ## ###        #   #",
					  "# # ###       ###### ####### #",
					  "# #    ### ##      #         #",
					  "##############################"
					 };

	//定义小球初始位置和迷宫的出口
	int x, y, p, q;
	x = 1; y = 1; p = 12; q = 29;//x和y来存储小球的初始位置,p和q来存储迷宫的出口
	
	//输出迷宫
	for (int i = 0; i <= 19; i++)
		puts(a[i]);
	
	//定义上下左右按键
	while (x != p || y != q)
	{
    
    
		//S:向下移动
		char ch = _getche();
		if (ch == 's')
		{
    
    
			if (a[x + 1][y] != '#')//只有下一步不是栅栏“#”时小球才能移动
			{
    
    
				a[x][y] = ' ';//让小球当前位置变为空格
				x++;//更改小球的位置
				a[x][y] = 'O';//将小球新位置上的内容替换为小球“O”
			}
		}
		
		//W:向上移动
		if (ch == 'w')
		{
    
    
			if (a[x - 1][y] != '#')
			{
    
    
				a[x][y] = ' ';
				x--;
				a[x][y] = 'O';
			}
		}

		//A:向左移动
		if (ch == 'a')
		{
    
    
			if (a[x][y - 1] != '#')
			{
    
    
				a[x][y] = ' ';
				y--;
				a[x][y] = 'O';
			}
		}

		//D:向右移动
		if (ch == 'd')
		{
    
    
			if (a[x][y + 1] != '#')
			{
    
    
				a[x][y] = ' ';
				y++;
				a[x][y] = '0';
			}
		}

		//清屏并输出新迷宫的状态
		system("cls");
		for (int i = 0; i <= 19; i++)
			puts(a[i]);
	}
	
	system("cls");
	printf("恭喜你成功走出迷宫了!\n");
	
	Sleep(5000);
	return 0;
}

第2节 推箱子

问题:
在一个狭小的仓库中,要求把木箱从开始位置推到指定位置。仓库中有障碍物,稍不小心就会出现箱子无法移动或者通道被堵住的情况,而且箱子只能推、不能拉,需要巧妙地利用有限地空间和通道,合理安排移动地次序和位置,才能顺利完成任务。

分析:

四个终点被箱子填满后,退出循环
根据具体地图情况修改完善代码
完整代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include <conio.h>//用_getche()函数需包含

int main()
{
    
    
	//提示文字
	system("color f5");//变色
	printf("请通过WSAD(小写模式)键控制小人‘S’移动\n");

	//按任意键清屏
	system("pause");
	system("cls");

	//定义推箱子地图
	char sokoban[50][50] = {
    
    "##########",
							"##     ###",
							"##O###   #",
							"# S O  O #",
							"# **# O ##",
							"##**#   ##",
							"##########"
						   };

	//定义推箱人初始位置和箱子的位置
	int x = 3, y = 2, p1 = 4, q1 = 2, p2 = 4, q2 = 3, p3 = 5, q3 = 2, p4 = 5, q4 = 3;

	//输出推箱子地图
	for (int i = 0; i <= 8; i++)
		puts(sokoban[i]);

	while (sokoban[p1][q1] != '@' || sokoban[p2][q2] != '@' || sokoban[p3][q3] != '@' || sokoban[p4][q4] != '@')
	{
    
    
		if (sokoban[p1][q1] == 'O')
			sokoban[p1][q1] = '@';

		if (sokoban[p2][q2] == 'O')
			sokoban[p2][q2] = '@';

		if (sokoban[p3][q3] == 'O')
			sokoban[p3][q3] = '@';

		if (sokoban[p4][q4] == 'O')
			sokoban[p4][q4] = '@';

		//定义上下左右按键
		char ch = _getche();
	
		//W
		if (ch == 'w')
		{
    
    
			if (sokoban[x + 1][y] == '@' && sokoban[x+2][y] == '#' || sokoban[x][y + 1] == '@' && sokoban[x][y + 2] == '#' || sokoban[x + 1][y + 1] == '@' && sokoban[x + 1][y + 2] == '#' && sokoban[x][y + 2] == '#')
			{
    
    
				sokoban[x][y] = '*';
				x--;
				sokoban[x][y] = 'S';
			}
			else if (sokoban[x - 1][y] != 'O' && sokoban[x - 1][y] != '@')
			{
    
    
				if (sokoban[x - 1][y] != '#')
				{
    
    
					sokoban[x][y] = ' ';
					x--;
					sokoban[x][y] = 'S';
				}
			}
			else
			{
    
    
				if (sokoban[x - 2][y] != '#' && sokoban[x - 2][y] != '@')//箱子的左边
				{
    
    
					sokoban[x][y] = ' ';//原来位置是空格
					x--;
					sokoban[x][y] = 'S';//新位置是S
					sokoban[x - 1][y] = 'O';//新箱子位置
				}
			}
		}

		//S
		if (ch == 's')
		{
    
    
			if (sokoban[x + 1][y] != 'O' && sokoban[x + 1][y] != '@')
			{
    
    
				if (sokoban[x + 1][y] != '#')
				{
    
    
					sokoban[x][y] = ' ';
					x++;
					sokoban[x][y] = 'S';
				}
			}
			else
			{
    
    
				if (sokoban[x + 2][y] != '#' && sokoban[x + 2][y] != '@')//箱子的左边
				{
    
    
					sokoban[x][y] = ' ';//原来位置是空格
					x++;
					sokoban[x][y] = 'S';//新位置是S
					sokoban[x + 1][y] = 'O';//新箱子位置
				}
			}
		}

		//A
		if (ch == 'a')
		{
    
    
			if (sokoban[x][y + 1] == '@' && sokoban[x][y + 2] == '#' || sokoban[x + 1][y] == '@' && sokoban[x + 2][y] == '#')
			{
    
    
				sokoban[x][y] = '*';
				y--;
				sokoban[x][y] = 'S';
			}
			else if (sokoban[x][y - 1] != 'O' && sokoban[x][y - 1] != '@')
			{
    
    
				if (sokoban[x][y - 1] != '#')
				{
    
    
					sokoban[x][y] = ' ';
					y--;
					sokoban[x][y] = 'S';
				}
			}
			else
			{
    
    
				if (sokoban[x][y - 2] != '#' && sokoban[x][y - 1] != '@')//箱子的左边
				{
    
    
					sokoban[x][y] = ' ';//原来位置是空格
					y--;
					sokoban[x][y] = 'S';//新位置是S
					sokoban[x][y - 1] = 'O';//新箱子位置
				}
			}
		}

		//D
		if (ch == 'd')
		{
    
    
			if (sokoban[x][y + 1] != 'O' && sokoban[x][y + 1] != '@')
			{
    
    
				if (sokoban[x][y + 1] != '#')
				{
    
    
					sokoban[x][y] = ' ';
					y++;
					sokoban[x][y] = 'S';
				}
			}
			else
			{
    
    
				if (sokoban[x][y + 2] != '#' && sokoban[x][y + 2] != '@')//箱子的左边
				{
    
    
					sokoban[x][y] = ' ';//原来位置是空格
					y++;
					sokoban[x][y] = 'S';//新位置是S
					sokoban[x][y + 1] = 'O';//新箱子位置
				}
			}
		}

		//清屏并输出
		system("cls");
		for (int i = 0; i <= 8; i++)
			puts(sokoban[i]);
	}

	Sleep(1000);//等待1s

	//提示成功
	system("cls");
	printf("恭喜你成功通关!\n");

	return 0;
}

Guess you like

Origin blog.csdn.net/qq_51432166/article/details/131198819