Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Loop profile

Organizing programs is another aspect of working with data, getting them to do the steps in the right order. C has a number of language features that help you accomplish the task of organizing programs. One such feature is loops, which repeat behavior and make programs more interesting and powerful.

Classification of cycles

Since the loop structure exists in a large number of programs, so in order to achieve the function of the program, there are four main loop statements or structures.

  1. While statement;
  2. The do… While statement;
  3. For statement;
  4. Nested loop structure.

Matters needing attention

Don’t let your program go into an infinite loop, which will cause your program to crash after exhausting the computing resources provided by the system.

True value problem

In C, true/false values are always represented by variables of type int.

C99 has a new _Bool type for this type of variable named after The British mathematician George Boole, who developed algebraic representation of logic and solving logic problems. _

_ Variables that represent true or false in programming are called Boolean variables, so _Bool is the type name of a Boolean variable in C.

Boo variables can only store 1(true) or (false). If you assign a non-zero value to a Bool variable, it will be set to 1. This reflects that C treats all non-zero values as true.

While loop

(1) Loop syntax

while(cyclic condition) {// Statements that can be executed
}
Copy the code

(2) The execution process of the cycle

(3) Usage scenarios of the While loop

In a program, the statement is used when part of a particular statement needs to be looped through under a loop condition. This cycle is in many cases like we’re doing our homework. The amount of homework we have is different each day, and there is no way to set the quota of how much to write each day.

But one rule we know is that if you don’t finish writing, you keep writing until you finish writing. The circular judgment condition here is that the homework is not done. So this is going to be a while loop. One condition is checked each time, and if the condition is met, the loop continues.

(4) The use of cyclic examples

#include <stdio.h>

int main()
{
    int x = 10;

    while(x>0)
    {
        printf("Number: %d\n",x);
        x--;
    }
    return 0;
}
Copy the code





​ Number: 10 ​ Number: 9 ​ Number: 8 ​ Number: 7 ​ Number: 6 ​ Number: 5 ​ Number: 4 ​ Number: 3 ​ Number: 2 ​ Number: 1

(5) Summarize while

The while statement conditions and then decides whether or not the contents of the parenthesized loop body should be executed.

If the loop condition is met, it executes. Executes the contents of the program loop body. If not, the loop is not executed. That is, if the loop condition is met the first time, and the result is not met, then the contents of the loop statement are not executed once and are ignored.

Tip: This statement sometimes has a special use, is when writing MCU programs, you sometimes need to use polling mode to collect port information, that is, need to constantly scan the status of each port. At this point, the program uses while(1). This statement is a loop that never stops. The program executes the contents of the program loop over and over again.

Second, for loop

(1) Syntax of the for loop

for(Control loop variables; Cyclic judgment condition; Cyclic variable change) {// Loop the statement
}


Copy the code

(2) Usage scenarios of the for loop

Use this statement when we can determine the control conditions for the loop. The cycle here is usually a finite cycle. We all know the story of Gauss calculating the sum from 1 to 100 as a child. The for loop can then be used to solve repetitive, consistent tasks with fixed numbers at the beginning and end. So we’re just adding up the number 1 all the way to 100. This is an application of the for loop.

The for statement uses three expressions, separated by a semicolon, to control the loop. The initialize expression is executed only once before the for statement is executed; The test expression is then evaluated, and the loop is executed once if the expression is true (or non-zero); Next, evaluate the UPDATE expression and check the test expression again. The for statement is an entry conditional loop that determines whether the loop is executed before it is executed. Therefore, the for loop may not be executed at all. The statement section can be a simple statement or a compound statement.

Form: for (initialize; test; The update) {

statement;

}

Repeat the statement section until test is false or 0

Example:

for(n = 0; n < 10; n++){

printf(“%d %d \n”,n,n*2+1);

}

(3) Examples of for

#include <stdio.h>

int main(a)
{
    for (int i = 0; i < 10; i++)
    {
        printf("No. %d: Hello C Language! \n", i);
    }

    return 0;

}


No. 0: Hello C Language!
No. 1: Hello C Language!
No. 2: Hello C Language!
No. 3: Hello C Language!
No. 4: Hello C Language!
No. 5: Hello C Language!
No. 6: Hello C Language!
No. 7: Hello C Language!
No. 8: Hello C Language!
No. 9: Hello C Language!

Copy the code

Third, do – the While

(1) overview

Both the while and for loops are entry conditional loops that check test conditions before each iteration of the loop

C also has exit-condition loops, which check test conditions after each iteration of the loop, ensuring that the contents of the loop body are executed at least once. This loop is called a do while loop.

(2) Usage scenarios of the do-while loop

When the statement inside the loop body needs to be executed once, and then whether to execute the statement again. It’s a bit like when you eat, you taste the food and then decide if you want to eat more.

(3) General form

do

​ statement

while (expression);

The do while loop does not execute the test condition until the body is finished executing, so execute the body at least once;

A for loop or a while loop executes the test condition before executing the body of the loop.

Form:

do

​ statement;

while();

Example:

do

​ scanf(“%d “,&num);

while(num ! = 20);

4. Nested loops

You can imagine a Russian nesting doll, circulating nesting

(1) Multiplication table

#include <stdio.h>



int main(void)

{

  for (int i = 1; i < 10; i++)

  {

    for (int j = 1; j < i+1; j++)

   {

     int sum = i * j;

      printf("%d * %d = %d ",i,j,sum);
   }

   printf("\n"); 

    

  }

  



  return 0;

}






1 * 1  = 1 
2 * 1  = 2 2 * 2  = 4
3 * 1  = 3 3 * 2  = 6 3 * 3  = 9
4 * 1  = 4 4 * 2  = 8 4 * 3  = 12 4 * 4  = 16
5 * 1  = 5 5 * 2  = 10 5 * 3  = 15 5 * 4  = 20 5 * 5  = 25
6 * 1  = 6 6 * 2  = 12 6 * 3  = 18 6 * 4  = 24 6 * 5  = 30 6 * 6  = 36
7 * 1  = 7 7 * 2  = 14 7 * 3  = 21 7 * 4  = 28 7 * 5  = 35 7 * 6  = 42 7 * 7  = 49 
8 * 1  = 8 8 * 2  = 16 8 * 3  = 24 8 * 4  = 32 8 * 5  = 40 8 * 6  = 48 8 * 7  = 56 8 * 8  = 64
9 * 1  = 9 9 * 2  = 18 9 * 3  = 27 9 * 4  = 36 9 * 5  = 45 9 * 6  = 54 9 * 7  = 63 9 * 8  = 72 9 * 9  = 81
Copy the code

5. Key concepts

Loop is a very powerful tool, can only be used, more exercise their programming thinking

No need to memorize

Test condition, the result is 0 times false, non-0 represents true

6. Programming exercises

1.c

#include <stdio.h>
#define LEN 26

int main(void)
{
    int n;
    char letters[LEN];
    Int [] arr = {};
    //c is int arr[] = {};

    / / value ascribed
    for (n = 0; n < LEN; n++)
    {
        letters[n] = 'a' + n;
    }
    printf("Here are %d letters:\n", LEN);
    
    / / after traversal
    for (n = 0; n < LEN; n++)
    {
        printf("%-3c", letters[n]);
    }
    
    return 0;

}


Here are 26 letters:
a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r  s  t  u  v  w  x  y  z 
Copy the code

2.c

#include <stdio.h>
#define N 5

int main(void)
{
    int i, j;

    for (i = 1; i <= N; i++)
    {
        for (j = 1; j <= i; j++)
        {
            printf("$");
        }
        printf("\n");
    }

    return 0; } That's what the multiplication table looks likeCopy the code

3.c

#include <stdio.h>
#define N 6

int main(void)
{
    int i, j;

    for (i = 1; i <= N; i++)
    {
        for (j = 0; j < i; j++)
        {
            printf("%c".'F' - j);
        }
        printf("\n");
    }

    return 0;
}



F
FE
FED
FEDC
FEDCB
FEDCBA
Copy the code

4.c

#include <stdio.h>
#define N 6

int main(void)
{
    int i, j;
    char ch = 'A';

    for (i = 1; i <= N; i++)
    {
        for (j = 1; j <= i; j++)
        {
            printf("%c", ch++);
        }
        printf("\n");
    }
    
    return 0;

}
Copy the code

5.c

#include <stdio.h>

int main(void)
{
    int i, j;
    char ch;

    printf("Please enter a upper letter: ");
    scanf("%c", &ch);

    int length = ch - 'A';
    // loop number;
    printf("The pyramid of %c is:\n", ch);
    for (i = 0; i <= length; i++)
    {
        char t = 'A' - 1;
        for (j = 0; j < length - i; j++)
        {
            printf("");
        }
        // the number of Spaces on the left of ↑;
        for (j = 0; j <= i; j++)
        {
            printf("%c", ++t);
        }
        //↑ prints incremental letters;
        for (j = 0; j < i; j++)
        {
            printf("%c", --t);
        }
        //↑ prints decrement letters
        printf("\n");
    }

    return 0;
}

Copy the code

6.c

#include <stdio.h>

int main(void)
{
    int i, upper, lower;

    printf("Please input the upper limits: ");
    scanf("%d", &upper);
    printf("Please input the lower limits: ");
    scanf("%d", &lower);

    printf("%-10s%-10s%-10s\n"."number"."square"."cube");
    for (i = lower; i <= upper; i++)
    {
        printf("%-10d%-10d%-10d\n", i, i * i, i * i * i);
    }
    printf("Done.\n");

    return 0;
}

Copy the code

7.c

#include <stdio.h>
#include <string.h>
#define LEN 20

int main(void)
{
    int i;
    char str[LEN];

    printf("Please enter a word: ");
    scanf("%19s", str);
    printf("The word is:\n");
    printf("%s\n", str);

    printf("Reversing the word is:\n");
    for (i = strlen(str) - 1; i >= 0; i--)
    {
        printf("%c", str[i]);
    }

    return 0;
}

Copy the code

8.c

#include <stdio.h>

int main(void)
{
    double i, j;

    printf("Please enter two numbers (q to quit): ");
    while (scanf("%lf %lf", &i, &j) == 2)
    {
        printf("(%g - %g) / (%g * %g)", i, j, i, j);
        printf(" = %g\n", (i - j) / (i * j));
        printf("You can enter again (q to quit): ");
    }
    printf("Done.\n");

    return 0;
}

Copy the code

9.c

#include <stdio.h>

double cal(double n, double k);

int main(void)
{
    double i, j;

    printf("Please enter two numbers (q to quit): ");
    while (scanf("%lf %lf", &i, &j) == 2)
    {
        printf("(%g - %g) / (%g * %g)", i, j, i, j);
        printf(" = %g\n", cal(i, j));
        printf("You can enter again (q to quit): ");
    }
    printf("Done.\n");

    return 0;
}

double cal(double n, double k)
{
    return (n - k) / (n * k);
}

Copy the code

10.c

#include <stdio.h>

int main(void)
{
    int upp, low, i;

    printf("Enter lower and upper integer limits: ");
    while ((scanf("%d %d", &low, &upp) == 2) && (upp > low))
    {
        int sum = 0;
        for (i = low; i <= upp; i++)
        {
            sum += i * i;
        }
        printf("The sums of the squares ");
        printf("from %d to %d is %d\n", low * low, upp * upp, sum);
        printf("Enter next set of limits: ");
    }
    printf("Done\n");

    return 0;
}

Copy the code

11.c

#include <stdio.h>
#define N 8

int main(void)
{
    int i, a[N];

    printf("Please enter 8 numbers:\n", N);
    for (i = 0; i < N; i++)
    {
        scanf("%d", &a[i]);
    }
    printf("Reverse order printing 8 numbers:\n", N);
    for (i = N - 1; i >= 0; i--)
    {
        printf("%-3d", a[i]);
    }

    return 0;
}

Copy the code

12.c

#include <stdio.h>

int main(void)
{
    int i, n;

    printf("Please enter a number (<= 0 to quit): ");
    while ((scanf("%d", &n) == 1) && (n > 0))
    {
        double res1 = 0.0;
        double res2 = 0.0;
        for (i = 1; i <= n; i++)
        {
            res1 += 1.0 / i;
            if (i % 2= =1)
            {
                res2 += 1.0 / i;
            }
            else
            {
                res2 -= 1.0/ i; }}printf("1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 +...");
        printf("sum are %g\n", n, res1);
        printf("1.0-1.0/2.0 + 1.0/3.0-1.0/4.0 +...");
        printf("sum are %g\n", n, res2);
        printf("The sum of the first %d items of the two sequences is %g\n", n, res1 + res2);
        printf("\nYou can enter again (<= 0 to quit): ");
    }
    printf("Done.\n");

    return 0;
}

Copy the code

13.c

#include <stdio.h>
#define N 8

int main(void)
{
    int a[N], i;
    int val = 2;

    for (i = 0; i < N; i++)
    {
        a[i] = val;
        val *= 2;
    }
    i = 0;
    printf("Here are the results for array:\n", N);
    do
    {
        printf("%d ", a[i++]);
    } while (i < N);
    printf("\nDone.\n");

    return 0;
}

Copy the code

14.c

#include <stdio.h>
#define N 8

int main(void)
{
    int i;
    double a[N], b[N];

    printf("Please enter %d numbers:\n", N);
    for (i = 0; i < N; i++)
    {
        scanf("%lf", &a[i]);
    }
    b[0] = a[0];
    for (i = 1; i < N; i++)
    {
        b[i] = a[i] + b[i - 1];
    }
    printf("Here are the results for array a:\n");
    for (i = 0; i < N; i++)
    {
        printf("%-3g", a[i]);
    }
    printf("\nHere are the results for array b:\n");
    for (i = 0; i < N; i++)
    {
        printf("%-3g", b[i]);
    }
    printf("\nDone.\n");

    return 0;
}

Copy the code

15.c

#include <stdio.h>
#define LEN 255

int main(void)
{
    int i = 0;
    char input[LEN];

    printf("Please enter a string:\n");
    do
    {
        scanf("%c", &input[i]);
    } while(input[i] ! ='\n' && ++i && i < LEN);

    printf("Reversing print the string is:\n");
    for (i--; i >= 0; i--)
    {
        //↑ Avoid printing newlines;
        printf("%c", input[i]);
    }
    printf("\nDone.\n");

    return 0;
}

Copy the code

16.c

#include <stdio.h>
#define RATE_SIMP 0.10
#define RATE_COMP 0.05
#define INIT_AMT 100.0

int main(void)
{
    int years = 0;
    double daphne = INIT_AMT;
    double deirdre = INIT_AMT;

    do
    {
        daphne += RATE_SIMP * INIT_AMT;
        deirdre += RATE_COMP * deirdre;
        years++;
    } while (deirdre < daphne);
    printf("Investment values after %d years:\n", years);
    printf("Daphne: $%.2f\n", daphne);
    printf("Deirdre: $%.2f\n", deirdre);
    printf("Deirdre(invest) > Daphne(invest)\n");

    return 0;
}


Copy the code

17.c

#include <stdio.h>
#define TAX 0.08

int main(void)
{
    int i = 0;
    double Chuckie = 100.0;

    do
    {
        i++;
        Chuckie += Chuckie * TAX;
        Chuckie -= 10;
        printf("(%d)account:%g.\n", i, Chuckie);
    } while (Chuckie > 9);
    // if the balance is less than 9, it will not be enough for the next year;
    printf("After %d years:\n", ++i);
    printf("Chuckie has taken all of the money! \n");

    return 0;
}

Copy the code

18.c

#include <stdio.h>

int main(void)
{
    int i = 1;
    int friends = 5;

    while (friends < 150)
    {
        printf("At %d weeks, Rabnud has", i);
        printf("%4d friends.\n", friends);
        friends = 2 * (friends - i++);
    }
    printf("At %d weeks, over Dunbar's number(150).\n", i);

    return 0;
}

Copy the code