5, C # process control

Posted by j4ymf on Sun, 16 Jan 2022 10:54:50 +0100

Process control statement classification

  • Branch statements: if statements and switch statements
  • Iterative statement
  • Jump statement

1. if statement

if (judgment conditional expression) {execute when the expression result is true} else {execute when the expression result is false}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if sentence
{
    class Program
    {
        static void Main(string[] args)
        {
            //Judge the relationship between a variable and 10
            Console.WriteLine("Please enter the first number you want to compare");
            int a=Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Please enter the number you want to compare");
            //int.parse is used to convert statements entered on the screen to integers
            int b = int.Parse(Console.ReadLine());
            if (a < b)
            {
                Console.WriteLine("The first number you entered{0}Less than the second number{1}", a,b);
            }
            else if (a == b)
            {
                Console.WriteLine("The first number you entered{0}Equal to the second number{1}", a,b);
            }
            else {
                Console.WriteLine("The first number you entered{0}Greater than the second number{1}", a,b);
            }
            Console.ReadKey();
        }
    }
}

2,switch

Enter 1 to display as Monday, and so on
Switchc (conditional expression){
case constant expression: conditional statement;
case constant expression: conditional statement;
case constant expression: conditional statement;
default: conditional expression
}

The control cannot be disconnected from the final use case label (XX) - the program cannot be determined as finished, so a break must be added;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace switch Control statement
{
    class Program
    {
        static void Main(string[] args)
        {
            // Enter one to display Monday, once, and so on
            Console.WriteLine("Please enter 1-7 Number of");
            int week = int.Parse(Console.ReadLine());
            switch (week) {
                case 1: Console.WriteLine("Monday"); break;  //End current code body
                case 2: Console.WriteLine("Tuesday"); break;
                case 3: Console.WriteLine("Wednesday"); break;
                case 4: Console.WriteLine("Thursday"); break;
                case 5: Console.WriteLine("Friday"); break;
                case 6: Console.WriteLine("Saturday"); break;
                case 7: Console.WriteLine("Sunday"); break;
                default: Console.WriteLine("The data you entered is incorrect"); break; //If the specified value is exceeded, set the corresponding prompt
            }
            Console.ReadKey();


            //Judging the number of days of each month in 2020, 1,3,5,7,8,10,12 is 31 days, 4,6,9,11 is 30 days, and February is 29 days
            Console.WriteLine("Please enter the number of months");
            int month = int.Parse(Console.ReadLine());
            switch (month)
            {
                
                case 2: Console.WriteLine("You entered{0}The month has 28 days",month); break;                
                case 4:               
                case 6:
                case 9:
                case 11:
                    Console.WriteLine("You entered{0}The month has 30 days",month); break;
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    Console.WriteLine("You entered{0}The month has 31 days", month); break;
                default: Console.WriteLine("You entered{0}Month error", month); break; 
            }
            Console.ReadKey();
        }
    }
}

3. Three bit operator

Conditional judgment expression? Statement executed when it is established: statement executed when it is not established
Applicable conditions of ternary operator: only use and judge the case with two results

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Three bit operator
{
    class Program
    {
        static void Main(string[] args)
        {
            // Judge the relationship between the input report and 10 (< 10 prompt is less than 10, > = 10 prompt is greater than or equal to 10)
            Console.WriteLine("Please enter the data you want to compare");
            int number = int.Parse(Console.ReadLine());
            //Console. Writeline (number < 10)? Console. Writeline ("less than 10"): console Writeline ("greater than or equal to 10");
            Console.WriteLine(number < 10 ? "Less than 10" : "Greater than or equal to 10");
            Console.ReadKey();
        }
    }
}

4. while statement of iterative statement

4.1 overview of iterative statements

A piece of code that repeats execution in a program until a specified condition is met. When you want to repeat some statements, you can select different cyclic use according to different current tasks, which are:

  • while statement
  • do... while statement
  • for statement
  • foreach statement

4.2 while statement

while (conditional expression){
Code statement
}
while statementexecutes when the condition is met

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while sentence
{
    class Program
    {
        static void Main(string[] args)
        {
            //Output 1-50 numbers to the screen
            int a = 1;
            while (a<=50){

                Console.WriteLine(a);
                a++;
               
            }
            Console.ReadKey();
        }
    }
}

5. do... while of iteration statement

do{
Loop body statement
}while();
The do... while statement is executed at least once, even if the condition is not true

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace do__while
{
    class Program
    {
        static void Main(string[] args)
        {
            //Output 1-50 numbers to the screen
            int num = 0;
            do {
                num++;
                Console.WriteLine(num);

            } while (num < 50);
            // Calculate how long the cash will be deposited in the bank before our expected income can be obtained (all are based on one-year fixed deposits, which will be automatically transferred after maturity)
            // Variables needed for the analysis topic: principal, target income, interest rate and time (year)
            // One year's income: principal * (1 + interest rate) * 1 year 
            double Balace = 0;
            double Rate = 0;
            int Year = 0;
            double TargetBalace = 0;
            Console.WriteLine("Please enter your principal");
            Balace = double.Parse(Console.ReadLine());
            Console.WriteLine("Please enter your current interest rate percentage");
            Rate = double.Parse(Console.ReadLine())/100;
            Console.WriteLine("Please enter your target revenue");
            do {
                TargetBalace = double.Parse(Console.ReadLine());
                if (TargetBalace<Balace) {
                    Console.WriteLine("Congratulations, you have it now{0}Yuan, please enter a larger target",TargetBalace);
                }
            } while (TargetBalace<Balace);
            do
            {
                Balace *= (Rate + 1);
                Year++;
            } while (Balace < TargetBalace);
            Console.WriteLine("You will be{0}During the year, it obtained{1}Income of yuan",Year,Balace);
            Console.ReadKey();           
        }
    }
}

6. for loop statement of iterative statement

The for loop can limit the number of cycles and maintain its own timer;
Sometimes we omit the initial condition, judgment condition and cyclic condition, but the two semicolons cannot be omitted
For (initial condition; judgment condition; cycle condition){
Circular statement
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace for Circular statement
{
    class Program
    {
        static void Main(string[] args)
        {
            //Factorization of input data
            // 1!=1  2!=2x1;  3!=3x2x1
            Console.WriteLine("Please enter the order multiplier you want to calculate");

            for (;;) {
            int num = int.Parse(Console.ReadLine());
            int result = 1;
            for (int i=num; i!=0; i--) {
                result *= i;

            };
            Console.WriteLine("{0}The factorial result of is{1}", num, result);
            };
            //Console.ReadKey();

        }
    }
}

for loop nesting (99 multiplication table)
Loop nesting is that one loop is nested with another loop
When a for loop is used, variables that count times of the loop are generally declared in the for loop statement

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace for Circular statement
{
    class Program
    {
        static void Main(string[] args)
        {
            //multiplication table
            Console.WriteLine("==================99 multiplication formula=========================");
            for (int i = 1; i < 10; i++) {
                for (int j=1; j<= i; j++) {
                    Console.Write("{0}X{1}={2}\t", j, i, j * i);
                }
                Console.WriteLine();
            }
            Console.ReadKey();


        }
    }
}

7. foreach of iterative statements

foreach provides a shortcut to the for statement, and it also stores collection classes for more consistency
Foreach (type; variable; in set){
Code body
}
String type (string) can be regarded as a collection of char types (characters)
char.IsWhiteSpace © Determine whether the character is a space
Every time foreach executes the embedded code, the loop variable will read one element in the set at a time to facilitate the loop at that time
The circular variable here is only a read-only local variable. If this value is modified, an error will be reported in compilation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @foreach
{
    class Program
    {
        static void Main(string[] args)
        {
            //Recognize statements as words and output them line by line
            //Statements are of type string and letters are of type char
            Console.WriteLine("Please enter an English sentence");
            string sentence = Console.ReadLine();
            foreach (char word in sentence)
            {
                if (char.IsWhiteSpace(word))
                {
                    Console.WriteLine();
                }
                else
                {
                    Console.Write(word);
                    //word='t';  // Iteration variables of foreach statements are not allowed to be reassigned
                }
            }
            Console.ReadLine();

        }
    }
}

8. break statement of jump statement

Jump statement is a statement that can jump to another line of code in the program when the program runs to a certain position

  • break: 1) the switch statement is used to jump out of the case statement and end the switch branch statement. 2) Used to jump out of the iteration statement and end the current session
  • Continue statement
  • goto Statement
  • return statement

Through iterative statements, prepare to output 500 numbers from 1 to 500, and output 10 numbers per line. When the output value is a multiple of 2, 3, 4, 5, 6] 7 at the same time, the for iteration statement pops up.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace break sentence
{
    class Program
    {
        static void Main(string[] args)
        {
            //Through iterative statements, prepare to output 500 numbers from 1 to 500, and output 10 numbers per line. When the output value is a multiple of 2, 3, 4, 5, 6 and 7 at the same time, the for iteration statement jumps out.
            Console.WriteLine("Output 1~500 These 500 numbers output 10 numbers per line");
            for (int i=1;i<501;i++) {
                if (i % 2 == 0 && i % 3 == 0 && i % 4 == 0 && i % 5 == 0 && i % 6 == 0 && i % 7 == 0) {
                    Console.WriteLine();
                    Console.WriteLine("2,3,4,5,6,7 What is the least common multiple of"+i);

                    break;
                }
                if (i % 10 == 0)
                {
                    Console.WriteLine(i);
                }
                else Console.Write(i + "\t");
            }
            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace break sentence
{
    class Program
    {
        static void Main(string[] args)
        {
            //Through iterative statements, prepare to output 500 numbers from 1 to 500, and output 10 numbers per line. When the output value is a multiple of 2, 3, 4, 5, 6 and 7 at the same time, the for iteration statement jumps out.
            Console.WriteLine("Output 1~500 These 500 numbers output 10 numbers per line");
            for (int i=1;i<501;i++) {
                if (i % 2 == 0 && i % 3 == 0 && i % 4 == 0 && i % 5 == 0 && i % 6 == 0 && i % 7 == 0) break;
                //{
                //    Console.WriteLine();
                //    Console. Writeline ("the least common multiple of 2, 3, 4, 5, 6 and 7 is" + i);

                //    break;
                //}
                if (i % 10 == 0)
                {
                    Console.WriteLine(i);
                }
                else Console.Write(i + "\t");
            }
            Console.ReadKey();
        }
    }
}

9. continue statement

It is used to stop the current iteration statement, end this cycle and enter the next cycle (the statements after continue in this cycle are not executed). Break is to end the loop directly
Can only be used in iterative statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace continute sentence
{
    class Program
    {
        static void Main(string[] args)
        {
            //Achieve odd output within 50, using continue
            Console.WriteLine("Please enter a number, and all odd numbers less than the number of times will be automatically displayed");
            int num = int.Parse(Console.ReadLine());
            for (int i = 1; i < num+1; i++)
            {
                if (i % 2 == 0) continue;  //When the conditions are met, jump out of this cycle and enter the next cycle; And the statement after continue in this cycle will not be executed
                Console.WriteLine(i);
               
                
            }
            Console.ReadLine();
        }
    }
}

10. return of jump statement

There are two general formats for return statements: 1) return; 2) Return expression;
The return statement can only appear in methods. When the method is called, when the return statement is executed; Jump directly to the main() function

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @return
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter three integers and press enter to confirm the input of each number");
            int a = int.Parse(Console.ReadLine());
            int b = int.Parse(Console.ReadLine());
            int c = int.Parse(Console.ReadLine());
            double average = (a + b + c) / 3;
            Console.WriteLine("The three numbers you entered{0},{1},{2}The average is{3}",a,b,c,average);
            Console.ReadKey();
        }
    }
}

Implementation using method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @return
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter three integers and press enter to confirm the input of each number");
            int a = int.Parse(Console.ReadLine());
            int b = int.Parse(Console.ReadLine());
            int c = int.Parse(Console.ReadLine());
            //double averageresult = (a + b + c) / 3;
            double averageresult = average(a,b,c);
            Console.WriteLine("The three numbers you entered{0},{1},{2}The average is{3}",a,b,c, averageresult);
            Console.ReadKey();
        }

        static double average(int a, int b, int c) {
            return (a + b + c) / 3;
        }
    }
}

11. goto of jump statement

Format: goto tag identifier;
Method for identifying program location by identifier
Identification method - identifier + ":"

Function: when the program executes the goto statement, the program will directly jump to the program location indicated by the identifier. Continue execution
The use of goto will reduce the readability of the code. Try not to use goto statements when writing programs
Task: use goto statement to realize multiple-choice questions:
5!=?
1,5!=5
2,5!=10
3,5!=20
4,5!=60
If the choice is true, prompt: Congratulations, you're right!
If the choice is wrong, prompt: Unfortunately, you answered wrong
If the selected option is not 1, 2, 3 or 4, you will be prompted that the selected option does not exist

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace goto sentence
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 0;
            Console.WriteLine("Please select the correct factorial answer of 5, enter the option number and press enter to confirm");
            Console.WriteLine("1. 5!=5\n2. 5!=10\n3. 5!=20\n4. 5!=60\n");

        error:
            {
                a++;  //a=1 in the first execution; Therefore, do not execute. When goto jumps to this statement, add 1 again, a=2, and then execute the following statement
                if (a > 1) Console.WriteLine("Unfortunately, you have the wrong number. Please re-enter the answer");  // The reason for adding a judgment condition is to avoid outputting this prompt for the first execution
            }
        input:  int result = int.Parse(Console.ReadLine());
            
            switch (result) {
                case 1:
                case 2:
                case 3: goto error;
                case 4: goto right;
                default:
                    Console.WriteLine("Your options{0}Does not exist, please re-enter",result);
                    goto input;


            }
        right:
            {
                Console.WriteLine("Congratulations on your correct answer!");
            }
            Console.ReadKey();

        }
    }
}

12. Task implementation

Accept three integers a\b\c, then output the number in the middle of the three numbers and output its factorial

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Task implementation
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter three integers");
            int a = Convert.ToInt32(Console.ReadLine());
            int b = Convert.ToInt32(Console.ReadLine());
            int c = Convert.ToInt32(Console.ReadLine());
            //Judge intermediate variables
            ///If a is an intermediate value, there are two cases, b is the maximum value or b is the minimum value
            int temp = 0;
            int jc = 1;
            if ((a>=b && a<=c) || (a>=c && a<=b)) {
                Console.WriteLine(a + "Is an intermediate value");
                temp = a;
                Console.WriteLine("error");
            }
            if (b >= a && b <= c || b >= c && b <= a)
            {
                Console.WriteLine(b + "Is an intermediate value");
                temp = b;
            }
            if (c >= a && c <= b || c >= b && c <= a)
            {
                Console.WriteLine(c + "Is an intermediate value");
                temp = c;
            }
            for (int i = 1; i < b+1; i++)
            {
                jc *= i;
            }
            Console.WriteLine("Median number{0}The factorial result is{1}",temp,jc);
            Console.ReadKey();




        }
    }
}

Topics: C# microsoft linq