# C language learning - Weng Kai (Chapter 4 notes)

Posted by Zpixel on Fri, 01 Oct 2021 22:42:40 +0200

# C language

## Chapter IV

### 4.1.1 cycle

#### Count a few digits

• The program should read in a positive integer with less than 4 bits (including 4 bits), and then output the number of bits of this integer. For example:
• Input 352. Output: 3

#### Human VS Computer

• Human way: you can see it with your eyes
• 352 - > 3 digits!
• The way of computer: determine the number of digits by judging the range of numbers
• 352 ∈  - > 3 bits
• People are not good at it, because people are less able to calculate numbers than words

#### Program implementation

```int x;
int n = 1;

scanf("%d",&x);

if(x>999){
n = 4;
}else if(x>99){
n = 3;
}else if(x>9){
n = 2;
}else{
n = 1;
}

printf("%d\n",n);
```
• Because the title specifies positive integers with 4 digits and below, it can simplify some judgment
• There is no need to judge the upper limit because it is judged from a high place
• Not the other way around
• Question: what about positive integers in any range?
• It's impossible to add an if for every additional digit. It's endless

#### Think about it another way

• 352 - > 3 soon
• What are the digits of 123812843267518273618273675317?
• Count!

#### Count

• 123812843267518273618273612675317
• How do you count people? Count from left to right and cross out one number at a time
• How can the computer cross out that number?

#### Three digit questions in reverse order

• 352
• 352%100 ->52
• Then 123812843267518273618273675317% 10000000000000000000000000000000000 - > 23812843267518273618273675317
• How do you get that 10000000000000000?

#### Human VS Computer

• If you change, start from the right
• 123812843267518273618273612675317/10->12381284326751827361827361267531
• Remove the rightmost number, and then?
• Continue to row until there are no numbers to row
• Count in the process

#### Try the code

```int x;
int n=0;

scanf("%d",&x);

n++;
x/10;
if(x>0){
n++;
x/=10;
if(x>0){
n++;
x/=10;
if...
}
}
printf("%d",n);
```
• This is endless, so you need to use while
```int x;
int n=0;

scanf("%d",&x);

n++;
x/10;
while(x>0){
n++;
x/=10;
}

printf("%d",n);
```

### 4.1.2 while cycle

```if(x>0){
x/=10;
n++;
}
//And while statements
while(x>0){
x/=10;
n++;
}
//The difference is that if is one-time and while is repeated
``` (there should be opportunities to change conditions in the circulatory system)

#### while Loop

• If we translate while as "when", a while loop means to repeat the statements in the loop when the conditions are met.
• Judge whether to continue the loop before executing the loop, so it is possible that the loop has not been executed once.
• The condition is the condition for the continuation of the cycle.

#### Think again

```int x;
int n=0;

scanf("%d",&x);

n++;
x/10;
while(x>0){
n++;
x/=10;
}

printf("%d",n);
```
• If there is no outside operation?
```int x;
int n=0;

scanf("%d",&x);

while(x>0){
n++;
x/=10;
}

printf("%d",n);
```

#### Look at the program running results

• The human brain simulates the operation of the computer, lists all variables on paper, and recalculates the value of variables as the program progresses. When the program is finished, the final result of the program is left at the bottom of the table.

#### verification

• Test programs often use boundary data, such as data at both ends of the effective range, special multiples, etc
• Single digit;
• 10；
• 0；
• Negative numbers.

#### debugging

```int x;
int n=0;

scanf("%d",&x);

n++;
x/10;
while(x>0){
//printf("x=%d,n=%d\n",x,n);
n++;
x/=10;
}

printf("%d",n);
```
• Insert printf where appropriate in the program to output the contents of the variable

### 4.1.3 DO-WHILE cycle

#### Digit number algorithm

1. User input x;
2. Initialize n to 0;
3. x=x/10, remove one bit;
4. n++;
6. Otherwise n is the result.

#### do-while Loop

• When entering the loop, do not check, but check whether the conditions of the loop are met after executing the code of one round of loop body. If they are met, continue the next round of loop, and if not, end the loop
```do
{
<Loop body statement>
}while(<Cycle condition>);
```  (left do while, right while)

#### Two cycles

• The do while loop is very similar to the while loop, except that the condition is judged at the end of the execution of the loop body. That is, in any case, the loop will execute at least once, and then judge the condition. The same as the while loop is that the loop is executed when the conditions are met, and ends when the conditions are not met.
```int x;
int n=0;
scanf("%d",&x);
do{
n++;
x/=10;
}while(x>0);
printf("%d",n);
```

### 4.2.1 cycle calculation

#### log₂x

```int x;
int ret=0;
scanf("%d",&x);
while(x>1){
x/=2;
ret ++;
};
printf("log₂x of %d is %d.",x,ret);
```

The output is always 1, because the loop divided by 2 always ends with 1 (integer). So, what's wrong with this log ν x?

#### Small routine

• Save the original value before calculation, which may be useful later
```int x;
int ret=0;
scanf("%d",&x);
int t=x;
while(x>1){
x/=2;
ret ++;
};
printf("log₂x of %d is %d.",t,ret);
```

#### How are these values determined?

```int x;
int ret=0;
scanf("%d",&x);
int t=x;
while(x>1){
x/=2;
ret ++;
};
printf("log₂x of %d is %d.",t,ret);
```

Why is x > 1 in the while condition?

Because in the loop, various values are related. For example, when accumulating, the initial value is generally 0, but if accumulating, it is generally 1.

#### Counting cycle

```int count=100;
while(count>=0){
count--;
printf("%d\n",count);
}
printf("Launch!\n");
```
• How many times does this loop need to be executed?
• When the loop stops, does it output the last 0?
• What is the value of count after the loop ends?

(small routine: if you want to simulate a large number of cycles, you can simulate a small number of cycles and then make inference.)

### 4.2.2 guessing game

#### Guessing game

• Let the computer think of a number, and then let the user guess. Each time the user enters a number, he will tell him whether it is large or small until the user guesses it correctly. Finally, he will tell the user how many times he guessed.
• Because you need to keep repeating to let users guess, you need to use a loop
• Before actually writing a program, we can describe the idea of the program in words
• The core focus is on the conditions of circulation
• People often consider the condition of loop termination
1. The computer thinks of a number randomly and records it in the variable number;
2. A variable count responsible for recording times is initialized to 0;
3. Let the user enter a number a;
4. count increment (plus 1);
5. Judge the size relationship between a and number. If a is large, output "large"; If a is small, output "small";
6. If a and number are not equal (large or small), the program returns to step 3;
7. Otherwise, the program outputs "guess" and the number of times, and then ends.

(the condition of the loop is that a and number are not equal)

```scrand(time(0))
int number=rand()%100+1;
int count=0;
int a=0;
printf("I've figured out a number between 1 and 100.");
do{
printf("Please guess the number between 1 and 100:");
scanf("%d",&a);
count++;
if(a>number){
}else if(a<number){
}
}while(a != number);
printf("Excellent! Did you use it%d I guessed the answer once.\n",count);
```

#### random number

• Every time rand() is called, a random number is obtained

#### %100

• The result of x%100 is an integer of [0,n-1]

### 4.2.3 average calculation

#### Calculate average • Let the user input a series of positive integers, and finally input - 1 to end the input. Then the program calculates the average of these numbers and outputs the number and average of the input numbers
• Variable - > algorithm - > flowchart - > program

#### variable

• A variable that records the integer read
• What's the average?
• Just add it to an accumulated variable every time you read a number. When all the data is read, remove it to the number of the number you read
• A variable records the result of accumulation, and a variable records the number of reads

#### algorithm

1. The initialization variables sum and count are 0;
4. If number is - 1, sum/count is calculated and printed (note that it is calculated by floating point). ```#include<stdio.h>

int main(){
int number;
int sum=0;
int count=0;

do{
scanf("%d",&number);
if(number!=-1){
sum+=number;
count++;
scanf("%d",&number);
}
}while(number != -1);

printf("%f\n",1.0*sum/count);

return 0;
}
```

### 4.2.4 integer reverse order

#### Decomposition of integers

• An integer is composed of 1 to multiple digits. How to decompose the digits on each bit of the integer and then calculate it
• Do% 10 operation on an integer to get its single digit;
• If you do / 10 to an integer, you remove its single digits;
• Then do% 10 to the result of the previous step to get the ten digits of the original number;
• and so on.
```#include<stdio.h>

int main(){
int x;
scanf("%d",&x);
int digit=0;
int ret=0;

while(x>0){
digit=x%10;
printf("%d",digit);
ret=ret*10+digit;
//printf("x=%d,digit=%d,ret=%d\n",x,digit,ret);
x/=10;
}
//printf("%d",ret);

return 0;
}
```

(there is a small problem here. Input 007, output 7, and input other first numbers that are not 0 can be reversed smoothly)

Topics: C