# Loop structure (composed of loop statements such as while and for)

## 1, Problem introduction:

Requirements:
sum = 1 + 2 + ... + 100

```sum = 0;
i = 1;
sum += i;
i++;
sum += i;
i++;
sum += i;
i++;
sum += i;
i++;
sum += i;
i++;
sum += i;

........

/*-> If we do this code manually, it's obvious that you'll go crazy
All right, let the computer go crazy
Let the computer do the same thing for you
This kind of thing is called cycle - > the essence is to repeat*/
```

## 2, goto statement

### 1. Grammatical form:

```Tag name:
sentence;

goto Tag name;
```

### 2. Explanation of usage:

goto target location; Go to a certain place. The target place is a mark in c language, which is used to mark an address. goto go jump this

### 3. Points needing attention when using goto statement:

goto has high priority and can jump unconditionally. No matter whether your address is valid or not, it will cause poor readability of your code

Therefore, as Xiaobai, try to avoid using it. If you want to use it, unless you are a character of nb

#### *Bootstrap thought

The gcc compiler uses an idea called bootstrap when developing

1. Will develop a subset compiler containing only a small amount of c language, which is written in assembly language

2. Then use this subset compiler to expand later to get a larger subset compiler. This compiler is the second generation, which can be compiled with the first generation compiler

3. After many generations, you can get the current gcc.

4. Result: if the first generation compiler has a back door, all the later compilers will have this back door, and you can't see it at all

goto is a good tool to use. Try not to use it when you can't control it

Use goto

### Find the sum of odd numbers within a value

Exercise 1:
Find the sum of all odd numbers within 10000

```//Find the sum of all odd numbers within 10000, mark the loop, goto jump to loop, and execute the conditions under loop
#include<stdio.h>
int main()
{
int i = 1,sum = 0;
loop:
sum += i;
i +=2;
if(i<10000)
goto loop;
printf("%d\n",sum);
return 0;
}
```

## 3, while statement

### 1. Grammatical form

```while(expression)
{
Circulatory body;//Compound statement
}
//Expressions can be legal expressions in c language
```

### 2. Explanation of usage

First judge the value of the expression. If it is true, execute the loop body
Then judge the value of the expression again. If it is true, continue to execute the loop body

...

Exit the loop until the value of the expression is false

### 3. Points needing attention

Curly braces: the contents in curly braces are under the jurisdiction of while. When the statement is executed, it will be true.

No curly braces: the while statement can only control the following statement. When the expression is true, only the immediately following statement will be executed.

### 4. Expand another usage of: \ n

\n:

1. Line feed

2. In the standard I / O, it also represents the refresh buffer

Program error finding method:

Usage: when there is a segment error and the core has been dumped, which only tells us the error of the program, but does not tell us where the error is, we can use printf ("% s% d \ n", function, line); Statement to lock where the error occurred.

Function of this statement: print out which function the current program execution place belongs to and the number of lines

If this statement is written in a function, but the relevant information is not printed out, it indicates that there is an error in the function, so the error location is locked.

Exercise 2:
Find the sum of multiples of 3 within 10000

```//Method 1:
#include<stdio.h>
int main()
{
int i = 0; sum = 0;
while(i < 10000)
{
sum += i;
i += 3;
}
printf("%d\n",sum);
return 0;
}

```
```//Method 2:
#include<stdio.h>
int main()
{
int i = 3, sum = 0;
loop:
sum += i;
i += 3;
if(i<10000)
goto loop;
printf("%d\n",sum);
return 0;
}

```

Exercise 2:
Find the number of daffodils in 100 ~ 999
Narcissus number: a bit, ten bit, a hundred bit cube and for itself

```//Find the number of daffodils in 100 ~ 999. Narcissistic number
//The cubic sum of one, ten and hundred is for itself
//double pow(double x,double y); To find the Y power of X, you need to add the header file math h,
//When compiling with gcc, you need to add the library gcc main c -o main -lm
#include<stdio.h>
#include<math.h>
int main()
{
int n = 100;
while(n<1000)
{
if(n == (int)pow(n/100,3)+(int)pow(n/10%10,3)+(int)pow(n%10,3))
printf("%d\n",n);
++n;
}
return 0;
}
```

Exercise 3:

Find how many 1s (32bit) are in a register

```//How many 1s are there in the binary system for finding a decimal number
/*Method 1: the method of converting decimal system to binary system. Divide a number by 2 until the remainder is 0. Judge whether the remainder 1 is 1 each time. If yes, num + +;*/
/*Method 2: use a = A & (A-1), so that after the rightmost 1 is set to zero, the other high-order 1 does not change. Each time you run, you can know that there is a 1*/
/*Method 3: &1 judge whether the last bit is zero. After each judgment, move one bit to the right to judge the next bit*/

//Method 1: divide by 2 from decimal to binary, which is only applicable to positive integers
#include<stdio.h>
int main()
{
int n,num = 0;
scanf("%d",&n);
while (n)
{
if(1 == n%2)
{
++num;
}
n = n/2;
}
printf("%d\n",num);
return 0;
}

```

```//Method 2: n & (n-1) applies to both positive and negative integers
#include<stdio.h>
int main()
{
int n,num = 0;
scanf("%d",&n);
while (n)
{
++num;
n = n & (n - 1);
}
printf("%d\n",num);
return 0;
}

```

```//Method 3: judge by bit and cycle 32 times (i.e. 32 bits), which is applicable to integers and negative numbers
#include<stdio.h>
int main()
{
int n,num = 0;
scanf("%d",&n);
for(int i = 0;i < 32;i++)
{
if(1 == (n>>i & 1))
++num;
}
printf("%d\n",num);
return 0;
}
/*
Test error reason:
Operator priority error
if(1 == (n>>i) & 1)
Priority: = = (relational operator) is higher than & (bitwise and logical operator)
So if (1 = = (n > > I) & 1) is equivalent to if ((1 = = n > > I) & 1)
Different from what I want to express, it should be
if(1==((n>>i) & 1)) I.e. if (1 = = (n > > I & 1)
*/

```

If there is only one 1 in reg, does this while also need to be done 32 times
Q: is there any way I can cycle it out once?
If there are several 1s in it, you only need to cycle a few times
​ reg & (reg - 1)
See 2 c

## do while statement

Syntax:
​ do
​ {

```	}
while(expression);

do If there are no curly braces, you will only recognize the following sentence, and this statement may have problems
proposal do After writing, type braces directly to show sovereignty

do
i = 1;
j = 2;
while();

Usage follow while The expression is the same
just  while Is to judge the execution first
do while No matter what your conditions are, it will be implemented once first
```

## for loop statement

for: loop
grammar
For (expression 1; expression 2; expression 3)
{
Circulatory body;
}

```for At the beginning of the loop, first go to expression 1,
Then judge whether the value of expression 2 is true
Execution loop body  -> Execute expression 3
Continue to judge expression 2 -> Execution loop body  -> Execute expression 3
-> Judgment expression 2  -> It's false  ->Exit loop

Expression 1: the whole loop will be executed only once

There are three expressions that don't need to be written, but there are two;;Not one less
If expression 2 is not written, the condition is always true

Expression 3 belongs to for Is not a circular body
```

Both for and while can form an endless loop
So which would be better
​ while(1);
​ for(;😉;
No one will be better. You can use whichever looks good to you

break and continue
break: end the loop of this layer
If the break is contained in which curly bracket, it ends who
while(1)
{
while(2)
{
break;// End while(2)
}
if()
{
break; -> The end is while(1)
}

```	}

be careful:
break It can also end switch
It and switch Don't do this cycle when you go to match

while(1)
{
switch(a)
{
case 1:
break;  //This break will match this switch
//Then it will only end the switch, not the loop
}

}

continue: End this cycle and start the next one
From this continue The section from the beginning to the end of the loop body will not be executed
Start the next cycle directly
At this time while and for It's different
while(i < 100)
{
if(i > 50)
{
continue;  //This time will form a dead cycle
}
i++;
}

for(i = 0;i < 100;i++)
{

if(i > 50)
{
continue;//It will end the execution of the following statements, but i + + still needs to be executed
//Then there will be no dead cycle
}
sentence;
}
```

practice:
1 find the maximum common divisor and the minimum common multiple of two numbers
1. Brute force cracking
Work until the minimum number
a b //a < b
n = a;
while(n >= 1)
{
If (a% n = = 0 & & B% n = = 0) / / divide from the big one to the small one
//The first one is the biggest one
{
break;
}
n–;
}

```	2 Rolling Division
(15,10) -> (10,5) -> (5,0) -> 5 Is the greatest common divisor

int a,b;//Divisor and dividend
while(b)
{
n = a % b;//Find remainder
a = b;
b = n;
}
printf(a);//greatest common divisor
```

2 find S = a + aa + aaa + aaaa +
A = value between 1 and 9
There are n a n, which are entered by the user

​ ai = 0;
​ sum = 0;

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

}

3 for 10000000! How many zeros are there at the end
​ 2 * 5 10 * 20 = 200 2 5 2 2 5
​ 1 ~ 10000000 100 / 5 ... 0 20 / 5 ... 0 4 / 5 ... 4

That is, find how many factors in each number are 5

​ num = 0;
​ i = 1;
​ while(i <= 10000000)
​ {
/ / find the number of 5 factors in this i
/ / make sure this i can be divided by 5
​ //if(i % 5 == 0)
​ //{
​ j = i;//i you can't move, so you need to save this I
​ while(j % 5 == 0)
​ {
​ j = j / 5;
​ num++;
​ }
​ //}

​ i++;
​ }

4 the sum of consecutive positive integers. A positive integer may be expressed as
Sum of n consecutive positive integers
​ ru: 6 = 1 + 2 + 3 7 = 3 + 4
​ 15 = 1 + 2 + 3 + 4 + 5 = 4 + 5 + 6
​ = 7 + 8
Please enter a number by programming to find out all possible sequences
Note: it may not be
1. Brute force cracking
Just list all the sequences to see which is equal
2. If left right is small, it will be right+1. If left right is large, it will be left+1
Find the sum of all numbers between left and right to see if they are equal

​ int n;
​ scanf("%d",&n);
​ int left = 1,right = 2;
​ int sum = 3;

​ while(right <= n / 2 + 1)
​ {
If (sum < n) / / I want to stretch to the right
​ {
​ right++;
​ sum += right;
​ }
​ else if(sum > n)
​ {
​ sum -= left;
​ left++;
​ }
else / / equal
​ {
/ / the interval has
printf("interval is:% d~%d\n", left,right);
​ right++;
​ sum += right;
​ }
​ }

5 decompose a positive integer into prime factors
For example:
Enter 90
Print 90 = 2 * 3 * 3 * 5
Short division

​ int32 n;
​ scanf("%d",&n);
​ printf("%d = 1 ",n);
​ int32 i = 2;
​ for(;i <= n;)//i <= n
​ {
/ / we need to take out all the prime factors in this n
If (n% i = = 0) / / if the remainder is 0, it can be divided. At this time, i can be taken out
​ {
​ printf("* %d ",i);
/ / you still have a prime factor behind you. You still need to continue to execute it below
/ / n should be the prime factor without this
​ n = n / i;
/ / next, you should start with this i, so there is no need to go back
/ / consider duplicate results
​ continue;
​ }
​ i++;
​ }
​ printf("\n");

```6 Find all prime numbers within 10000
Prime: there are no factors other than 1 and itself
Divide by the square of this number
brute force

In actual work, we don't come like this
Open an array to hold all primes from 1 to 10000
After we get a number, we don't divide it from 2. We can know the answer by dividing all prime numbers smaller than it
```

7 find the last three bits of the 1024 power of 15
Take the last three every time
The last three digits of the final result are only related to the last three digits each time you multiply it

​ int s = 1,i = 0;
​ while(i < 1024)
​ {
​ s *= 15;
​ s = s % 1000;// Just take the last three
​ i++;
​ }

8 find all completions within 10000
A number has many factors - > n / 2
If the sum of all factors except its own factor is equal to this number
Then this number is the perfect number
​ 6 -> 1 2 3
1 + 2 + 3 = 6 is the perfect number
​ 8 -> 1 2 4
​ 1 + 2 + 4 != 8 this number is not complete

Enter the shared folder - > \ 192.168.31.87 (the address may change every day)

Static: static decoration
Modify global variables
Indicates that this global variable is only valid in this file
A project consists of several c .h file (there can only be one main)

There is only one main in a c project?
When compiling, the main function is the entrance and exit of the whole project
That is, without main, there will be no entrance and exit for this project

It was said in the original book that this sentence is right, but now strictly speaking, this sentence is wrong
The main function is just a default entry and exit
Since it is the default, I can change it

​ gcc 1.c -e hehe -nostartfiles
This 1 There is no main entry in C, but there is hehe
You think this hehe is the entrance now
Specify that the entry of the project is hehe, and the compiler will find the hehe function and regard it as the entry of the project
We still need to dig an exit for this project
Exit - > Exit

Modify local variables
The lifetime is the same as that of the global variable - > it lasts as the process continues (if this project dies, I won't have it)
Scope (valid only in a certain place) - > local

extern: keyword external declaration
It means that this thing is defined in other files. You can take it directly and use it
The variable modified by this keyword can only be declared and cannot be defined (initialization is not allowed)

Keywords: C

Added by jzhang1013 on Tue, 08 Feb 2022 03:11:56 +0200