The program has three types of structure
1. Sequential structure
2. Branch structure
3. Loop structure (usually used in combination with arrays)
While loop
while (conditional expression) {
Statement
}
Note: The conditional expression is true and the loop body is executed, and once the conditional expression is false, the loop stops.
Use while to print a multiple of 1~100 that is not 7 and does not contain a number of 7.
int i=1;
while (i<=100) {
if (i%10!=7 && i/10!=7&&i% 7!=0) {
printf ("%d\n", I);
}
i++;
}
4. Random number
Arc4random ()------Returns a random number
If you want a random integer within a [a, b] range, the formula: Arc4random ()% (b-a+1) +a;
The user outputs from the console a N,? Use while to print n random numbers (in the range of 30~70) to find the largest value in n random numbers.
int n = 0;
printf ("Enter a N:");
scanf ("%d", &n);
int max=0; Define MAX, global variables, and give Max character values outside the while
while (n >0) {
int random= arc4random ()% (70-30+1) +30;
printf ("%d\n", random);
if (Random>max) {
Max=random;
}
n--;
}
printf ("Max:%d\n", Max);
5. Break
The switch statement is out of the switch statement
Loop out of this layer in the loop body (usually with if)
6, continue
In the loop body: End this loop (the code behind continue is no longer executed), into the next loop (usually with if)
7. Do...while Cycle
do{
Statement
}while (conditional expression);
The loop body is executed before the loop condition is determined, and the loop ends when the condition is not satisfied.
8. For loop
for (loop variable initialization; loop condition; loop increment) {
Statement
}
Loop condition is true, loop body is executed
Use for to print out that the 1~100 is not a multiple of 7 and does not contain a number of 7.
for (int i = 1; i<=100; i++) {
if (i%10!=7 && i/10!=7&&i%7!=0) {//single digit is not 7,i%10!=7
printf ("%d\n", I);
}
}
9. Loop nesting
How to print how to print how to print
1 1 2) 3 1
1 2----Simple decomposition-------> 1 2 3 1 2 3 1 2
1 2 3 1 2 3 1 2 3
for (int i=1; i<4;i++) {
for (int j=1; j<=i; J + +) {
printf ("%d", j);
}
printf ("\ n");
}
99 Multiplication Table
for (int i=1; i<=9;i++) {
for (int j=1; j<=i; J + +) {
printf ("%dx%d=%-3d", j,i,j*i);
}
printf ("\ n");
}
A combination of three digits (0-9) may be printed (the group is composed of three digits).
int m=0;
for (int a = 1; a<10; a++) {
for (int b = 0; b<10; b++) {
for (int c = 0; c<10; C + +) {
M= A*100+b*10+c;
printf ("%d%d%d\n", a,b,c);
}
}
}
Attention:
For most common, usually used to know the loop of the number of loops
While is also very common, often used for loops that do not know the number of loops
Do...while is not particularly common, and is typically used for loops that need to be executed first.
Break jumps out of this layer loop, continue ends the loop, usually with if
C language 03 Loop structure