Lesson # 2. Programming on c sharp, condition statements

Programming on c sharp in Microsoft Visual Studio. Using the Console Application. If and Switch control statements.

Lesson # 2. C# Theory

Lecture in pdf format

Data Type Conversion

Integer data types:

  • byte
  • short
  • int
  • long

Real data types:

  • float
  • double
  • decimal
Data Type Conversion
  
1. Implicit type conversion;
2. Explicit type conversion;
3. None-compatible types.

  • C# supports two inherent types of conversion (casting) for data types, implicit and explicit. C# will use implicit conversion where it can, mostly in the case when a conversion will not result in a loss of data or when the conversion is possible with a compatible data type. The following is an example of an implicit data conversion:
  • Converting from smaller to larger integral types:

    int myInt = 2147483647;
    long myLong= myInt;
  • The long type has a 64-bit size in memory while the int type uses 32-bits. Therefore, the long can easily accommodate any value stored in the int type. Going from a long to an int may result in data loss however and you should use explicit casting for that if you know what data will be lost and it doesn’t impact your code.
  • Explicit casts are accomplished in one of two ways as demonstrated with the following code sample.
  • double myDouble = 1234.6;
     
    // Cast double to int by placing the type modifier ahead of the type to be converted
    // in parentheses
    int myInt = (int)myDouble;

    The second option is to use the methods provided in the .NET Framework.

    // None-compatible types
    double myDouble = 1234.6;
     
    // Cast double to int by using the Convert class and the ToInt32() method.
    // This converts the double value to a 32-bit signed integer
    int myInt = Convert.ToInt32(myDouble);
  • You will find many other methods in the Convert class that cast to different integral data types such as ToBoolean(), ToByte(), ToChar(), etc.

If the theory is clear, make lab 1.

C# Conditional statement | decision structures

Decision structures

  • C# decision structures provide logic in your application code that allows the execution of different sections of code depending on the state of data in the application.
  • There are two conditional statements in Visual C#. They are if statement (the primary conditional statement) and switch statement (alternative to the if).

IF statement

  • If statements are concerned with Boolean logic. If the statement is true, the block of code associated with the if statement is executed. If the statement is false, control either (и_зер) jumps to the line after the if statement, or after the closing curly brace of an if statement block.
  • string answer = "Yes";
    if (answer == "Yes")
    {
        // statements that will execute if the value of the answer variable is
        // yes, will be placed here.
    }
  • You can remove the curly braces if your statement to execute is a single line statement. C# understands that if no curly braces are used, the line immediately after the if(condition) will be executed if the condition is true. To avoid confusion a recommended practice is to always use curly braces for your if statement.
  •   
    Else clauses

  • IF statements can also have associated else clauses (предложениями). The else clause executes when the if statement is false:
  • string answer;
    if (answer == "yes")
    {
        // Block of code executes if the value of the answer variable is "yes".
    }
    else
    {
        // Block of code executes if the value of the answer variable is not "yes".
    }

    Else if clauses

  • If statements can also have associated else if clauses. The clauses are tested in the order that they appear in the code after the if statement. If any of the clauses returns true, the block of code associated with that statement is executed and control leaves the block of code associated with the entire if construct.
  • string answer;
    if (answer == "yes")
    {
        // Block of code executes if the value of the answer variable is "yes".
    }
    else if (answer == "I_don't_know")
    {
        // Block of code executes if the value of the answer variable is "I_don't_know".
    }
    else
    {
        // Block of code executes if the value of the answer variable is neither above answers.
    }
  • You can create as many else if blocks as necessary.
  • Switch statement

  • If there are too many else if statements, code can become difficult to understand. In this case, a better solution is to use a switch statement:
  • string answer;
    switch (answer)
    {
       case "yes":
          // Block of code executes if the value of answer is "yes".
          break;
       case "I_don't_know":
          // Block of code executes if the value of answer is "I_don't_know".
          break;
       case "no":
          // Block of code executes if the value of answer is "no".
          break;
       default:
          // Block executes if none of the above conditions are met.
          break;
    }
  • There is a block labeled default. This block of code will execute when none of the other blocks match.
  • In each case statement, notice the break keyword. This causes control to jump to the end of the switch after processing the block of code. If you omit the break keyword, your code will not compile.
  • Ternary operator

    int five = 5;
    string answer = five == 5 ? "true" : "false"; // string answer = true

    Labs and tasks

    Console Applications

    To create a console application in visual studio 2019:

    Lab 1. Checking the parity of a number (read theory)

    To do: Request user to input an integer. Convert input to integer. Check to see if the number is even. Output the result (a phrase «The entered number was an even number» or «The entered number was not an even number»).

    Expected output:

    Please enter an integer value and press Enter
    5
    The result: The entered number was not an even number
    
    Please enter an integer value and press Enter
    6
    The result: The entered number was an even number
    

    [Solution and Project name: Lesson_2Lab1, file name L2Lab1.cs]

    ✍ Algorithm:

    • Open Visual Studio.
    • Create a new console project, name your project Lesson_2Lab1 (read the Theory of lesson #1).
    • In the Solution Explorer (Обозреватель решений) window find a file Program.cs and rename it into L2Lab1.cs (right click -> Переименовать).
    • Make sure that the file L2Lab1.cs is active in the Solution Explorer window (Обозреватель решений).
    • Place your cursor immediately after the open curly brace in the Main method, then press enter to create a new line.
    • Request user to input with WriteLine() method:
    • static void Main(string[] args)
        {
           Console.WriteLine("Please enter an integer value and press Enter.");
        }
    • Assign the entered value to the variable numb. Convert numb to integer before using:
    • ...
       int numb = Int32.Parse(Console.ReadLine());
      ...
      
    • Check to see if the number is even. If it is, output the phrase «The entered number was an even number»:
    • ...
      if(numb % 2 == 0)
        {
           Console.WriteLine("The entered number was an even number");
        }
      ...
      
      Checking to see if a number is even

    • It is possible to check a remainder when dividing the number by 2.
    • The (%) or modulus operator returns the remainder of integer devision.
    • If the remainder is 0, then the value is able to be divided by 2 with no remainder, which means it is an even number.
    • Add else section to output the result if the numb is not even (odd). In this case, output the phrase «The entered number was not an even number»:
    • ...
      if(numb % 2 == 0)
        {
           Console.WriteLine("The entered number was an even number");
        }
      else  
        {
           Console.WriteLine("The entered number was not an even number");
        }
      
    • Press the CTRL+F5 keys to start the application without debugging.
    • This will cause Visual Studio to compile the code and to run the application. A console window will open asking you to enter an integer value.
    • Experiment with different values to see the output.
    • Don’t forget to place the text of the task as a comment before the program:
    • To upload the file into the moodle system, find the solution folder on the computer and upload the L2Lab1.cs file.
    Task 1:

    To do: Request user to input an integer. Convert input to integer. Check to see if the number is positive or negative. Output the result (a phrase «positive» or «negative»).
     
    Note: you can use one of the folowing ways to convert the variable:

    1) int numb = Convert.ToInt32(Console.ReadLine());
    2) int numb = Int32.Parse(Console.ReadLine());
    

      

    Expected output:

    Please enter an integer value and press Enter
    50
    The result: The entered number was positive
    
    Please enter an integer value and press Enter
    -7
    The result: The entered number was negative
    

    [Solution and Project name: Lesson_2Task1, file name L2Task1.cs]

    Task 2:

    To do: A two-digit integer is given (is entered). Output its right and left digits (operations %, /).
      
    Note: the number -56 consists of digits 5 and 6, but not -5 and -6. To output an absolute value of the number:

    ...
    // importing namespace with a class Math
    using static System.Math;
    ...
    Math.Abs(number);

      
    Note: Don’t forget to convert the variable for the inputted number to integer type (Int32.Parse(...)).
     

    Expected output:

    Please enter a two-digit number:
    50
    The result: right digit is 0, left digit is 5
    
    Please enter a two-digit number:
    -76
    The result: right digit is 6, left digit is 7
    

    [Solution and Project name: Lesson_2Task2, file name L2Task2.cs]

    Task 3:

    To do: A three-digit number is given (is entered). Set its middle digit to a value of 0.
      
    Note 1: First, you have to get the digits of the number. Then, set the middle digit to 0. Afterward you have to make a number of the digits. To make a number of three digits use the example:

    if we have 1, 2, 3
    1*100 + 2*10 + 3 = 123
    

      
    Note 2: Don’t forget to convert the variable for the inputted number to integer type (Int32.Parse(...)).
     

    Exected output:

    Please enter a three-digit number:
    523
    The digits: 5,2,3; the resulting number: 503
    

    [Solution and Project name: Lesson_2Task3, file name L2Task3.cs]

    Task 4:

    To do: Three integers are given (they are entered). Output true if any two of them are not equal, and false otherwise.
      
    Note: Boolean operation check for inequality is != , logical And operation is &&, logical Or operation is ||:

    if (a!=b || a!=c) {...}

    Expected output:

    Please enter three numbers:
    13, -4, 6 
    The result: true
    
    Please enter three numbers:
    6, -4, 6
    The result: false
    
    Please enter three numbers:
    13, 13, 6 
    The result: false
    

    [Solution and Project name: Lesson_2task4, file name L2Task4.cs]

    Task 5:

    To do: Integers a, b and c are given (they are entered). Print True if a triangle with matching side lengths can exist, print False otherwise. If the triangle exists, print its area.

    Note: Remember the «triangle inequality». To calculate the area, use Heron’s formula (p means half-perimeter):

    Expected output:

    Please enter three numbers:
    4, 8, 6
    The result: exists = true, area is 11.61895003
    

    [Solution and Project name: Lesson_2task5, file name L2Task5.cs]

    Task 6:

    To do: Integer number x is entered. Calculate the value of the function f:

    Note: The sign means boolean or ( || sign in C#):

    // example:
    (a<b)||(a<c)

    Expected output:

    Enter an integer: 
    >>> 4
    Result is 8
    

    [Solution and Project name: Lesson_2task6, file name L2Task6.cs]

    Task 7:

    To do: Real number x is entered. Calculate the value of the function f:

    Note: To calculate sin you should use Math class:

    Math.Sin(x)

    Expected output:

    Enter a real: 
    ...
    

    [Solution and Project name: Lesson_2task7, file name L2Task7.cs]

    Lab 2. Switch statement (read theory)

    To do: Request user to input a number — coffee size (1=small 2=medium 3=large). Output the price (1 — 25 cents, 2 — 50 cents, 3 — 75 cents). Use switch statement.

    Expected output:

    Coffee sizes: 1=small 2=medium 3=large
    Please enter your selection: 
    2
    The result: Please insert 25 cents
    
    Coffee sizes: 1=small 2=medium 3=large
    Please enter your selection: 
    5
    The result: Invalid selection. Please select 1, 2, or 3.
    

    [Solution and Project name: Lesson_2Lab2, file name L2Lab2.cs]

    ✍ Algorithm:

    • Open Visual Studio.
    • Create Console Application with the name Lesson_2Lab2.
    • In the Solution Explorer window (Обозреватель решений) find a Program.cs
      file and rename it into L2Lab2.cs (right ckick -> Переименовать).
    • Place your cursor immediately after the open curly brace in the Main method, then press enter to create a new line.
    • Enter WriteLine method to explain user about the coffee sizes and requesting him to enter his selection:
    • ...
      Console.WriteLine("Coffee sizes: 1=small 2=medium 3=large");
      Console.Write("Please enter your selection: ");
      ...
      
    • Assign the entered value to the variable str of string type:
    • ...
      string str = Console.ReadLine();
      ...
      
    • Initialize a variable price with a value of 0:
    • ...
      int price = 0;
      ...
    • Create a switch statement to test the str variable: if user selected 1 (1 was inputted), the price has to be 25. If 250, if 375.
    • ...
      switch (str)
        {
          case "1":
            price += 25;
            break;
          case "2":
            price += 50;
            break;
          case "3":
            price += 75;
            break;
         ...
        }
      ...
      

    • Enter a default section to output the phrase for the case when a wrong number was inputted:
    • ...
      switch (str)
        {
          case "1":
            price += 25;
            break;
          case "2":
            price += 50;
            break;
          case "3":
            price += 75;
            break;
          default:
            Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
            break;
        }
      ...
      
    • Check the variable price and output the price using c# recommended syntax:
    • ...
      if (price != 0)
                  {
                      Console.WriteLine($"Please insert {price} cents.");
                  }
      ... 
      

    • Press the CTRL+F5 keys to start the application without debugging.
    • Experiment with different values to see the output.
    • Save the project and upload the file into the moodle system.
    Task 8:

    To do: Request user to input a serial number of the day of the week (1, 2, 3, …, 7). Check the input and output the name of the day (Monday1, Tuesday2, etc.).

      
    Expected output:

    Please enter a number from 1 to 7: 
    2
    The result: The 2-d day of the week is Tuesday
    
    Please enter a number from 1 to 7:  
    9
    The result: The are no such days, please enter 1, 2, ..., 7
    

    [Solution and Project name: Lesson_2Task8, file name L2Task8.cs]