C # Basic Analysis-III [cyclic structure]

Source: Internet
Author: User

We will continue to discuss C # With you today. Today we will talk about the circular structure in C. I want to see the loop structure in all languages! Because the loop structure is a good method that saves time and effort! Therefore, it is common for everyone to use it. Next we will join in the loop structure.
When we log on to QQ, if your password is incorrect, the system will always prompt you that your account or password is incorrect. This function uses a loop structure, okay! Let's take a look at the console program example. I think the example is the easiest way to illustrate the problem.
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 Console. Write ("Logon account ");
6 string name = Console. ReadLine (); // receives the login account
7 Console. Write ("Login Password ");
8 string password = Console. ReadLine (); // receives the logon password
9 // while loop to determine whether the login account and password are correct, if one is incorrect, continue to enter
10 while (name! = "Admin" | password! = "123 ")
11 {
12 // If the logon is incorrect, a prompt is displayed.
13 Console. WriteLine ("The Logon account or password is incorrect. Please enter it again ");
14 Console. Write ("Logon account ");
15 name = Console. ReadLine (); // receives the account again
16 Console. Write ("Login Password ");
17 password = Console. ReadLine (); // receives the password again
18}
19 Console. WriteLine ("Login successful..."); // login successful, loop ends
20 Console. ReadKey ();
21}
22}

Running result:

 


 

While loop structure Syntax:
While (conditional expression)
{
Code block;
}

Flowchart:

 

Flowchart description:
When executing a while LOOP, first judge the condition expression. If the result of the condition expression is true, execute the code in the while loop (that is, the login account and password ), if the result of the conditional expression is false, the while loop ends (LOGIN successful ). Before executing the while LOOP, you must assign values to the variables in the conditional expression, that is, first enter the account and password, and then judge.
Next do... While LOOP, for do... The while loop is similar to the while loop. do... While is the first execution, and then the judgment, while is the first judgment, and then the execution. Do... While, to put it bluntly, is the meaning of playing first! Haha! The following is an example of a console program:
1 classProgram
2 {
3 staticvoidMain (string [] args)
4 {
5
6 stringanswer; // define a variable to save
7 do
8 {
9 // output a prompt and ask
10 Console. WriteLine ("qingapple lives in the blog Garden ");
11 Console. WriteLine ("do you know qingapple (Y/N )");
12 answer = Console. ReadLine (); // receives the answer
13} while (answer! = "Y" & answer! = "Y ");
14 Console. WriteLine ("I know qingapple ");
15 Console. ReadKey ();
16}
17}
Running result:
 



 

I will give you a brief explanation of this example. This example is equivalent to asking for directions. When you ask the first person if they do not know, you will ask the next person, until you ask someone who knows the route (that is, the person who answers Y ).
Let's take a look at the do... while loop Syntax:
Do
{
Code block;
} While (conditional expression );

Flowchart:

 

 

Flowchart description:
Starting from the program, first execute the code block in a loop, and then execute the conditional expression in while to judge. If the result is true, continue to execute the code block, that is, start the loop, if false, the loop ends.
While and do... While is the number of uncertain loops. while is the number of executions after judgment, and do... While is the first execution and then judgment, at least once. Next we will look at a for loop that has determined the number of cycles,
The for loop is used to loop by knowing the number of cycles, or to check a console program:
1 class Program
2 {
3 static void Main (string [] args)
4 {
5
6 // Let's take the Travel Notes to the West as a metaphor (I despise those remake things very much, for example: Travel Notes to the South)
7 // The number of output loops is difficult. If 81 is difficult, the loop ends. num indicates the number of loops.
8 for (int num = 1; num <= 81; num ++)
9 {
10 Console. WriteLine ("Number of hard {0} hard", num); // number of hard output
11}
12 Console. WriteLine ("hard to end ");
13 Console. ReadKey ();
14}
15}

Running result:

 

 

In this example, the number of loops has been determined. We generally use for loops when we know the number of loops.
Let's take a look at the for loop syntax!
For (expression 1; expression 2; expression 3)
{
Code block;
}

The expression in this syntax is a bit dizzy. Expression 1 here is a value assignment statement that assigns values to the variables in the loop, for example: int num = 1; expression 2 is a conditional expression, which can be used for judgment. If the result is false, the loop ends. If the result is true ), the loop continues. For example, num <= 81 in the above console program; expression 3 is also a value assignment statement, which is used to calculate the variable in the loop, such as num ++; the three expressions are written together as for (int num = 1; num <= 81; num ++)
Flowchart:

 


 

Flowchart description:
When a for statement is executed in a loop, expression 1 is executed first, and expression 2 is executed to determine whether the condition is correct. If true, the code block in the loop is executed and expression 3 is executed; if the result is false, the loop ends. Let's talk about it here. In the case of true, after expression 3 is executed, expression 2 is executed to judge again, and the above operations are repeated, until the conditional expression is judged as false.
Let's look at two special things... Break and continue are the operations that stop and continue in the program! I will not talk too much about it. I will understand it when I write two console programs,
Break console program:
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 int count = 0; // The number of login times that the variable is first defined to save. The value is initialized to 0.
6 Console. Write ("Logon account ");
7 string name = Console. ReadLine ();
8 Console. Write ("Logon password ");
9 string password = Console. ReadLine ();
10 // The following uses the while loop to check the role of break. Our goal is to give a user prompt after entering the password three times in a loop.
11 while (name! = "Admin" | password! = "123 ")
12 {
13 count ++; // Add one for each loop
14 if (count = 3) // if the number of logins is 3, stop it.
15 {
16 break; // (^ o ^) note! Break is here!
17}
18 // If the input is incorrect, ask the user to re-enter
19 Console. WriteLine ("the password or account is incorrect. Please enter it again! ");
20 Console. Write ("Logon account ");
21 name = Console. ReadLine ();
22 Console. Write ("Logon password ");
23 password = Console. ReadLine ();
24}
25 if (count = 3) // a prompt is displayed after the loop is aborted.
26 {
27 Console. WriteLine ("Sorry! You have entered three consecutive errors! ");
28}
29 else
30 {
31 Console. WriteLine (" succeeded"); // a prompt is displayed indicating that the logon is successful, and the loop ends.
32}
33 Console. ReadKey ();
34}
35}

Running result:

 


 

Next, the continue console program:
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 // continue: we use the for loop implementation. The loop is 7 times, representing a week,
6 for (int I = 1; I <= 7; I ++)
7 {
8 if (I = 3) // it is determined to be closed on Saturday.
9 {
10 Console. WriteLine ("3 days in a week --- Leave ");
11 continue; // (^ 0 ^) note! Continue is here!
12}
13 // output judgment
14 if (I = 7)
15 {
16 Console. WriteLine ("Sunday break ");
17}
18 else
19 {
20 Console. WriteLine ("week {0} --- go to work... ", I); // cycle output week
21}
22}
23 Console. ReadKey ();
24}
25}

Running result:

 

 

See it! Okay. Let's take a simple look at break and continue. Break is a stop loop, which directly affects the number of cycles. That is to say, as long as the break cycle ends, it does not hesitate. Continue stops this cycle and continues to execute the following cycle without affecting the number of cycles. For example, if you eat three meals a day (normal people's eating habits ), if you have not eaten the lunch at noon, continue it! You can eat at night, but if break is used! You can't eat any more in the future! Just waiting to starve...
Finally, let's take a look at the foreach loop. The foreach loop can be called a special loop statement in C #. Let's take an example to see how special it is:
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 Console. WriteLine ("enter a number ");
6 string str = Console. ReadLine ();
7 // foreach loop get a single character from the string str each time
8 foreach (char ch in str)
9 {
10 // determine whether the single character is a number
11 if (Char. isDigit (ch) = false) // "Char. isDigit "indicates a number. If it is a number, true is returned. Otherwise, false is returned. You only need to know it here!
12 {
13 Console. WriteLine ("{0} is not a number", ch); // output result
14 break; // break end cycle
15}
16}
17 Console. WriteLine ("judgment completed ");
18 Console. ReadKey ();
19}
20}

Running result:

 

 

Foreach Syntax:
Foreach (Data Type Variable in set or array)
{
Code block;
}

The syntax of the foreach loop may not be easy to understand here. I will explain in detail below that each loop of the foreach loop should be from the set or array (in) get a value from left to right. The value type must be consistent with the data type of the set or array. Generally, this value is kept in a variable. The foreach loop is similar to the for loop, but the foreach loop is not fixed, and the number of cycles is automatically controlled in the previous foreach console example.
Flowchart:

 

 

Flowchart description:
In a loop, foreach first assigns a value and then determines in expression 1. If true, the code block is executed, expression 2 is executed, and loop judgment is performed, when expression 1 determines that the result is false, the loop ends.
OK! The above is all the loops of this time. In the loop, we should pay attention to one problem, that is, the endless loop, which should be avoided as much as possible in program development. Once we find an endless loop, it is necessary to carefully check whether there are errors in the code that controls loop exit. Let's take a look at a typical example:
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 int I = 1;
6 while (I <10)
7 {
8 Console. WriteLine ("this is the {0} loop", I );
9 // here is the missing code
10}
11 Console. ReadKey ();
12}
13}

Running result:

 


Modify error points:


Correct running result:




 

Summary:

1. while loop structure;

2. do... while loop structure;

3. for loop structure;

4. Keyword break and continue;

5. foreach loop structure;

6. Endless loops;

OK! This sharing is here. You are welcome to leave a message to discuss it so that we can make common progress. Let's get here today! More! It's time to go to bed! Finally, let's copy the sentence: This article is my personal opinion. If there are any imperfections or inaccuracies, you are welcome to criticize and give advice from the experts.

 

From apple
 

Related Article

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.