Summary of general control statements

Source: Internet
Author: User

Sequential process

You have a cup of water, which is generally like this:
1. fill the cup with boiling water;
2. Wait for boiling water to cool down;
3. Pour it in your mouth.
In this example, you can think of how to accomplish things,
There must always be an order, and the execution order is often very important.
For example, in the example of drinking water, if you sort steps 2nd and 3rd, the outcome may be quite uncomfortable;
If you want to put Step 1 at the end of the execution, you will never be able to drink water.
Programs are used to solve real-life problems, so processes are equally important in programs.
We have learned the statements. When we write a line of code,
These codes must be executed in a certain order, which is the process of the program.
First, we should familiarize ourselves with the simplest process: sequential process.
A simple addition question C ++ syntax format
//---------------------------------------------------------------------------
Now, let's add the code to implement addition computing:
# Include <iostream. h>
Int main ()
{
Int JS1, JS2; // Add 1, add 2
Int he; // and
JS1 = 58;
JS2 = 42;
He = JS1 + JS2; // and = addend 1 + addend 2
Cout <JS1 <"+" <JS2 <"=" Return 0;
}
After this program is compiled, the running result is: 58 + 42 = 100
//---------------------------------------------------------------------------
The following code calculates the order of addition for the button controls in the graphic interface.
Void _ fastcall tform1: button1click (tobject * sender)
{
Int JS1, JS2, he;
JS1 = edit1-> text. tointdef (0 );
JS2 = edit2-> text. tointdef (0 );
He = JS1 + JS2;
Edit3-> text = inttostr (HE );
}

 

//************************************** ***********************
Conditional branch statement --
1 If... else statement
2 If... statement
3? : Expression
4 Multi-level if... else... statement
5 switch statement
"To be or not be "? This problem is deeply plagued by hampir.
He must make a choice between "survival or destruction", which is a difficult choice.
In your life, what choices have you ever faced?
"Learning programming or not learning programming "? "Learning CB or VC "?
Which one to choose is always determined. what is different is the different conditions that each person must face when making a choice.
In the previous chapter, we talked about the "sequence process" as straight as Changan Street, from the beginning to the end;
In this chapter, we will talk about the "conditional branching process", like a forking on the road, is it a direct or right turn?
Let's take a full look at the conditions that the program encounters when it goes to the forks.
 
9.1 If... else statement
If, which means "if "......
"If the water in the entire Pacific Ocean is poured out, the fire of my love for you will not be extinguished," said Yan zicai ".
Of course, if you have learned programming and this chapter, you will understand how cool the conditional branch statement is,
As the sentence below it reveals: "Is the water of the entire Pacific Ocean fully produced? No. So I don't love you ".
Let's take a look at how to use the IF... else statement in C, C ++.
 
If... else syntax format:
If (condition)
{
Branch 1
}
Else
{
Branch 2
}
If the condition is true, the program executes the statement in branch 1. Otherwise (the condition is false) The program executes the statement in branch 2.
This is the IF... else statement. For example:
If (I won the 5 million awards for this sports lottery)
{
I buy a house;
I bought a car;
I am traveling to Europe;
}
Else
{
I want to repair my bicycle;
I bought a sports lottery,
I continue to burn incense.
}

Code

# Include <iostream>
Using namespace STD;
Int main ()
{
Int num;
Cout <"enter an integer :";
Cin> num;
If (Num % 2) = 0)
Cout <num <"is an even number. "<Endl;
Else
Cout <num <"is an odd number. "<Endl;
Return 0;
}

Else (otherwise) in if... else... is not required, because sometimes, when the specified condition is set, we execute some actions. Otherwise, we do not execute those actions.

-----------------------------------------------------------------------------
If... statement format:
 
If (condition)
{
Branch 1
}
The Code is as follows:
# Include <iostream>
Using namespace STD;
Int main ()
{
Char;
Cout <"enter a character :";
Cin>;
If (A> = 'A' & A <= 'Z ')
Cout <A <"is a lowercase letter. "<Endl;
Return 0;
}

? : Expression
? : The expression is called the question mark colon expression.
If (A> B)
C = 1;
Else
C = 0;
The code without curly brackets is much more compact. But for the above code, we can continue to simplify, that is, use? : Statement.
C = (A> B )? 1: 0;
Just a line of talk, more simple!
What is the question mark in the statement? Is a greater than B? If yes, 1 is obtained. Otherwise, 0 is obtained.
? : Expression format Syntax:
(Condition )? Value 1: Value 2
For example, the int variables A and B have been initialized. Please obtain a greater margin among the two.
The method is: int c = (A> B )? A: B;
Not all if... else... statements can be used :? To replace,
Only conditional branch statements that are used to calculate a value of the same type and assign the same variable are suitable.
Code Implementation
# Include <iostream>
Using namespace STD;
Int main ()
{
Int A, B, C;
Cout <"enter two integers (separated by spaces ):";
Cin> A> B;
C = (A> B )? A: B;
Cout <C <"big" <Endl;
Return 0;
}

Bytes -----------------------------------------------------------------------------------------------

Syntax format of multilevel if... else:
 
If (condition 1)
{
Branch 1
}
Else if (condition 2)
{
Branch 2
}
Else if (Condition 3)
{
Branch 3
}
Else
{
Branch 4
}
 
The format contains four branches. There can be only three, two, or more. See this example.

Let's imagine a scene like this ?? Time: July 15, February 14; Location: small park in a school;
Character: Female 1, male 1.
(Boys give girls a ring)
GIRL (happy): How beautiful ?? How much did you buy!
BOYS: Guess.
GIRL (I thought: if more than 100 yuan, I will kiss him): More than 100 yuan?
BOYS: No.
Girl: (I thought: If I had more than 50 yuan, I 'd just ask him to kiss me): Isn't it less than 50 yuan?
BOYS: No.
Girl: (in my heart, I want to say thank you if I have more than 10 yuan.): Isn't that less than 10 yuan?
BOYS: No.
Girl: (I don't have any idea anymore. I just threw away the flowers.): Sorry!
Do you understand? "Understand ......" A boy stood up with tears,

A: "I understand. None of the girls now write good things into programs, that is:
 
Int price = rose price;

If (price> 100)
{
The girl needs to kiss the boy;
}
Else if (price> 50)
{
The girl prepares to give the boy a kiss;
}
Else if (price> 10)
{
The girl said "thank you" to the boy ";
}
Else
{
The girl threw away the flowers and said, "Sorry !";
}

If the cost is more than 100 yuan, the girl will kiss the boys; otherwise? Otherwise, judge whether the cost is greater than 50 yuan,

If it is not large, it will no longer judge whether the cost is greater than 10 yuan. If it is not big, then unconditionally execute the "little girl throwing away the flowers ......" This sentence.

 

# Include <iostream>
Using namespace STD;
Int main ()
{
Int flowerprice;
Cout <"in February 14, 2018 AD, a boy presented a bunch of roses to a girl ...... "<Endl;
Cout <"Girl: Enter the price for this bundle. "<Endl;
Cout <"Boys :";
Cin> flowerprice;

If (flowerprice> 100)
Cout <"Girl: Wow! I like it so much. Let me show you my gratitude! "<Endl;
Else if (flowerprice> 50)
Cout <"Girl: Ha! Do you want to kiss me? "<Endl;
Else if (flowerprice> 10)
Cout <"Girl: Thank you! "<Endl;
Else
Cout <"GIRL: What are the flowers. "<Endl;
Return 0;
}

Bytes -----------------------------------------------------------------------------------------------

Switch statement

Switch statement format:

Switch (integer or complex type variable)
{
Case variable value 1:
Branch 1;
Break;
Case variable value 2:
Branch 2;
Break;
Case variable value 3:
Branch 3;
Break;
...
Default:
Last branch;
}
 
In the switch syntax, we need to learn four keywords: Switch, Case, break, and default.
In the switch (variable) line, the variable can only be an integer or variable type.
The program first reads the value of this variable, and then finds in each "case" which value is equal to this variable,
If the conditions are equal, the program executes the corresponding branch until the break or switch statement ends.
Abstract. Let's take a look at it with an instance.
The instance simulates an online survey. It requires a netizen to enter a number to select how he or she has arrived at the current webpage.
Then, the program outputs different results based on the user input.
The program outputs different results based on the user's choice. Create a blank project in the console, and enter the following simhei section in the code.
//---------------------------------------------------------------------------
# Include <iostream. h>
Using namespace STD;
Int main ()
{
Int fromway;
Cout <"Enter the serial number and select how to access this website. "<Endl;
Cout <"1) ---- search engine <Endl;
Cout <"2) ---- introduced by friends" <Endl;
Cout <"3) ---- use newspapers and magazines" <Endl;
Cout <"4) ---- Other Methods" <Endl;
Cin> fromway;
 
Switch (fromway)
{
Case 1:
Cout <"you came to this website through the search engine. "<Endl;
Break;
Case 2:
Cout <"you came to this website through a friend's introduction. "<Endl;
Break;
Case 3:
Cout <"you came to this website through newspapers and magazines. "<Endl;
Break;
Case 4:
Cout <"you came to this website through other methods. "<Endl;
Break;
Default:
Cout <"Incorrect choice! Enter 1 ~ 4. "<Endl;
}
Return 0;
}

Switch (fromway)
The program will find the matched values in each case according to the fromway value.
In this example, the switch has four cases with values: 1, 2, 3, and 4.
In the result graph, Because I entered 2, the program enters the following case:
Case 2:
Cout <"you came to this website through a friend's introduction. "<Endl;
Break;
Program "you are introduced to this website through a friend. "This line of content. Finally, the entire switch statement exists.
 
In the same way, if the user inputs other numbers, such as 1 or 3, the corresponding case 1 or case 3 branch is entered.
But what if the number entered by the user cannot be found in all cases? For example, enter 5.
In this case, the default branch will take effect. If the values in all cases do not match, the switch enters the default branch.
If no default exists, the program does not do anything in the switch statement and completes the switch statement directly.
Let's take a look at the meanings of switch, Case, break, and default. They are: Switch, condition, interrupt, default (value ).
In a single sentence, the statement is: depending on the switch value, execute different situations until there is an interruption;
If none of the conditions match the switch value, the default branch is executed.
Finally, let's take a few important notes about the switch.
1. In switch (an integer or character type variable), the type of the variable, as marked in the text, can only be an integer or character type.
They include int and char. Of course, none of the character types or different length INTEGER (unsigned int, short, unsigned char) can all be.
In addition, the enumeration type (Enum) is also implemented by the integer or character type.
The number of real instances (floating point) cannot be used, for example, float a = 0.123;
Switch (a) // error! A is not an integer or character type variable.
{
....
}
 
2. After case, it can be a direct constant value. For example, 1.2.3.4 in this example can also be a constant calculation formula, such as 2 + 2,

But it cannot be a variable or an expression with a variable, such as a * 2.
Of course, it cannot be a real number, such as 4.1, or 2.0/2.
Switch (formway)
{
Case 2-1: // correct
...
Case A-2: // The Error
...
Case 2.0: // an error occurs.
...
}
In addition, a colon is required after case and constant value. Be careful not to neglect it.
 
Third, the role of break.
Break enables the program to jump out of the entire switch statement (that is, after one pair of {} after the switch is connected) after running the selected branch to complete the switch.
Without this break, the program will continue to the next branch until the next break or switch is met.
For example, assume that the program now enters the branch in Case 1: But the branch in Case 1 does not add break:
 
Case 1:
Cout <"you came to this website through the search engine. "<Endl;
Case 2:
Cout <"you came to this website through a friend's introduction. "<Endl;
 
Then, the program outputs "you came to the website through the search engine.
"Later, we will continue to output" in Case 2, "you came to this website through a friend introduction. ".
Change the code snippet in the previous instance to the following (the red part indicates that all breaks are invalid by adding.

Case 1:
Cout <"you came to this website through the search engine. "<Endl;
// Break;
Case 2:
Cout <"you came to this website through a friend's introduction. "<Endl;
// Break;
Case 3:
Cout <"you came to this website through newspapers and magazines. "<Endl;
// Break;
Case 4:
Cout <"you came to this website through other methods. "<Endl;
// Break;
Default:
Cout <"Incorrect choice! Enter 1 ~ 4. "<Endl;
...
 
What is the result after running? Please try it and then answer me in your homework.
 
Fourth, default is optional. We have already mentioned its usefulness and, if there is no default,
After the program cannot find the matching case Branch, it will directly complete the switch without doing anything within the scope of the switch statement.
You can also comment out the default code in the instance, run the test, and enter 5 at the time of selection.
...
// Default:
// Cout <"Incorrect choice! Enter 1 ~ 4. "<Endl;
...
 
Fifth, if necessary, you can use {} in each case to explicitly generate an independent compound statement.
When we talk about the IF... statement and other process control statements, both use {} to generate compound statements:
If (condition)
{
Branch 1;
}
Unless there is only one statement in the branch, brackets {} are not required here {}.
However, in the case statements of the switch, the syntax format is not marked as {}. Please refer:
Switch (integer or complex type variable)
{
Case variable value 1:
Branch 1;
Break;
Case variable value 2:
....
}
 
Generally, in textbooks, the case Branch does not use {}, but I would like to remind you that,
In no case, the case Branch does not add {}. For example, you want to define a variable in a case:
Switch (formway)
{
Case 1:
Int A = 2; // error. The compiler cannot define a variable here because the range of case is not clear.
...
Case 2:
...
}
 
In this case, adding {} can solve the problem.
Switch (formway)
{
Case 1:
{
Int A = 2; // correct. Variable A is explicitly limited to the current {} range.
...
}
Case 2:
...
}
As this note involves the scope of the variable, if you do not understand it very well, you can leave it empty for now.
6. Switch cannot replace all statements with if... else. You should know this, because we have already said,
When determining a variable, it can only judge the variable of the integer or numeric type.
In addition, the switch can only be used to determine whether the value is equal. You cannot write conditions in case:
Switch (I)
{
Case (I> = 32 & I <= 48) // error! In case, only possible values of variables can be written, and conditions cannot be written.
...
}
 
In this case, you can only implement it through if... else.
 
**************************************** ******************************
Loop
1 While Loop
2 do... while loop
3. The three elements of for loop conditions are embodied in the for loop structure.
4 Multi-layer Loop
5. Summary and a few questions
 
 
Loop is repetition. There are many things that need to be repeated in life.
For example, you and my whole life is a repetition, repeating every day until we die. Fortunately, our daily life is not exactly the same.
While Loop
Syntax format:
While (condition)
{
Statements that need to be executed cyclically;
}

While is the meaning of "when. First, make a comparison with the if statement:
 
If (condition)
{
Statement executed when the condition is set;
}
 
Except for the different keywords, the two have the same structure.
Note that when the condition is set, the IF statement is executed only once, and the while statement is executed repeatedly until the condition is no longer true.
The program starts execution from the "previous statement" and then determines the conditions. If the conditions are true, the program executes the "Statement executed in each loop" once ",
Pay special attention to the red part.
For the first time, we will go back to the process: the red line is like a car turning, turning around to the condition (not including the preceding statement ),
Then proceed to the next condition judgment ...... The program "continues the following statement" until the condition is invalid during a certain judgment ".
 
We use the while syntax to apply the actual examples in our daily life. We can intuitively see the usage of while.
Suppose there is a crying little doll. One day she asks her parents to buy a red dress. Unfortunately, her parents do not agree, so she starts a cycle:

While (parents do not buy a red dress)
{
I cried;
}
 
This "code" means that when "My parents don't buy a red dress", the little girl will cry over and over again.
This is the first battle between us and the loop process.
The example seems intuitive: "Children cry over and over again until their parents buy a dress ",
However, if you really want to use the language of the program to correctly express it, you need to consider many aspects. The program is rigorous.
First, a suitable condition for determining whether to continue is very important.
The little girl will continue to cry, just "My parents do not buy a red dress", which shows that it does not match the facts,
When we were young, we would cry again and eventually get tired. So,
To continue crying, we have two conditions: "My parents don't buy a red dress" and "I'm not tired yet ".
While (my parents do not buy a red dress & I have not been tired of crying)
{
I cried;
}
 
Secondly, in most cases, conditions need to be properly changed.
The little girl is crying constantly. How does she know whether her parents have bought a red dress?
Therefore, she can't just cry, but she has to observe whether adults agree to buy a dress while crying.
As for whether to cry tired, let's assume that the little girl has a fatigue. Each time she cries, the fatigue increases by 1. When the fatigue reaches 200, the poor little girl is tired ......
 
While (parents do not buy small red skirts & fatigue <200)
{
I cried;
I peeked at whether my parents agreed to buy a dress;
Fatigue ++;
}
 
Example 1: Use the while statement to calculate the sum from 1 to 100.
For the sum of 1 + 2, we can write a = 1 + 2; for the sum of 1 to 100,
Of course we can write a = 1 + 2 + 3 +... 100. However, this is obviously too tiring,
Write Data from 1 to 100! So you are smart like Gauss,
Of course, I also know that writing like this: A = (1 + 100) * 50; this is indeed a commendable, fast, and simple method at any time,
But today we want to make the computer a little tired, honestly from 1 to 100.
First, use the while loop we learned first.

//---------------------------------------------------------------------------
# Include <iostream. h>
Using namespace STD;

Int main ()
{
Int sum = 0; // The variable sum will be used to store the sum and initialize it to 0, which is very important.
Int I = 1; // I is the number to be added each time. It starts from 1.
 
While (I <= 100)
{
Sum + = I;
I ++;
}

// Output the accumulative result:
Cout <"1 to 100 sum:" <sum <Endl;
Getchar ();
}
Sum is initially 0, and then in each loop, it adds I, and I is added after each addition, increase by 1.
In the end, I increases to 101 and exceeds 100. This cycle completes the task.
 
Run the above program and the output result is:
 
The sum between 1 and 100 is: 5050.
 
Do... while loop
 
Syntax format:
 
Do
{
Statements that need to be executed cyclically;
}
While (condition );
 
The most obvious difference between a while loop and a while loop is that in a do... while loop, the condition for determining whether or not to continue the loop is placed at the end.
That is to say, even if the condition is not true at the beginning, the loop will be executed once.
Compare the following two sections of code: the former uses the while loop, and the latter uses the do... while loop.
 
Code snippet 1:
Int A = 0;
While (a> 0)
{
A --;
}
 
The initial value of variable A is 0, and the condition a> 0 is obviously not true. Therefore, the --; statement in the loop body is not executed.
After the code is executed, the value of variable A is still 0;
 
Code Segment 2:
Int A = 0;
Do
{
A --;
}
While (a> 0 );
 
Although the condition a> 0 is not true before loop execution, but because the program is running to do,
Instead of judging the conditions first, you can directly run the statement in the loop body: --.
So the value of a becomes-1, and then the program judges a> 0. It finds that the condition is not true and the loop ends.
 
The conditions in do... while are the same as those in the while loop: "conditions that allow loop continuation ",
Instead of the "condition for ending the loop"
This is the opposite of do... Until in Pascal. If you have learned Pascal (Delphi), you can pay attention to it.
Based on my experience, do... while loops are not used much. Most loops are implemented more intuitively using while.
Below we simply convert the 1-100 concatenation program to do... while:
 
Int sum = 0;
Int I = 1;
 
Do
{
Sum + = I;
I ++;
}
While (I <= 100 );

3. For Loop
For loops use the most in C and C ++, and are also the most flexible loop statements.
To learn it well, you need to "mine" the elements of the loop flow from the while loop that you have learned,
These elements are hidden behind the while, or do... while, but they are directly reflected in the structure of the for loop.
The three elements of one cycle condition learn two cycles. Let's explore the "three conditions" in the cycle process ".
First, the condition usually requires initialization. Please refer to the code that uses the while loop to accumulate 1 to 100:
Int sum = 0; // The variable sum will be used to store the sum and initialize it to 0, which is very important.
Int I = 1; // I is the number to be added each time. It starts from 1.
While (I <= 100)
{
Sum + = I;
I ++;
}
 
In this Code, the condition for loop is I <= 100; therefore, at the beginning, I must have a definite value. Previous:
Int I = 0; this line of code, while declaring the variable I, also assigned an initial value for I: 1.
In this way, condition I <= 100 is true (because I is 1, I <= 100 is true ).
Second, the loop must have a chance to end.
The "endless loop" is the most taboo in the program ". The so-called "endless loop" means that the loop condition is always true,
In addition, there is no chance to jump out of the loop (which will be learned later ).
For example: // an example of an endless loop:
While (2> 1)
{
Cout <"endless loop" <Endl;
}
 
Run this code and you will find that the program cannot stop. The reason is that its cycle condition 2> 1 is always true.
Therefore, a final condition that can be changed to an invalid condition is required in most cases. For example, in the while example:
While (I <= 100)
Condition I <= 100, Because I is changed in the loop, it may at least theoretically cause I <= 100 to be invalid.
 
Third, the establishment factor of changing the cycle condition in the loop
This article matches the second article.
For example, this Code:
Int I = 1;
While (I <= 100)
{
Sum + = I;
}
It is also a terrible "endless loop ". Because I has no chance of being changed, its value is always 1, so that the cyclic condition I <= 100 is always true.
Therefore, the last sentence (bold below) in the loop cannot be forgotten.
While (I <= 100)
{
Sum + = I;
I ++;
}
Of course, in this program, in addition to the factors that change the conditions, I ++ also increases the sum continuously, so as to accumulate and.
 
After reading this, we can see the most flexible loop structure in C ++: For Loop.

The three elements are embodied in the for loop structure.
For Loop Syntax:
 
For (condition initialization; condition change)
{
Statements that need to be executed cyclically;
}
 
It can be seen that in the for structure, not only the "condition" location is provided, but also the condition initialization and the location where the condition changes.
Although the three are on the same line, they are not sequentially executed.
 
The conditional initialization expression is executed first (and only once );
Then, the program checks whether the conditions are true. If the conditions are true, the statement in the loop body is executed. Otherwise, the loop ends directly.
After a loop is executed, the program executes the "conditional change" statement.
 
The program that accumulates integers from 1 to 100 is changed to for loop writing, which is the most suitable:
 
Int sum = 0;
Int I;
 
For (I = 1; I <= 100; I ++)
{
Sum + = I;
}
 
The program first executes the conditional initialization statement: I = 1;
Then, can I determine the condition I <= 100 immediately? Display. The condition is true;
Therefore, the program executes the statement in the loop body. At this time, there is only one sentence: Sum + = I;
Then, execute the statement to change the condition factor: I ++; at this time, the I value is changed to 2;
The program judges the condition again I <= 100 ?, Still valid, so the second loop ......
 
Variable I can be declared temporarily only when the conditions are initialized:
For (INT I = 1; I <= 100; I ++ )......
 
The compound structure of the for statement makes the program simple. For example, in the above example,
In the original while or do... while structure, there must be two statements in the loop body. Now you only need one sentence (I .e., the I ++ sentence is moved to the specific position of the ),
In this way, we can remove curly braces:
For (INT I = 0; I <= 100; I ++)
Sum ++ = 100;
Of course, if, in other cases, the for loop body still needs to have multiple rows of statements, {} is still unavoidable.
In fact, even in this situation, we recommend that you use curly brackets. This makes the program structure clearer.
 
In this example, we can move the only row in the circular body to the position of "condition change" if we have to make it simple:
For (INT I = 1; I <= 100; sum + = I, I ++ );
Sum + = I and I ++ are separated by commas. The end of the () line after the for statement is followed by a semicolon, indicating that the for statement does not have to be executed.
Considering the post ++ feature (adding 1 after the expression is evaluated), you can also combine sum + = I and I ++ into one sentence:
For (INT I = 1; I <= 100; sum + = I ++ );
 
The above describes how to merge for statements in a simple way. In turn, the for statement can be opened and written in the same way as the while or do... while statement:
 
Int I = 1;
For (; I <= 100 ;)
{
Sum + = I;
I ++;
}
 
Check that the conditional initialization statement is removed from the for structure, and the conditional change statement is treated as a normal statement and directly added to the loop body.
In the corresponding position, only the semicolon is left to indicate the null Statement (note that there are two semicolons in this line, before and after I <= 100 ):
For (; I <= 100 ;)
As shown in the uplink, the expressions of "initial condition" and "change condition" in the for loop structure are ignored,
In this case, the for and while or do... while loops are exactly the same. For example, 1 ~ 100 sum:
Int I = 1, sum = 0;
For (; I <= 100 ;)
{
Sum + = I;
I ++;
} Int I = 1, sum = 0;
While (I <= 100)
{
Sum + = I;
I ++;
}

10.5 summary and a few questions
 
I learned three types of loop processes: while, do... while,.
 
While checks whether the condition is true at the beginning of each loop. If the condition is not true at the beginning, the statement in the loop is not executed at one time.
 
The special feature of do... while is that the conditions are not checked before the first loop,
So even if the conditions are not true at all, the loop will be executed once, for example:
Do
{
...
}
While (false );
Is the condition "false "? Is that a condition? Yes, this is also a condition,
A definite condition is not true. It is also common: While (0 ).
0 indicates false. On the contrary, the true condition is: While (true) or while (1.
 
The special feature of for is that in addition to condition judgment, it also explicitly sets aside the location of condition initialization and condition change.
Therefore, the counting cycle is most suitable for using for. For more information, see the example of using for to accumulate between 1 and 100 in the course.
As for the various "variants" of for, loops are like circles.
For example, in a physical education class, we can run 1200 meters and 400 meters in a circle, so what we need to do is to run and count them in our hearts.
(Of course, the number should be counted. Otherwise, if the teacher calculates less than one circle, we will be done.) When the Count reaches three circles, the "loop" will end.
In this example, when the condition is initialized, the count is set to 0, and the cycle condition is that the count is less than 3;
Conditional change means that when every lap is completed, the count is increased by 1. As for the cyclic action, it is naturally a running ......

Implement with while:
Int JS = 0; // JS calculates "count ",
While (JS <3)
{
Run a lap ......;
JS ++;
}
 
Use do... while to implement:
Int JS = 0;
Do
{
Take a lap ......
JS ++;
}
While (JS <3 );
 
Use for (most suitable)
For (INT I = 0; I <3; I ++)
{
Run a lap ......;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.