Getting started with C – loop

Time:2020-3-11

I. circulation

Input a number and output several digits

#include  

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

2、 While loop

The circulatory body should have the opportunity to change the conditions and avoid the dead circulation

The meaning of while loop is: when the condition is satisfied, repeat the statement inside the loop continuously

Before loop execution, judge whether to continue the loop, so it is possible that the loop has not been executed once

Let’s see if the code above is a bit redundant. Let’s change it, but there is still a problem that there are no digits when entering 0

#include  

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

3、 Do while loop

Do not check when entering the cycle, and check whether the conditions are met after another round,At least one loopThe specific format is as follows

do{
    Circulatory body
}Whlie (condition)

Algorithm of digit number

  1. User input x
  2. Initialize n to 0
  3. X = x / 10, bits removed
  4. n++
  5. If n > 0, go back to 3
  6. Otherwise, n is the result

Change the code above

#include  

int main()
{
    int x;
    int n = 0;
    scanf("%d" , &x);
    do{
        n++;
        x /= 10;
    }while(x > 0);
    
    printf("%d\n",n);
    return 0;   
}

Enter 0 to display the number of digits,

4、 Cycle calculation

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

Guessing game

Let the computer think of a number, and then let the user guess. Every time the user enters an array, he will be told whether it is large or small, until the user guesses it, and how many times he guesses it

Here we use a random number

#include 
#include 
#include 

int main(){
    srand(time(0));
    int a = rand();
    
    //But this random number is a little big. Here we take the remaining 100 
    printf("%d\n" , a%100);
    
    return 0;
}

The specific implementation is as follows:

#include 
#include 
#include 

int main(){
    srand(time(0));
    
    int number = rand()%100+1;
    int a = 0;
    int count = 0;
    //To cheat 
    // printf("%d\n",number); 
    
    while(number != a){
        Printf ("parent, please enter a number within 100:");
        scanf("%d", &a);
        if(a > number){
            Printf ("pro, you have entered a large number \ n");
        }else if(a < number){
            Printf ("pro, the number you entered is smaller \ n");
        }
        count++; 
    }
    Printf ("Congratulations, the input is correct! You have entered% d times ", count";
    return 0;
}

Arithmetic average

Let the user enter a series of positive integers, then enter – 1 for the end of the input, and then calculate the average of these numbers

int number;
    int count = 0;
    int sum = 0;
    
    Printf ("please enter the number (- 1 end):");
    scanf("%d" , &number);
    while(number != -1){
        Printf ("please enter the number (- 1 end):");
        count++;
        sum += number;
        scanf("%d" , &number);
    }
    
    Printf ("you have entered% d times in total, with an average of% d", count, sum / count);

5、 Integer inversion

Do% 10 on an integer to get its single digit

If you do the / 10 operation on an integer, remove its single digits

Find: enter a positive integer, and enter the number in reverse order

int number;
    int digit;
    int ret = 0;
    Printf ("please enter number:");
    scanf("%d" , &number) ;
    
    while(number != 0){
        digit = number%10;
        //printf("%d",digit);
        ret = ret * 10 + digit;
        printf("x=%d,digit=%d,ret=%d\n", number, digit, ret);
        number /= 10;
    }
    printf("%d",ret);

6、 For loop

For loop is like a counting loop. Set a counter, initialize it, and then repeat the loop body before the counter reaches a certain value. For each cycle, the calculator adjusts in a certain step.

Calculate n!

#include 

int main(){
    int n;
    scanf("%d" , &n);
    int fact = 1;
    
//  for(int i = 1; i<=n; i++){
//      fact *= i;
//  }
    
    for(int i = n; i>1; i--){
        fact *= i;
    }
    
    printf("%d!=%d" , n , fact);
    
    return 0;
}

Calculation and selection of cycle

For (initial action; condition; action of each round){

Circulatory body;

}

Every expression in for can be omitted, semicolon cannot be omitted

#include 

int main(){
    int i;
    for(i = 0; i<5; i++){
        printf("i=%d\n" , i);
    }
    Printf ("\ nlast I =% d \ n", I);
    
    return 0;
}
i=0
i=1
i=2
i=3
i=4
The last i=5
  1. If there are fixed times, use for loop
  2. If you have to do it once, use do? While
  3. While for other cases

7、 Cycle control

Prime: a number that can only be divided by 1 and itself, excluding 1

int x;
    scanf("%d" , &x);
    int i;
    int isPrime = 1;
    for(i=2; i

Nested loop

Prime numbers within 100

#include  

int main(){
    int x;
    
    for( x=1; x<=100; x++){
        int i;
        int isPrime = 1;
        for(i=2; i

You can also do this, and you can work out 50 prime numbers

#include  

int main(){
    int x;
    int cnt = 0;
    // for( x=1; cnt<50; x++){
    x = 1;
    while(cnt < 50){
        int i;
        int isPrime = 1;
        for(i=2; i

Jump out of a nested loop

Break and continue can only loop on the layer where they are,

Goto: jump directly to your designated location

Coin up

How to use dimes 1, 2 and 5 to get a sum of less than 10 yuan,Relay break, too much trouble

int x;
    int exit = 0;
    int one, two, five;
    Printf ("please enter amount:"); 
    scanf("%d", &x);
    for(one = 1; one < x *10; one++){
        for(two=1; two < x*10/2; two++){
            for(five=1; five < x*10/5; five++){
                if(one + two*2 + five*5 == x*10){
                    Printf ("can be composed of% d 1 corners and% D 2 corners and% d 5 corners as% d yuan \ n", one, two, five, x);
                    exit = 1;
                    break;
                }
            }
            if (exit == 1) break;
        }
        if (exit == 1) break;
    
    }

Goto, you can use this when there are multiple loops, and do not use it when there are others

#include  

int main(){
    int x;
    int one, two, five;
    Printf ("please enter amount:"); 
    scanf("%d", &x);
    for(one = 1; one < x *10; one++){
        for(two=1; two < x*10/2; two++){
            for(five=1; five < x*10/5; five++){
                if(one + two*2 + five*5 == x*10){
                    Printf ("can be composed of% d 1 corners and% D 2 corners and% d 5 corners as% d yuan \ n", one, two, five, x);
                    //Jump directly to your designated position 
                    goto out;
                }
            }
        }
    
    }
out:
    return 0;
}

8、 Cyclic application

Sum of the first n terms

$$
f(n) = 1+1/2+1/3 +….+1/n
$$

#include  

int main(){
    int n;
    int i;
    double sum = 0.0;
    
    scanf("%d" , &n);
    
    for(i=1; i<=n; i++){
        sum += 1.0/i;
        printf("%f\n", sum);
    }

    return 0;
}

But what about this?
$$
f(n)=1-1/2+1/3-1/4+…+1/n
$$
There are many ways to do this. Here I wrote one myself

#include  

int main(){
    
    int n;
    int i;
    double sum = 0.0;
    
    scanf("%d" , &n);
    
    for(i=1; i<=n; i++){
        if(i%2 == 0){
            sum -= 1.0/i;
        }else{
            sum += 1.0/i;
        }
        printf("%f\n", sum);
    }

    return 0;
    
}

Integer factorization

  1. Input a non negative integer and output each digit of it in positive order
  2. Input: 1314
  3. Output: 1 3 1 4
#include  

int main(){

    int x;
    Printf ("enter any number of digits: \ n");
    scanf("%d" , &x);

    //Number of records
    int mask = 1;
    //The entered value is assigned to t, which is used to record the number of digits of the input number
    int t = x;
    while( t > 9){
        t /= 10;
        mask *= 10;
    }


    //The value entered by the user and the number of digits of the value entered by the user
    printf("x=%d, mask=%d\n",x, mask );

    do{
        int d = x / mask;

        printf("%d",d );
        //The last bit does not need to output space
        if (mask > 9)
        {
            printf(" ");
        }

        //Get his single digit
        x %= mask;
        //Remove its single digit
        mask /= 10;

    }while( mask >0);

    printf("\n");


    return 0;
}

greatest common factor

  1. Input two numbers a and B, and output their greatest common divisor
  2. Input: 12 18
  3. Output: 6

General calculation

int a,b;
    int min;

    Printf ("please enter two numbers:");
    scanf("%d %d" , &a, &b);
    if(a < b){
        min = a;
    }else{
        min = b;
    }

    int ret = 0;
    int i;
    for (i = 1; i <= min; i++)
    {
        if ( a%i == 0)
        {
            if ( b%i == 0)
            {
                ret = i;
            }
        }
    }

    Printf (the maximum common divisor of% D and% d is% d \ n ", a, B, RET);

But there’s more

  1. If B is equal to 0, the calculation ends, and a is the greatest common divisor
  2. Otherwise, calculate the remainder of a divided by B so that a equals B and B equals that remainder
  3. Back to step one
a b T (remainder)
12 18 12
18 12 6
12 6 0
6 0

The code is as follows:

#include  

int main(){

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

    while(b != 0){
        t = a % b;
        a = b;
        b = t;121
        printf("%d,%d\n", a ,b);
    }

    Printf ("the maximum common divisor is% d \ n", a);

    return 0;
}