C# day2 note 2 (variables, constants, operators, judgments, loops)

Posted by xadmin on Sun, 26 Dec 2021 12:52:46 +0100

C# note 2 (variables, constants, operators, judgments, loops)

  1. C# variable

    A variable is simply the name of a storage area for program operation. In C #, each variable has a specific type, which determines the memory size and layout of the variable. The values in the range can be stored in memory and can perform a series of operations on variables.

    [external link picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-eU5XrnOY-1629068834761)(image(. Data type. png)]

    Syntax of variable definition in C #:

    The type can be followed by multiple identification names

    Data type identification name

    For example:

    int i, k;

    It is also assigned when defining variables

    int i = 10;
    
  2. Variable initialization in C #

    • Variables are initialized (assigned) by a constant expression followed by an equal sign. The general form of initialization is:

      Variable name = value
      
    • Variables can be initialized when declared (specifying an initial value). Initialization consists of an equal sign followed by a constant expression, as follows:

      Data type variable name = value
      

    Practice code

    int a;
    short b;
    double cc;
    
    a = 10;
    b = 20;
    cc = a+b;
    
    Console.WriteLine("a={0},b={1},cc={2}",a,b,c); // a=10,b=20,cc=s
    
  3. Receive user entered values

    • **Console.ReadLine() * * is used to receive input from the user and store it in a variable.

      // Receive user entered values
      int sum;
      sum = Convert.ToInt32(Console.ReadLine());  // Cast to integer
      // Triggered when the user enters data on the console and presses enter
      Console.WriteLine("Value from user input:{0}",sum);
      
    • Function convert Toint32() converts the data entered by the user to the int data type because console Readline() only accepts data in string format.

  4. Lvalues and Rvalues in C #

    Two expressions in C #:

    1. Lvalue: lvalue expressions can appear to the left or right of an assignment statement.
    2. Rvalue: rvalue expression can appear on the right of assignment statement, but not on the left of assignment statement.

    The variable is lvalue, so it can appear on the left of the assignment statement. The value is rvalue, so it cannot be assigned and cannot appear on the left of the assignment statement. The following is a valid statement:

    int g = 20;
    
  5. C # constant

    Constants are fixed values and do not change during program execution. Constants can be any basic data type, such as integer constants, floating-point constants, character constants, or string constants, as well as enumeration constants.

    Constants can be treated as regular variables, but their values cannot be modified after definition.

  6. C # character constant

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-qSAP35Kb-1629068834764)(image.. Character constant. png)]

     // Escape character
    Console.WriteLine("holle\\world\tc#");
    // holle\world     c#
    
  7. C # define constants

    Constants are defined using the const keyword. The syntax for defining a constant is as follows:

    const Data type constant name = value
    

    example

    // constant
    const double pi = 3.1413;
    double r;
    Console.WriteLine("Please enter the calculated radius:");
    r = Convert.ToDouble(Console.ReadLine()); // Cast to double
    double areaCircle = pi * r * r; // Find radius
    Console.WriteLine("Radius:{0},Arrea:{1}",r,areaCircle);
    Console.ReadLine();
    

    Console output effect

    Please enter the calculated radius:
    3
    Radius:3,Arrea:28.2717
    
  8. C # arithmetic operator

    An operator is a symbol that tells the compiler to perform a specific mathematical or logical operation. C # has rich built-in operators, which are divided into the following six categories:

    • Arithmetic operator
    • Relational operator
    • Logical operator
    • Bitwise Operators
    • Assignment Operators
    • Miscellaneous operator

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-BcWN2pso-1629068834766)(image, arithmetic operator. png)]

    [external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ePpv06cT-1629068834768)(image, relational operator. png)]

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Qihd2CmF-1629068834770)(image, logical operator. png)]

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9ErjoA0U-1629068834772)(image. Bit operation. png)]

    1

    [external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-yiWaHMDL-1629068834775)(image.png)]

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zldA7eS7-1629068834776)(image. Operator priority. png)]

  9. C# judgment

    if() judgment statement

    if(Conditional judgment statement){
       If the condition is true, execute the statement
    }else{
        If the condition is false, execute the statement
    }
    

    switch() statement

    A switch statement allows you to test when a variable is equal to multiple values. Each value is called a case, and the tested variable checks each switch case.

    switch(expression){
        casse "condition":
        Execute statement
        break;
        /* You can have any number of case statements */
        default : /* Optional */
           statement(s);
           break; 
    }
    

    The switch statement must follow the following rules:

    • The expression in the switch statement must be an integer or enumeration type, or a class type, where class has a single conversion function to convert it to an integer or enumeration type.
    • There can be any number of case statements in a switch. Each case is followed by a value to compare and a colon.
    • The constant expression of case must have the same data type as the variable in switch and must be a constant.
    • When the variable being tested is equal to the constant in the case, the statement following the case will be executed until the break statement is encountered.
    • When a break statement is encountered, the switch terminates and the control flow jumps to the next line after the switch statement.
    • Not every case needs to contain a break. If the case statement is empty, it may not contain a break, and the control flow will continue with subsequent cases until a break is encountered.
    • C # it is not allowed to continue from one switch section to the next. If there is a processing statement in the case statement, it must include a break or other jump statement.
    • A switch statement can have an optional default case that appears at the end of the switch. Default case can be used to perform a task when none of the above cases is true. The break statement in the default case is not required.
    • C # does not support explicit penetration from one case tag to another. If you want c# support to run explicitly from one case tag to another, you can use goto a switch case or goto default.

    Practice code

    using System;
    
    namespace Project3
    {
        class Program
        {
            static void Main(string[] args)
            {
                while (true) {
                    Console.WriteLine("Please enter the number of weeks you want to view:");
                    int day = Convert.ToInt32(Console.ReadLine());
                    switch (day)
                    {
                        case 1:
                            Console.WriteLine("run");
                            break;
                        case 2:
                            Console.WriteLine("Swimming");
                            break;
                        case 3:
                            Console.WriteLine("Mountain climbing");
                            break;
                        case 4:
                            Console.WriteLine("Walk slowly");
                            break;
                        case 5:
                            Console.WriteLine("play a ball");
                            break;
                        case 6:
                            Console.WriteLine("ride on a bicycle");
                            break;
                        case 7:
                            Console.WriteLine("rest");
                            break;
                        case 0:
                            return;
                        default:
                            Console.WriteLine("The number you entered exceeds the limit and will exit automatically!");
                            return;
                    }
                }
            }
        }
    }
    
  10. C # cycle

    C # provides the following types of loops

    while() loop

    When the given condition is true, repeat the statement or statement group. It tests the condition before executing the loop body.

    while(condition){
        Execute statement
    }
    
    int a = 20;
    while (a>0) {
        a--;
        Console.WriteLine("After the conditions are met a After subtraction, the output result is:{0}",a);
    }
    

    for() loop

    A for loop is a repetition control structure that allows you to write a loop that executes a specific number of times.

    for ( init; condition; increment )
    {
       statement(s);
    }
    

    The following is the control flow of the for loop:

    1. init is executed first and only once. This step allows you to declare and initialize any loop control variables. You can also not write any statements here, as long as a semicolon appears.
    2. Next, we will judge the condition. If true, the loop body is executed. If false, the loop body is not executed and the control flow jumps to the next statement immediately following the for loop.
    3. After executing the body of the for loop, the control flow will jump back to the increment statement above. This statement allows you to update loop control variables. The statement can be left blank as long as a semicolon appears after the condition.
    4. The condition is judged again. If true, the loop will be executed, and the process will be repeated (loop body, then increase the step value, and then re judge the condition). When the condition becomes false, the for loop will terminate.
    // for printing triangles
    for (int i = 0;i<8;i++) {
        for (int j = 0;j <=i;j++) {
            Console.Write("* ");
        }
        Console.WriteLine();
    }
    
    *
    * *
    * * *
    * * * *
    * * * * *
    * * * * * *
    * * * * * * *
    * * * * * * * *
    

    foreach loop

    C # also supports foreach loops, which can be used to iterate over arrays or a collection object.

    The following example has three parts:

    • Outputs the elements of an integer array through a foreach loop.
    • Outputs the elements in an integer array through a for loop.
    • The foreach loop sets the calculator for array elements.
    // foreach loop 
    int[] arr = { 1,2,3,4,5,6,7,8,9}; // Define array
    foreach (int elemt in arr) {
        Console.WriteLine("foreach Output each element in the array:{0}",elemt);
    }
    // for loop output array
    for (int i = 0;i<arr.Length;i++) {
        Console.WriteLine("use for Array elements of cyclic output:{0}",arr[i]);
    }
    

    do... while loop

    Unlike for and while loops, they test the loop condition at the loop header. The do... While loop checks its conditions at the end of the loop.

    The do... While loop is similar to the while loop, but the do... While loop ensures that the loop is executed at least once.

    do
    {
       Execute statement
    
    }while(Judgment statement);
    

    Note that the conditional expression appears at the end of the loop, so the statement(s) in the loop will be executed at least once before the condition is tested.

    If the condition is true, the control flow will jump back to the above do and re execute the statement(s) in the loop. This process is repeated until the given condition becomes false.

    int aa = 10;
    // do while loop
    do {
        Console.WriteLine("do...while Cyclic output a: {0}",aa);
    } while (aa>0);
    

Topics: C#