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: Statement 1; ... 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
When marking, you actually jump to the marked address to execute the code.
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 a small white, try to avoid using it
*Bootstrap thought
The gcc compiler uses an idea called bootstrap when developing
-
Will develop a subset compiler that contains only a small amount of c language, which is written in assembly language
-
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
-
After many generations, you can get the current gcc.
-
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
Using goto
Title: find the sum of odd numbers within a certain 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 the loop, and execute the conditions under the 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 } //As long as the expression is a legal expression 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
...
The loop exits 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 expression is true, all statements in curly braces will be executed.
No curly braces: the while statement can only control the following statement. When the expression is true, only the immediately following statement is 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, we can use it if it only tells us that the program is wrong, but does not tell us where it is wrong
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.
Title: the sum of multiples of 3 in a certain range
Exercise 2:
Find the sum of multiples of 3 within 10000
//Method 1: use the while statement #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: use goto statement #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; }
Title: find the number of daffodils
Exercise 2:
Find the number of daffodils in 100 ~ 999
Narcissus number: bits, tens, hundreds of cubes and for themselves
//Find the number of daffodils in 100 ~ 999. Narcissistic number //The cube of individual, ten and hundred and 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; }
Title: find the number of 1 in the register
Exercise 3:
Find out how many 1s (32bit) are in a register -------------- > find out how many 1s are in the binary of a decimal number
//How many 1s are there in the binary system for finding a decimal number /*Method 1: decimal to binary method: 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; printf("Please enter an integer:"); scanf("%d",&n); while (n) { if(1 == n%2) { ++num; } n = n/2; } printf("%d\n",num); return 0; }
//Method 2: n & (n-1) is applicable to both positive and negative integers. The number of 1s will cycle as many times as there are #include<stdio.h> int main() { int n,num = 0; printf("Please enter an integer:"); 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; printf("Please enter an integer:"); 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) */
4, do while statement
1. Grammatical form:
do { Statement 1; Statement 2; ... } while(expression);
2. Explanation of usage:
It is the same as while, and the expression is the same, except that while is judged before execution
do while will be executed once regardless of your conditions
3. Points needing attention:
Similar to the while statement, if there are no braces after do, only the following sentence will be recognized, and this statement may have problems
It is suggested that do write directly in curly braces to show sovereignty
int i=1,j=1;
do
i ++; // In the circulatory system
j ++; // Not in the circulatory system
while(i<5);
5, for loop statement
1. Grammatical form
for(Expression 1;Expression 2;Expression 3) { Circulatory body; }
2. Explanation of usage
At the beginning of the for loop, first go to expression 1 - > then judge the value of expression 2. If it is true - > execute the loop body - > execute expression 3
->Continue to judge expression 2 as true - > execute loop body - > execute expression 3 - > judge expression 2 as false - > Exit loop
3. Points needing attention
(1) Expression 1: the whole loop will be executed only once
(2) You don't have to write the three expressions in for, but there are two;; Not one less
(3) If expression 2 is not written, the condition is always true
(4) Expression 3 belongs to for, not to the loop body
4. About dead cycle
Both for and while can form an endless loop, with the same efficiency. There is no difference
for(; 😉; // Dead cycle
while(1); // Dead cycle
6, break and continue
1) break: end the loop and jump out of the loop body
while(1) { while(2) { break; //End while(2) } if(1) { break; // The end is while(1) } }
be careful:
break can also end the switch. After it matches the switch, it will only end the switch, not the loop
while(1) { switch(a) { case 1: break; //This break will match this switch //Then it will only end the switch, not the loop } }
2) continue: end this cycle and start the next one
Note the difference between while and for
int i = 88; while(i < 100) { if(i > 50) { continue; //No longer execute the following statements and start the next cycle. At this time, an endless cycle will be formed } i++; }
for(i = 0;i < 100;i++) { if(i > 50) { continue;//Do not execute the following statements and start the next cycle, but i + + still needs to be executed, because i + + belongs to for and does not belong to the loop body //Then there will be no dead cycle } i += 2; }
7, Topic exercise
Title: finding the greatest common divisor
1. Find the maximum common divisor and minimum common multiple of two numbers
//Find the maximum common divisor and the minimum common multiple of two numbers //Rolling Division: (15,10) - > (10,5) - > (5,0) - > the maximum common divisor is 5 //Violence solving method: find out all numbers of 1~b that can be divided by a and B, and assign the largest to variable t; #include<stdio.h> int main() { int a,b,temp,m,n; printf("Please enter two numbers:"); scanf("%d %d",&a,&b); //Judge whether a is greater than b, and if not, exchange the position if(a<b) { a = a^b; b = a^b; a = a^b; } m = a; n =b; while (a%b != 0) { temp = b; b = a%b; a = temp; } printf("The maximum common divisor is%d\n",b); printf("The least common multiple is%d\n",m*n/b); return 0; } /* Method 2: the violent solution method is not as efficient as the rolling division method int i,a,b,n,t; scanf("%d %d",&a,&b); if(a<b) { a = a^b; b = a^b; a = a^b; } n = b; while(n <= b) { if(a%i == 0 && b%i == 0) break; n--; } printf("The maximum common divisor is% d\n",t); printf("Minimum common multiple is% d\n",a*b/t); */
Title: find a+aa+aaa +
2 . Find S = a + aa + aaa + aaaa +
A = value between 1 and 9
There are n, a and N, which are entered by the user
//Find s = a + aa + aaa + aaaa + //A is a value between 1 and 9. There are n values. A and N are entered by the user //9 99 999 -> 9 9+9*10 9+99*10 #include<stdio.h> int main() { int a,n,s = 0,temp = 0; printf("Please enter a and n:"); scanf("%d %d",&a,&n); temp = a; for(int i = 0;i<n;i++) { s += temp; temp = a + temp*10; //printf("%d\n",temp); } printf("%d\n",s); return 0; }
Title: find a number with 0 numbers at the end of factorial
- Ask 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
//Ask for 10000000! How many zeros are there at the end of (factorial) //Idea: there are as many zeros as there are 5's #include<stdio.h> int main() { int i,j,num = 0; for(i = 5;i <= 10000000; i++) { j = i; //Where it is easy to ignore, the value of i cannot change after completing while while(j%5==0) { ++num; j = j/5; } } printf("10000000!At the end%d 0\n",num); return 0; }
Title: find sequences that meet the conditions
-
The sum of consecutive positive integers. A positive integer may be expressed as the sum of n consecutive positive integers
For example: 6 = 1 + 2 + 3 7 = 3 + 4
15 = 1 + 2 + 3 + 4 + 5 = 4 + 5 + 6 = 7 + 8
Please program and enter a number to find out all possible sequences
Note: it may not be//Enter a positive integer, which is expressed as the sum of n consecutive positive integer sequences //For example, 6 = 1 + 2 + 3, 7 = 3 + 4 //Violence solving method: list all sequences to see which is equal //Expansion method: left When right is small, it will be right+1, and when it is large, it will be left+1 // Find the sum of all numbers between left and right to see if they are equal #include<stdio.h> int main() { int n,j,left,right = 1,sum = 1; printf("Please enter a number greater than 2:"); scanf("%d",&n); for(left = 1;left<=n/2;left++) { loop: if(sum==n) { for(j=left;j<=right;j++) printf("%d,",j); printf("\n"); } if(sum<n) { right++; sum = sum+ right; goto loop; } sum -= left; } return 0; } /*Teacher code int n; scanf("%d",&n); int left = 1,right = 2; int sum = 3; while(right <= n / 2 + 1) { if(sum < n)//Stretch to the right { right++; sum += right; } else if(sum > n)//Shrink to the left { sum -= left; left++; } else //equal { //There's an interval printf("The interval is:% d~%d\n",left,right); right++; sum += right; } }*/
Topic: positive integer factorization prime factor
- Decompose a positive integer into prime factors
For example, enter 90
Print 90 = 2 * 3 * 3 * 5
//Decompose a positive integer into prime factors //For example, enter 90 to print 90 = 2 * 3 * 3 * 5 short division //Nested loop in loop = a loop + continue statement = a loop + loop: goto loop; #include<stdio.h> int main() { int i = 2,n,t; printf("Please enter a positive integer:"); scanf("%d",&n); printf("%d = 1",n); t = n; while(1!=t) //Except when the last quotient is one { while(t%i == 0) //If the remainder is zero and i is a factor, print i { printf("* %d ",i); t = t/i; } //Otherwise, i + +, test the next number ++i; } printf("\n"); return 0; } /*Teacher Code: int n; scanf("%d",&n); printf("%d = 1 ",n); int i = 2; for(;i <= n;)//i <= n { //We're going to take out all the prime factors in this n if(n % i == 0)//If the remainder is 0, then 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 down //n There should be no prime factor after this is taken out n = n / i; //You should start with this i, so there's no need to go back //Consider repeated results continue; } i++; } printf("\n"); */
- Decompose a positive integer into prime factors
Title: find all prime numbers within 10000
-
Find all prime numbers within 10000
// Find all primes within 10000. Primes: there are no factors other than 1 and itself //Method 1: brute force cracking, except for the prescription of this number //Method 2: Open an array to hold all primes from 1 to 10000 //After we get a number, we can know the answer by dividing all prime numbers smaller than it #include<stdio.h> int main() { int i,j; //External circulation, 1 ~ 10000 for(i = 2;i <= 10000;i++) { //Inner loop, i divided by number 2~i-1 for(j = 2;j <= i-1;j++) { //Judge whether i can divide j if(i%j==0) { break; } } //Judge whether it is a prime number (the reason for jumping out of the loop is that i can be divided by 2~i-1, //Still can't find the number i can be divided by) if(j == i) printf("%d\t",i); } printf("\n"); return 0; } /*Areas for improvement for(j = 2;j <= i-1;j++) The condition can be changed to j < = I / 2 */
Title: find the 3 bits at the end of the 1024 power of 15
7. Find the last 3 bits of the 1024 power of 15
// Find the last 3 bits of the 1024 power of 15 //Idea: Take the last three every time //The last three digits of the final result are only related to the last three digits of each multiplication #include<stdio.h> int main() { int s = 1; for(int i = 1;i<=1024;i++) { s *= 15; s %= 1000; } printf("15 The last 3 bits of 1024 power are%d\n",s); return 0; }
Title: find the perfect number in a certain range
- Find all completions within 10000
//Find all completions within 10000 //Perfect number: the sum of all factors except its own factor is equal to the number itself //6 - > 1 * 2 * 3, 1 + 2 + 3 = 6 is the perfect number //8 -> 1 * 2 * 4 , 1 + 2 + 4 != This number is not perfect #include<stdio.h> int main() { int i,j,sum; for(i = 1;i < 10000; i++) { sum = 0; //Find factor for(j = 1;j < i; j++) { if(0 == i%j) sum += j; } if(i == sum) printf("%d\t",i); } printf("\n"); return 0; }