Lesson # 2. Programming on c sharp, condition statements

Дата изменения: 25 февраля 2021
Programming on c sharp in Microsoft Visual Studio. Using the Console Application. If and Switch control statements.

Lesson # 2. C# Theory

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.
  • Labs and tasks

    Console Applications

    To create a console application in visual studio 2019:

    Lab 1. Testing if a number is even (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 (d:\Projects\Lesson_2Lab1\) and upload the file L2Lab1.cs.
    Task 1 for Lesson #2:

    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 for Lesson #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 for Lesson #2:

    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 for Lesson #2:

    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 for Lesson #2:

    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 for Lesson #2:

    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 for Lesson #2:

    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: File (Файл) -> New (Новый) -> Project/Solution (Проект) -> Console Application (Консольное приложение).
    • In the Solution Explorer window (Обозреватель решений) find a file Program.cs 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 for Lesson #2:

    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]


    Windows Forms Applications

    To create a Windows Forms Applications in Visual Studio 2019:
    Lab 2. ListBox

    To do: Create Windows Forms Application to change the Backcolor property of the text field using the ListBox control.
      
    [Solution and Project name: Lesson_2Lab3, form name L2Lab3.cs]
      
    Expected output:

    ✍ Algorithm:

      Controls:

      control name property value text property value
      form L2Lab3
      button btnExit Exit
      textbox txt
      ListBox lst
    1. Note! Give the names to the controls as it is in the specification of C# language and as it is always written in the lab or in the table above.
    2. Create new project (File → New → Project → Windows Forms Application ), and give it a name — Lesson_1Lab4; the form of the project must be named as L2Lab3 (Properties window → (Name) property).
    3. Place the TextBox control named txt and the ListBox control named lst on the form.
    4. In the properties of the ListBox control, select a Items (Collection) property and set four list items for it (by pressing Enter after each item): black, red, blue, green.
    5. Now program the SelectedIndexChanged event for the list, so that when you click on a certain item with a specific color, a background color of the text field changes to the corresponding one. Use the Visual c# If statement when doing this. Make double click on the listBox to open the code:
    6.  private void lst_SelectedIndexChanged(object sender, EventArgs e)
              {
                 // here your code starts:
                  if (lst.SelectedItem == "black")
                  {
                      txt.BackColor = System.Drawing.Color.Black;
                  }
                  else if (lst.SelectedItem == "red")
                  {
                      txt.BackColor = System.Drawing.Color.Red;
                  }
                  else if (lst.SelectedItem == "blue")
                  {
                      txt.BackColor = System.Drawing.Color.Blue;
                  }
                  else if (lst.SelectedItem == "green")
                  {
                      txt.BackColor = System.Drawing.Color.Green;
                  }
              // here your code has finished
              }
      
      System is the namespace;
      Drawing is a namespace that provides access to the functionality of the graphical interface;
      The SelectedIndexChanged event occurs when various items in the data list control are selected.
    7. Run the application and try to change the selected item of the list.
    8. Now, we will consider the second way to set the list items: using the program code. Remove all colors from the Items property of the lst control.
    9. After, you need to add the following code to the Form Load event (make double-click on an empty space of the form design to open the code):
    10. private void Form1_Load(object sender, EventArgs e)
              {
                  // here your code starts:
                  lst.Items.Add("black");
                  // ... add the rest colors here the same way
              }
      
    11. Run and debug the program.
    Extra task.
    Create a Windows forms Application to use a ListBox control to change the width (Width property) of the text field: minimum — 20, middle — 50, maximum — 100.
    Note: you should use the Size property of the text field, and System.Drawing.Size(width value, height value).

    [Solution and Project name: Lesson_2ExTask1, form name L2ExTask1.cs]

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    *
    *


    Вставить формулу как
    Блок
    Строка
    Дополнительные настройки
    Цвет формулы
    Цвет текста
    #333333
    Используйте LaTeX для набора формулы
    Предпросмотр
    \({}\)
    Формула не набрана
    Вставить