2021-09-06 the fourth day of C language learning (cycle)

Posted by digitalbart2k on Mon, 06 Sep 2021 21:27:58 +0200

C control statement: loop

This paper mainly studies the following contents:

  • Keywords: for, while, do while
  • Operators: <, >, > =, < =, = =, + =, * =, - =, / =,%=
  • Functions: fabs()
  • C language has three loops: for, while, do while
  • Use relational operators to build expressions that control loops
  • Other Operators
  • Loop common arrays
  • Write a function with a return value

while Loop

#include<stdio.h>
int main(void)
{
	int n = 5;
	while (n < 7)
	{
		printf("n = %d\n",n);
		n++;
		printf("Now n = %d\n",n);	
	}
	printf("The loop has finished.\n");

	return 0;
}

The output results are as follows:

n = 5
Now n = 6
n = 6
Now n = 7
The loop has finished.

The general form of the while loop is as follows:

while (expression)
	statement

The statement part can be a simple statement ending with a semicolon or a compound statement enclosed in curly braces.
Expression mostly uses key expressions. Expression is the comparison between values, and any expression can be used. If expression is true (or more generally, non-zero), the statement part is executed once, and then the expression is judged again. As long as the expression judgment is not false, the statement part is executed all the time, and each cycle is called an iteration.

  • When to abort a while loop
    Make it clear that the decision to abort or continue the loop is made only when the test condition is evaluated. In the above program, when running to the second cycle, n obtains 7 for the first time, but the program does not exit at this time. End this cycle after printing the value of N at this time, and then conduct the next test condition evaluation, and then exit the cycle.
  • while: entry condition loop
    A while loop is a conditional loop that uses an entry condition. Conditional means that the execution of the statement part depends on the conditions described by the test expression, such as (index < 5). The expression is an entry condition, which must be met before entering the loop body.
  • Grammar points
    Note that the individual statement after the while loop test condition is the loop part (simple statement or compound statement)
#include<stdio.h>
int main(void)
{
	int n = 0;
	while (n < 3)
		printf("n is %d\n",n);
		n++;
	printf("That's all this program does\n");
	return 0;
}

This is a terrible infinite loop program:

n is 0
n is 0
n is 0
n is 0
n is 0
n is 0
n is 0
...

Although we indented the statement n + +, we did not enclose it in curly braces with the previous statement. Therefore, only the first statement following the test condition is part of the loop, and the value of variable n never changes.
We are paying attention to the following situation:

while(scanf("%d",&num == 1);

The while loop is directly followed by a semicolon after the test condition, indicating that the loop part is an empty statement. As long as our input is an integer, scanf will return 1. The test condition is true and the loop part is empty. The program will directly read the next input until we enter a non integer.

Compare sizes with relational operators and expressions

while loops often rely on test expressions for comparison. Such expressions are called relational expressions, and the operators appearing in relational expressions are called relational operators.
Table: relational operators:

operatormeaning
<less than
>greater than
>=Greater than or equal to
<=Less than or equal to
!=Not equal to

Note that you cannot compare strings with relational operators.

  • Truth value
    In C, the expression must have a value, and the relationship expression is the same. For C, the value of true expression is 1, false expression is 0;
while(1)
{
	...
}

In this case, the program will cycle all the time. In general, all non-zero values are considered true, and only 0 is considered false.

  • New_ Bool type
    In C language, variables of type int have always been used to represent true and false. C99 adds a new variable for this type_ Bool type.
    Variables of this type can only store 1 or 0. If you assign other non-zero values to_ Bool type variable, which will be set to 1.
//Use_ Variable of type Bool
#include<stdio.h>
int main(void)
{
    long num;
    long sum = 0L;
    _Bool input_is_good;
    printf("Please enter an integer to be summed");
    printf("(q to quit):");
    input_is_good = (scanf("%ld",&num) == 1);
    while (input_is_good)
    {
        sum = sum + num;
        printf("Please enter next integer (q to quit):");
        input_is_good = (scanf("%ld",&num) == 1);
    }
    printf("Those integers sum to %ld.\n",sum);

    return 0;

}

In this program:

input_is_good = (scanf("%ld",&num) == 1);

scanf obtains the return value according to our input, and then judges whether it is equal to 1 according to the return value. If yes, it returns true, and if not, it returns false.

for loop

Three behaviors are involved in creating a loop that repeats a fixed number of times:
1. The counter must be initialized;
2. Compare the counter with the limited value;
3. Increment the counter at each cycle.
In the for loop, the above three behaviors (initialization, test and update) are combined:

// sweetie2.c -- count loop using the for loop
#include<stdio.h>
int main()
{
    const int NUMBER =22;
    int count;

    for (count =1 ;count <= NUMBER; count++)
    {
        printf("Be my Valentine!\n");
    }

    return 0;
}

There are three expressions in parentheses after the keyword, separated by a semicolon. The first expression is initialized and will only be executed once at the beginning of the for loop. The second expression is a test condition. The expression is evaluated before the loop is executed. If the expression is false, the loop ends. The third expression is updated and evaluated at the end of each loop.
Note that in the above program, the final count value is 23.

Exit condition cycle: do while

While loop and for loop are both entry condition loops, and do while is exit condition loop, that is, check the test condition after each iteration of the loop, which can ensure that the contents in the loop body are executed at least once. This loop is called a do while loop.

/*do_while.c --Outlet condition cycle*/
#include<stdio.h>
int main()
{
    const int secret_code =13;
    int code_entered;
    do
    {
            printf("To enter the triskaidekaphobia therapy club,\n");
            printf("Please enter the secret code number:");
            scanf("%d",&code_entered);
    } while (code_entered != secret_code);
    printf("Congratulations! You are cured!\n");

    return 0;
}

Note that the do while loop ends with a semicolon. The test condition will not be executed until the loop is executed at least once.

To enter the triskaidekaphobia therapy club,
Please enter the secret code number:12
To enter the triskaidekaphobia therapy club,
Please enter the secret code number:14
To enter the triskaidekaphobia therapy club,
Please enter the secret code number:13
Congratulations! You are cured!

Nested loop

/*rowsl.c --Using nested loops */
#include<stdio.h>
#define ROWS 6
#define CHARS 10
int main()
{
    int row;
    char ch;

    for(row = 0;row < ROWS;row++)		//Outer circulation
    {
        for(ch = 'A';ch<('A'+CHARS);ch++)		//Internal circulation
            printf("%c",ch);
        printf("\n");
    }

    return 0;
}

After running the program, the output is as follows:

ABCDEFGHIJ
ABCDEFGHIJ
ABCDEFGHIJ
ABCDEFGHIJ
ABCDEFGHIJ
ABCDEFGHIJ

The internal cycle is executed 6 times and the internal cycle is executed 10 times.

Example of a loop using the return value of a function

To write a function with a return value, you should complete the following:

  • 1. When defining a function, determine the return type of the function
  • 2. Use the keyword return to indicate the value to be returned
double power(double n,int p) //Returns a value of type double
{
	double pow = 1;
	int i;
	for(i=1;i<=p;i++)
		pow *=n;
	return pow; //Returns the value of pow
}

To declare the return type of a function, you only need to write out the type before the function name, just like declaring a variable. The keyword return indicates that the function will return the value after it to the calling function. According to the above code, the function returns the value of a variable, and the return value can also be the value of an expression. For example:

return 2*x + b;

Topics: C