Lesson # 1. Programming on c sharp in Microsoft Visual Studio

Programming on c sharp in Microsoft Visual Studio. Using Console Application

Lesson # 1. Introduction C# sharp in Visual Studio

Theory: Microsoft Visual Studio IDE

1. Creating a new empty project.

  1. Open Microsoft Visual Studio.
  2. The menu item File —> New —> Project (Файл -> Создать -> Проект).
  3. In the window that opens, find Visual C# in the New Project Types section. From the Templates (Шаблоны) section, select Console Application (Консольное приложение).
  4. Name the new solution (the field Solution Name) and call the project (the field Name (Имя)).
  5. Save the project to a local disk in an easily accessible location (for example, D:\Projects).
  6. Uncheck the Create directory for solution (Создать каталог для решения) checkbox to avoid multiplying directories unnecessarily.



2. To add new files to the project and Exclude the files.
You can add new files to the project (right-click on the project in the Solution Explorer window (Обозреватель решений) —> Add -> New Item (Создать элемент). For this and any other project, you will need at least one file with an entry point to the program — the main function.

  1. For example, to add a new .cw file to the project with a name task2-L1.cs:
  2. The result is:
  3. Select the Program.cs file in the Solution Explorer window, copy code of the Main function and paste it to a new file. The result has to be so:

  4. Paste the code into task2-L1:

  5. The result is:
  6. Place your cursor immediately after the open curly brace in the Main method, then press enter to create a new line. Place your code:
  7. Exclude the file program.cs from the project to avoid the error (two Main functions cant exist in one project):
  8. Don’t forget to place the text of the task as a comment before the program:


Keyboard shortcuts

  • [CTRL]+k+c — commenting a block of code
  • [CTRL]+k+u — uncommenting a block of code
  • [F5] — to execute the program
  • [CTRL]+F5 — to start the application without debugging
  • Theory: C# Syntax

    Statements

    In C#, a statement is considered a command. Statements perform some action in your code such as calling a method or performing calculations. Statements are also used to declare variables and assign values to them.

    Statements are formed from tokens. These tokens can be keywords, identifiers (variables), operators, and the statement terminator which is the semicolon (;). All statements in C# must be terminated with a semicolon.

    Example:

    int myVariable = 2;

    In this example, the tokens are:

  • int
  • myVariable
  • =
  • 2
  • ;
  • int is the data type used for the variable called myVariable.

    The ‘=‘ is an assignment operator and is used to set the value of myVariable to 2.

    The numeral 2 is known as a literal value. Literal simply means that it is, what it says it is. The numeral 2 cannot be anything but the numeral 2. You cannot assign a value to 2. You can assign the numeral 2 to a variable however, and that is what this C# statement is doing.

    Finally, the statement ends with a semi-colon.


    Identifiers
    In C#, an identifier is a name you give to the elements in your program. Elements in your program include:

    • Namespaces — the .NET Framework uses namespaces as a way to separate class files into related buckets or categories. It also helps avoid naming collisions in applications that may contain classes with the same name
    • Classes — classes are the blueprints for reference types. They specify the structure an object will take when you create instances of the class
    • Methods — they are discrete pieces of functionality in an application. They are analogous to functions in the non-object-oriented programming world
    • Variables — these are identifiers or names, that you create to hold values or references to objects in your code. A variable is essentially a named memory location

    When you create a variable in C# you must give it a data type. The data type tells the compiler and syntax checker what kind of information you intend to store in that variable. If you try to assign data that is not of that type, warnings or errors will inform you of this. This is part of the type-safe nature of C#.

    You can assign a value to the variable at the time you create it or later in your program code. C# will not allow you to use an unassigned variable to help prevent unwanted data from being used in your application. The following code sample demonstrates declaring a variable and assigning a value to it.

    int myVar = 0;

    C# has some restrictions around identifiers that you need to be aware of.

    First off, identifiers are case-sensitive because C# is a case-sensitive language. That means that identifiers such as myVar, _myVar, and myvar, are considered different identifiers.

    Identifiers can only contain letters (upper case or lowercase), digits, and the underscore character. You can only start an identifier with a letter or an underscore character. You cannot start the identifier with a digit. myVar and _myVar are legal but 2Vars is not.

    C# has a set of reserved keywords that the language uses. You should not use these keywords as an identifier in your code. You may choose to take advantage of the case-sensitivity of C# and use Double as an identifier to distinguish it from the reserved keyword double, but that is not a recommended approach.


    Operators

    When writing C# code, you will often use operators. An operator is a token that applies to operations on one or more operands in an expression. An expression can be part of a statement, or the entire statement. Examples include:

    3 + 4 – an expression that will result in the literal value 4 being added to the literal value 3

    counter++ – an expression that will result in the variable (counter) being incremented by one

    Not all operators are appropriate for all data types in C#. As an example, in the preceding list the + operator was used to sum two numbers. You can use the same operator to combine two strings into one such as:

    “Tom” + “Sawyer” which will result in a new string TomSawyer

    You cannot use the increment operator (++) on strings however. In other words, the following example would cause an error in C#.

    “Tom”++

    The following table lists the C# operators by type.

    Type Operators

    Arithmetic

    +, -, *, /, %

    Increment, decrement

    ++, —

    Comparison

    ==, !=, <, >, <=, >=, is

    String concatenation

    +

    Logical/bitwise operations

    &, |, ^, !, ~, &&, ||

    Indexing (counting starts from element 0)

    [ ]

    Casting

    ( ), as

    Assignment

    =, +=, -=, =, /=, %=, &=, |=, ^=, <<=, >>=, ??

    Bit shift

    <<, >>

    Type information

    sizeof, typeof

    Delegate concatenation and removal

    +, —

    Overflow exception control

    checked, unchecked

    Indirection and Address (unsafe code only)

    *, ->, [ ], &

    Conditional (ternary operator)

    ?:

    Labs and Tasks

    Lab 0:
    To do: Create a simple console application that displays a «Hello world!» phrase to the console window.

    [Solution and Project name: HelloWorld, file name hw.cs]

    Algorithm:

    1. Open Visual Studio.
    2. Create a new console project with a name HelloWorld (read the Theory).
    3. In the Solution Explorer window find a file Program.cs and rename it into hw.cs:
    4. The first lines of the code in hw.cs files is a surrounding structure (list of global namespace connections):
    5. using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
    6. Write a program that displays the phrase «Hello, world» into the console. Use the algorithm and help pictures below:
    7.     4.1. Make sure that the file hw.cs is active in the Solution Explorer window.
          4.2. To output something in the console use the method Console.WriteLine(...); . Each line of code with commands must end with a semicolon. Add the method into the correct place of the code: Place your cursor immediately after the open curly brace in the Main method, then press enter to create a new line:

      ...
      static void Main(string[] args)
              {
                   Console.WriteLine("Hello world!");
              }
      ...

    8. Start debugging:

    9. To output in console window:

      Console.WriteLine(...);

      if you have to output the value of the variable:

      Console.WriteLine(x);

    10. To see console window use keybort shortcut [CTRL]+F5 (to start the application without debugging) or method Console.ReadKey();:
    11. ...
      static void Main(string[] args)
              {
                  Console.WriteLine("hello World!!!");
                  Console.ReadKey();
              }
      ...
    12. Start debugging again. Save the solution. To save all the files use the button:
    13. Don’t forget to place the text of the task as a comment before the program:
    14. To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\helloWorld\) and upload the file hw.cs:

    Lab 1:
    To do: Create variables of different data types, initialize them with a «default» value, assign some values, output to the console window.

    [Solution and Project name: Lesson_1Lab_1, file name Program.cs]

    Algorithm:

    1. Open Visual Studio.
    2. Select File -> New -> Project
    3. From the Templates section, select Visual C#
    4. Select Console Application
    5. Name your project, such as Lesson_1Lab_1
    6. Choose a location to store the project
    7. Click the OK button and Visual Studio will create a new C# Console application project for you and opens Program.cs for you in the editor window.
    8. Place your cursor immediately after the open curly brace in the Main method, then press enter to create a new line
    9. Enter the following code to create variables of different data types, assign values, and output the results to the Console window:

    10. Press the CTRL+F5 keys to start the application without debugging, or, using the menus, select Debug then Start Without Debugging.
    11. This will cause Visual Studio to compile the code and the run the application. A console window will open displaying the results if no errors are encountered.
    12. Save the project. To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_1Lab_1\) and upload the file Program.cs

    Task 1 for Lesson #1 (HOMETASK):
    To do: Create a C# Console application. Within the Main() method in this application, create variables of the correct data type, using the information presented below. Once you have the variables created, use assignment statements to assign values to the variables and use the Console.WriteLine() method to output the values to the console window.

    Student Information:
    First Name | Last Name | Birthdate | Address | Gender | Country
    Course Information:
    Course Name | Credits | Duration in Weeks | Teacher
    

      
    Note: for the person’s gender use characteristic type:

    char gender='m';

     
    [Solution and Project name: Lesson_1Task1, file name L1Task1.cs]

    The result:

    Student Information: 
    First Name: Ivan, Last Name: Ivanov, Birthdate: 1993 1 2,
    Address: Rostov-on-Don, Gender: m, Country: Russia
    Course Information:
    Course Name: CS211, Credits:56, Duration in Weeks: 16, Teacher: Mayer Svetlana
    


    Input data

    • To input some data use a standart method ReadLine():
    • Console.ReadLine()
    • To input data and set it to the integer variable n:
    • 1.

      int n = int.Parse(Console.ReadLine());

      where int means integer type of the variable n;
      int.Parse — method to transform string type of the inputted data into integer type.
      2.

      int n = Convert.ToInt32(Console.ReadLine());
    • The same you can do if you use two variables: at first, the inputted data is saved into a string variable (s), afterward this value is transformed into integer and saved into integer type variable (n):
    • String s = Console.ReadLine();
      int n = int.Parse(s);


    Lab 2. Increasing the number by one
    To do: Request a number (input it). Increase the inputted number by one. Output the result.

    [Solution and Project name: Lesson_1Lab2, file name L1Lab2.cs]
      
    The resulting example:

    Input the number, please
    5
    The result: 6
    


    Algorithm:

    1. Open Visual Studio.
    2. Create Console Application with the name Lesson_1Lab2: File -> New -> Project/Solution -> Console Application.
    3. In the Solution Explorer window find a file Program.cs and rename it into L1Lab2.cs.
    4. Inside the Main function ask user to input a number:
    5. ...
      static void Main(string[] args)
       {
          Console.WriteLine("Input a number, please");
       }
      ...
    6. Add the declaration code for an integer variable n and request a value for it (input):
    7. ...
        Console.WriteLine("Input a number, please");
        int n = int.Parse(Console.ReadLine());
      ...
    8. Add a code to increment the variable by one and output its value. Then place an operator to delay the console window:
    9. ...
      n++;
      Console.WriteLine(n);
      Console.ReadKey();
      ...
    10. In General, the file code should look like this:
    11. using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
       
      namespace Lesson_1
      {
          class L1Lab2
          {
              static void Main(string[] args)
              {
                  Console.WriteLine("Input a number, please");
                  int n = int.Parse(Console.ReadLine());
                  n++;
                  Console.WriteLine(n);
                  Console.ReadKey();
              }
          }
      }
    12. Start debugging the application (F5).
    13. Don’t forget to place the text of the task as a comment before the program.
    14. Save the project. To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_1Lab2\) and upload the file L1Lab2.cs.

    Task 2 for Lesson #1:

    To do: Create a console application that calculates the arithmetic mean (average) of two given integers and outputs a result to the console window.

    [Solution and Project name: Lesson_1Task2, file name L1Task2.cs]

    The result:

    Please, input two integers:
    2  6
    The average is 4
    


    Note: In order for the division to be performed in a real type, one of the operands must be real (double type in c#). The easiest way to achieve this is to use 2.0 as a divisor (e.g. (a + b) / 2.0).

    Lab 3. Boolean type
    To do: Three integers are given: A, B and C (they are inputted). Output the value true to the console window if the double inequality A < B < C is true, and output false otherwise.
      
    Note: do not use the conditional operator.

    [Solution and Project name: Lesson_1Lab3, file name L1Lab3.cs]
      
    The resulting example:

    Input three numbers, please
    5  7  10
    The result: true
    
    Input three numbers, please
    8  7  10
    The result: false
    


    Algorithm:

    1. Open Visual Studio.
    2. Create Console Application with the name Lesson_1Lab3: File -> New -> Project/Solution -> Console Application.
    3. In the Solution Explorer window find a file Program.cs and rename it into L1Lab3.cs.
    4. Inside the Main function ask user to input three numbers:
    5. ...
      static void Main(string[] args)
       {
          Console.WriteLine("Input three numbers, please");
       }
      ...
    6. Add the declaration code for three integer variables (A, B, C) and request the values for them (input):
    7. ...
        Console.WriteLine("Input three numbers, please");
        int a = int.Parse(Console.ReadLine());
        int b = int.Parse(Console.ReadLine());
        int c = int.Parse(Console.ReadLine());
      ...

      To use two or more comparative operators in C# you must put logic operator && which means AND:

      A < B && B < C

    8. Add a code to output a result of a double comparison of the variables to the console window (if a < b and b < c the result will be true, and otherwise - false):
    9. ...
      Console.WriteLine(a<b && b<c);
      Console.ReadKey();
      ...
    10. Start debugging the application (F5).
    11. To make the output more beautiful you can use another way (c# recommended syntax):
    12. ...
      //Console.WriteLine(a<b && b<c);
      Console.WriteLine($"{a}<{b}<{c}={a < b && b<c}");
      Console.ReadKey();
      ...
    13. In this case, you must use the symbol $. There are the placeholders in the curly brackets, they are for the values of variables.
    14. Start debugging. The result will be the same but more beautiful.
    15. Don't forget to place the text of the task as a comment before the program.
    16. Save the project. To upload the file into the moodle system, find the solution folder on the computer (d:\Projects\Lesson_1Lab3\) and upload the file L1Lab3.cs.

    Task 3 for Lesson #1:

    To do: Four numbers are given: x1, x2, x3, x4. Print true if the sum of the first two numbers (x1, x2) is greater than the sum of the next two numbers (x3, x4), and print false otherwise.
      
    Note: Do not use the conditional operator.
     
    [Solution and Project name: Lesson_1Task3, file name L1Task3.cs]

    The result:

    Please, input four integers:
    2  6  5  1
    The result: true
    
    Please, input four integers:
    2  6  5  7
    The result: false
    

    Поделитесь уроком с коллегами и друзьями:[SvenSoftSocialShareButtons]

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

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

    *
    *


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