From 4b0f5ebd728188da4a223230a09649102f498f4c Mon Sep 17 00:00:00 2001 From: borb Date: Thu, 3 Jul 2025 15:24:51 +0300 Subject: [PATCH] Work on lectures 1 and 2 --- ...roduction-to-csharp-and-dotnet-slides.html | 147 +++++ 1-introduction-to-csharp-and-dotnet.md | 29 +- 2-variables-and-types-slides.html | 524 ++++++++++++++++++ 2-variables-and-types.md | 417 ++++++++------ 4 files changed, 940 insertions(+), 177 deletions(-) create mode 100644 1-introduction-to-csharp-and-dotnet-slides.html create mode 100644 2-variables-and-types-slides.html diff --git a/1-introduction-to-csharp-and-dotnet-slides.html b/1-introduction-to-csharp-and-dotnet-slides.html new file mode 100644 index 0000000..3cd5f48 --- /dev/null +++ b/1-introduction-to-csharp-and-dotnet-slides.html @@ -0,0 +1,147 @@ +
+

Introduction to C# and .NET

+

+
+
+

Overview

+

Installing Visual Studio

+

A Brief History of .NET and C#

+

Creating Your First Application

+

Statements

+

Errors in Visual Studio 2022

+

Comments

+

Installing Visual Studio

+
    +
  • Note: Visual Studio and Visual Studio Code are NOT the same thing +
      +
    • Visual Studio is a full-blown IDE (integrated development environment)
    • +
    • Visual Studio Code is more akin to text editors like Sublime Text, Atom etc.
    • +
    • While both can be used in certain situations, the C# and ASP.NET portions of this training assume that you are using Visual Studio
    • +
    +
  • +
  • You can download the free version (Visual Studio Community) from https://visualstudio.microsoft.com/vs/community/
  • +
  • This downloads the setup executable for VS, which will be used to download all the modules needed (see the next slide)
  • +
+

Installing Visual Studio (cont.)

+
    +
  • After launching the setup executable, you will be prompted to select the components to be installed along with VS. For our purposes you will need "ASP.NET and web development" portion, found in the "Workloads" tab
  • +
  • Click "Install" found in the lower right corner to begin installing VS and the required components
  • +
  • Note: The installation can be quite large (8 GB or more) depending on which components are already installed on your system, so we recommend using a personal hotspot if possible +
      +
    • Multiple people downloading large amounts of data using the same public WIFI network will bog down the download speed for everyone
    • +
    +
  • +
  • After installing VS, you can skip the account creation portion
  • +
+

+

.NET

+
    +
  • +

    .NET is Microsoft's software framework that turns your code (C#, F# or VB) into machine language

    +
  • +
  • +

    Two types of .NET Frameworks:

    +
      +
    • .NET Framework +
        +
      • 2001
      • +
      • Windows only
      • +
      • Comes pre-installed with every Windows OS
      • +
      +
    • +
    • .NET Core +
        +
      • 2016
      • +
      • "Successor to .NET Framework"
      • +
      • Open source! https://github.com/dotnet/ core
      • +
      • Cross-platform (Linux, Mac, Windows)
      • +
      • We will be using .NET Core during this course as the old .NET Framework is pretty much legacy
      • +
      +
    • +
    +
  • +
  • +

    Base Class Library (BCL)

    +
      +
    • A set of libraries that every .NET implementation uses
    • +
    • The libraries consist of common activities, like classes and value types, that you will use to create your programs
    • +
    • No need to reinvent the wheel with every new project
    • +
    +
  • +
+

using System;

+

using System.Collections.Generic;

+

using System.Linq;

+

using System.Threading.Tasks;

+

C#

+

C# was developed for .NET Framework in 2000

+

Microsoft wanted a Windows exclusive competitor for Java

+

Easy to understand, general purpose, object oriented

+

+

Source: http://pypl.github.io/PYPL.html

+

Creating a Console Application

+

Open Visual Studio 2022.

+

Select "Create a new project"

+

Type "console" to the search bar and select the following template:

+

+

Running a Console Application

+

To run your program, select "Debug" -> "Start Debugging" __or __ press F5 __or __ press the small play sign preceding your project name at the top middle

+

The template project should now run and print "Hello World!" to the console. Try changing the code so that it prints something else!

+

C# Syntax - Statements

+
using System;
+
+namespace MyAwesomeProgram
+{
+    class Program
+    {
+        static void Main(string[] args)
+        {
+            Console.WriteLine("Hello World!");
+        }
+    }
+}
+
+

Rows = statements

+

Curly brackets ' _{' _ and ' _}' _ mark the start and the end of different _bodies _ of statements

+

Semicolon at the end of some statements

+

When to use semicolon? Don't worry: Visual Studio will tell you

+

C# Syntax - Errors in Visual Studio 2022

+

Why is this throwing an error?

+

Missing one closing curly bracket

+

+

Hovering on the red underline will show a hint for the error:

+

+

All errors can be displayed by pressing the red cross in the bottom:

+

+

C# Syntax - Comments

+

There are two basic ways to comment in C#:

+

// This is a comment

+

/* This is a

+

multi

+

line

+

comment */

+

Any text inside a comment will not be executed

+

Use comments to explain your code or comment out actual code for testing and debugging

+

try online

+

https://www.programiz.com/csharp-programming/online-compiler/

+

Assignments

+

Assignments about this topic can be found here

+
+
\ No newline at end of file diff --git a/1-introduction-to-csharp-and-dotnet.md b/1-introduction-to-csharp-and-dotnet.md index 4eb6e79..6e5562b 100644 --- a/1-introduction-to-csharp-and-dotnet.md +++ b/1-introduction-to-csharp-and-dotnet.md @@ -95,27 +95,20 @@ The template project should now run and print "Hello World!" to the console. Try # C# Syntax - Statements +```c# using System; namespace MyAwesomeProgram - -{ - -class Program - { - -static void Main(string[] args) - -{ - -Console.WriteLine("Hello World!"); - -} - -} - + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } } +``` Rows = statements @@ -159,6 +152,10 @@ Any text inside a comment will not be executed Use comments to explain your code or comment out actual code for testing and debugging +## try online + +https://www.programiz.com/csharp-programming/online-compiler/ + # Assignments [Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/1.%20C%23%20Basics%20Assignments) diff --git a/2-variables-and-types-slides.html b/2-variables-and-types-slides.html new file mode 100644 index 0000000..cbf9f82 --- /dev/null +++ b/2-variables-and-types-slides.html @@ -0,0 +1,524 @@ +2. Variables and Types
+

Variables and Types

+
+
+

Overview

+
    +
  • Variables
  • +
  • Data Types
  • +
  • Arithmetic Operators
  • +
  • Increment & Decrement
  • +
  • Assignment Operators
  • +
  • Strings
  • +
  • Character Constants
  • +
  • String Interpolation
  • +
+
+
+

Variables

+
    +
  • A variable can be thought of as a name for a certain address in computer's memory +
      +
    • Using this name we can access the value on the computer's memory
    • +
    • The value can be read or written
    • +
    +
  • +
  • On more practical terms: We can assign values to named variables.
  • +
+
+
+

Declaring variables

+
    +
  • Every variable declaration in C# requires the type and the name of the variable, for example:
    int x;
    +
    +
  • +
  • After declaration, you can assign a value for declared variables:
    x = 25;
    +
    +
  • +
  • Variable declaration with value assignment can be done in one line:
    int x = 25;
    +
    +
  • +
+
+
+

Printing to console with Console.WriteLine

+
+
+
    +
  • We can use the method Console.WriteLine to write, a.k.a. print to the C# console
    Console.WriteLine("Hello World!")
    +
    +
  • +
  • We can also declare variables and print their values like this:
    int example = 123;
    +Console.WriteLine(example);
    +// prints 123
    +
    +
  • +
+
+
+

This program prints the value 15:

+
using System;
+namespace MyAwesomeProgram
+{
+  class Program
+  {
+    static void Main(string[] args)
+    {
+      int a = 25;
+      int b = 10;
+      Console.WriteLine(a - b);
+    }
+  }
+}
+
+
+
+
+
+

Extra: Modifiers

+ +
    +
  • A common modifier to add in front of a variable is const, short for constant
  • +
  • If we know that a value of a variable is never going to change during the execution of the script, we can set it to const:
    const int one = 1;
    +
    +one = 2;  // raises an error
    +
    +
  • +
  • Some programmers prefer using const by default.
  • +
  • Other modifiers include access modifiers introduced in Lecture 7.
  • +
+
+
+

Data types

+
+
+

What is a data type?

+
    +
  • Data type tells to a computer what type of data is stored in a variable.
  • +
  • Data types are commonly divided into two categories: +
      +
    • Primitive data types
    • +
    • Reference data types
    • +
    +
  • +
  • Here we go through the primitive data types +
      +
    • We dig deeper on the differences of these data types later in Lecture 7
    • +
    +
  • +
+
+
+

Primitive data types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeRepresentsRangeDefault
boolBoolean valuetrue or falsefalse
int32-bit signed integer to 0
float32-bit single-precision float to 0.0F
double64-bit double-precision float to 0.0D
decimal128-bit precise decimal values to 0.0M
char16-bit Unicode characterU+0000 to U+ffff\0
byte8-bit unsigned integer to 0
+

More types listed in the C# reference!

+
+
+

Data type examples

+
double airPressure = 1.2;         // Use for most decimal numbers
+decimal accountBalance = 1.2m;    // Use for accuracy (e.g. financial applications)
+float bulletSpeed = 1.2f;         // Use only when you know its precision will be enough
+bool loggedIn = false;
+char previousInput = 'b';
+
+
    +
  • char is only used for single characters, multi-character strings will be introduced in a bit.
  • +
+
+
+

Extra: Casting data types

+ +

Data types can be cast to another either...

+
+
+

...implicitly:

+
double valueAddedTax = 25.5;
+decimal valueAddedTaxDecimal = valueAddedTax;
+
+
+
+

...explicitly:

+
double valueAddedTax = 25.5;
+decimal valueAddedTaxDecimal = (decimal)valueAddedTax;
+
+
+
+
    +
  • Casting is useful when, for example, when we want to sum a double and a decimal together:
    double a = 1.0;
    +decimal b = 2.1m;
    +Console.WriteLine(a + (double)b);
    +Console.WriteLine((decimal)a + b);
    +
    +
  • +
  • C# Guide: Casting and type conversions
  • +
+
+
+

Assignments (variables)

+ +

Assignments about this topic can be found here

+
+
+

Assignments (data types)

+ +

Assignments about this topic can be found here

+
+
+

Arithmetic operations?

+
    +
  • Arithmetic operations are common mathematical operations: +
      +
    • Addition
    • +
    • Subtraction
    • +
    • Multiplication
    • +
    • Division
    • +
    • Modulus (remainder, in Finnish jakojäännös)
    • +
    +
  • +
  • The operations are represented by arithmetic operators
  • +
+
+
+

Arithmetic Operators

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExampleDescription
+Additiona + bAdds together two values
-Subtractiona - bSubtracts one value from another
*Multiplicationa * bMultiplies two values
/Divisiona / bDivides one value by another
%Modulusa % bReturns the division remainder
++Incrementa++Increases the value by 1
--Decrementa–-Decreases the value by 1
+
+
+

Exercise 1: Trying Out Variables

+ +
    +
  1. Create a new console application and declare two variables of type double.
  2. +
  3. Assign different values for those variables.
  4. +
  5. Print the sum, difference, fraction and product of those values to the console.
  6. +
+
+
+

The assignment operator

+

We have used the assignment operator = for assigning values for variables:

+
int x;
+x = 25;
+
+
    +
  • Note the difference between = and == introduced in Lecture 3! +
      +
    • = is used for assigning values for variables, == is used for comparing values
    • +
    +
  • +
+
+
+

Assignment operators

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorExampleSame As
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5
+
+
+
    +
  • As shown here, there are some assignment operators that work as shorthands for longer assignments
  • +
  • Particularly useful when the variable name is longer, so you don't have to write it twice when its value is changed
  • +
+
+
+
+
+

Assignment operators: An example

+
int uppercaseLetters = 2;
+uppercaseLetters += 4;          // is now 6
+
+int specialCharacters = 2;
+specialCharacters *= 2;         // is now 4
+
+Console.WriteLine(uppercaseLetters);
+Console.WriteLine(specialCharacters);
+
+
+
+

Increment and decrement operations

+
    +
  • You can increment or decrement a variable value by 1 with dedicated short-hands +
      +
    • Most programming languages implement these!
    • +
    +
  • +
+
+
+
    +
  • Addition example:
    int a = 3;
    +
    +a = a + 1;  // a is now 4
    +a += 1;     // a is now 5
    +a++;        // a is now 6
    +
    +
  • +
+
+
+
    +
  • Subtraction example:
    int a = 3;
    +
    +a = a - 1;  // a is now 2
    +a -= 1;     // a is now 1
    +a--;        // a is now 0
    +
    +
  • +
+
+
+
    +
  • ++ and -- are called the increment and decrement operators
  • +
+
+
+

Extra: Increment/decrement operation precedence

+ +
    +
  • Note that incrementing can be written as prefix (++i) or a postfix (i++)
  • +
  • In this example, a++ and ++a do exactly the same:
    int a = 3;
    +a++; // a is now 4
    +++a; // a is now 5
    +
    +
  • +
  • Their exact difference is complicated, and in some cases, using either prefix or postfix form can produce different results:
  • +
+
+
+
int a = 3;
+int b = ++a;
+Console.WriteLine(b); // 4
+
+

Assignment of b happens after ++,
+so its value is 4

+
+
+
int a = 3;
+int b = a++;
+Console.WriteLine(b); // 3
+
+

Assignment of b happens before ++,
+so its value is 3

+
+
+
+
+

Strings

+

String is a special type, which contains an array of characters. You can declare and assign strings like any other type of variables:

+

string name = "Johannes Kantola";

+

You can concatenate multiple strings with the '+' operator:

+

string firstName = "Johannes";

+

string lastName = "Kantola";

+

string fullName = firstName + " " + lastName;

+

Console.WriteLine(fullName); // Outputs "Johannes Kantola"

+
+
+

Character Constants

+

Character constants are preceded by a backslash '\' and can be used for formatting strings

+

'\n' represents a newline in the following example:

+

string firstName = "Johannes";

+

string lastName = "Kantola";

+

string fullName = firstName + "\n" + lastName;

+

Console.WriteLine(fullName);

+

/* This outputs

+

Johannes

+

Kantola

+

*/

+

All character constants: https://www.tutorialspoint.com/csharp/csharp_constants.htm

+
+
+

String Interpolation

+

Concatenating multiple variables into one string with the '+' operator quickly becomes tedious

+

It's much easier to use __string interpolation __ by prefixing your target string with '$' and inserting the variables inside curly brackets '{ }':

+

string animal = "Dog";

+

string sound = "Woof";

+

Console.WriteLine($"{animal} says {sound}!");

+

// Outputs "Dog says Woof!"

+
+
+

String Formatting

+

You can add format strings to change the way variables are interpolated into a string

+

Add the format string after your variable, separated by a colon (:)

+

You can find an overview of format strings and a handy list of both standard and custom strings here

+

double pi = 3.141592653;

+

Console.WriteLine($"Pi to three digits: {pi:G3}");

+

// Outputs "Pi to three digits: 3.14"

+
+
+

Console.ReadLine()

+

For the next exercise, you'll need the Console.ReadLine() method. The method pauses the program, waits for an input stream from the console that pops up, and returns the value of the input:

+

string userInput = Console.ReadLine();Console.WriteLine(userInput);

+

+
+
+

Exercise 2: Weekday survey

+ +

Create a console application which asks the user which weekday it is and assigns the answer to a string variable.

+

Print "Have a nice weekday!" to the console where weekday is replaced with the string the user wrote.

+
+
+

Assignments (arithmetic operations)

+ +

Assignments about this topic can be found here

+
+
\ No newline at end of file diff --git a/2-variables-and-types.md b/2-variables-and-types.md index 83c0575..913729c 100644 --- a/2-variables-and-types.md +++ b/2-variables-and-types.md @@ -1,242 +1,334 @@ -# Variables & Types - -![](imgs/2%20Variables%20and%20Types_0.png) - +--- +marp: true +paginate: true +math: mathjax +theme: buutti +title: 2. Variables and Types --- -# Overview - -Variables - -Data Types - -Arithmetic Operators - -Increment & Decrement - -Assignment Operators +# Variables and Types -Strings + + -Character Constants +## Overview -String Interpolation +* Variables +* Data Types +* Arithmetic Operators +* Increment & Decrement +* Assignment Operators +* Strings +* Character Constants +* String Interpolation -# Variables +## Variables -* Variable can be thought of as a name for a certain point in computer's memory. -* Using this name we can access the value on the computer's memory - * We can read the value - * We can manipulate the value +* A variable can be thought of as a name for a certain address in computer's memory + * Using this name we can access the value on the computer's memory + * The value can be read or written * On more practical terms: We can assign values to named variables. -# C# Syntax - Declaring Variables - -Every variable declaration in C# requires the type and the name of the variable, for example: - -int x; - -You can assign a value for declared variables: - -x = 25; - -Variable declaration with value can be executed with one line: - -int x = 25; - +### Declaring variables + +* Every variable declaration in C# requires the ***type*** and the ***name*** of the variable, for example: + ```csharp + int x; + ``` +* After declaration, you can assign a ***value*** for declared variables: + ```csharp + x = 25; + ``` +* Variable declaration with value assignment can be done in one line: + ```csharp + int x = 25; + ``` + +### Printing to console with `Console.WriteLine` + +
+
+ +* We can use the method `Console.WriteLine` to write, a.k.a. ***print*** to the C# console + ```csharp + Console.WriteLine("Hello World!") + ``` +* We can also declare variables and print their values like this: + ```csharp + int example = 123; + Console.WriteLine(example); + // prints 123 + ``` + +
+
+ +This program prints the value `15`: +```csharp using System; - namespace MyAwesomeProgram - -{ - -class Program - -{ - -static void Main(string[] args) - { - -int a = 25; - -int b = 10; - -Console.WriteLine(a - b); - + class Program + { + static void Main(string[] args) + { + int a = 25; + int b = 10; + Console.WriteLine(a - b); + } + } } +``` -} - -} +
+
-Everything within a console application executes inside the Main body +### Extra: Modifiers + -This program prints the value "15" to the console +* A common modifier to add in front of a variable is `const`, short for ***constant*** +* If we know that a value of a variable is never going to change during the execution of the script, we can set it to `const`: + ```c# + const int one = 1; + + one = 2; // raises an error + ``` +* Some programmers prefer using `const` by default. +* Other modifiers include ***access modifiers*** introduced in [Lecture 7](7-classes-and-objects#access-modifiers). -# Why we use variables? +## Data types -Variables are key ingredients in programming. - -We don't need to know the exact values when we write the code but the values can be given later while the program is executed - -As an example we can take an input from a user and store it to a variable and use that value somewhere later in our program - -# What is a data type? +### What is a data type? * Data type tells to a computer what type of data is stored in a variable. * Data types are commonly divided into two categories: * Primitive data types * Reference data types * Here we go through the primitive data types - * We dig deeper on the differences of these data types later in the Classes and Objects -section - -# Primitive Data Types in C# + * We dig deeper on the differences of these data types later in [Lecture 7](7-classes-and-objects#value-and-reference-types) -| __Type__ | __Represents__ | __Range__ | __Default Value__ | -| :-: | :-: | :-: | :-: | -| __bool__ | __Boolean value__ | __True or False__ | __False__ | -| __byte__ | __8-bit unsigned integer__ | __0 to 255__ | __0__ | -| __char__ | __16-bit Unicode character__ | __U +0000 to U +ffff__ | __\\0'__ | -| __decimal__ | __128-bit precise decimal values with 28-29 significant digits__ | __(-7.9 x 1028 to 7.9 x 1028) / 100 to 28__ | __0.0M__ | -| __double__ | __64-bit double-precision floating point type__ | __(+/-)5.0 x 10-324 to (+/-)1.7 x 10308__ | __0.0D__ | -| __float__ | __32-bit single-precision floating point type__ | __-3.4 x 1038 to + 3.4 x 1038__ | __0.0F__ | -| __int__ | __32-bit signed integer type__ | __-2,147,483,648 to 2,147,483,647__ | __0__ | +## Primitive data types -More types listed here: +| Type | Represents | Range | Default | +|:----------|:-------------------------------|:-------------------------------------------------|:--------| +| `bool` | Boolean value | `true` or `false` | `false` | +| `int` | 32-bit signed integer | $-2147483648$ to $2147483647$ | `0` | +| `float` | 32-bit single-precision float | $±1.5 \cdot 10^{-45}$ to $±3.4 \cdot 10^{38}$ | `0.0F` | +| `double` | 64-bit double-precision float | $±5.0 \cdot 10^{-324}$ to $±1.7 \cdot 10^{308}$ | `0.0D` | +| `decimal` | 128-bit precise decimal values | $±1.0 \cdot 10^{-28}$ to $±7.9228 \cdot 10^{28}$ | `0.0M` | +| `char` | 16-bit Unicode character | `U+0000` to `U+ffff` | `\0` | +| `byte` | 8-bit unsigned integer | $0$ to $255$ | `0` | -[https://www.w3schools.com/cs/cs\_data\_types.asp](https://www.w3schools.com/cs/cs_data_types.asp) +More types listed in the [C# reference](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types)! -# Data Types in C# - Example - -double airPressure = 1.2; // Use generally for everything +### Data type examples +```csharp +double airPressure = 1.2; // Use for most decimal numbers decimal accountBalance = 1.2m; // Use for accuracy (e.g. financial applications) - -float bulletSpeed = 1.2f; // Use only when you know the precision will be enough (in other words, don't use) - +float bulletSpeed = 1.2f; // Use only when you know its precision will be enough bool loggedIn = false; - char previousInput = 'b'; +``` -# Assignments (variables) +* `char` is only used for single characters, multi-character ***strings*** will be introduced in a bit. -[Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/2.1.%20Variables%20&%20Types) +## Extra: Casting data types + -# Assignments (data types) +Data types can be ***cast*** to another either... -[Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/2.2.%20Data%20Types) +
+
-# What are arithmetic operations? +...implicitly: +```csharp +double valueAddedTax = 25.5; +decimal valueAddedTaxDecimal = valueAddedTax; +``` -The arithmetic operations are common mathematical operations: +
+
-addition +...explicitly: +```csharp +double valueAddedTax = 25.5; +decimal valueAddedTaxDecimal = (decimal)valueAddedTax; +``` -subtraction +
+
-multiplication +* Casting is useful when, for example, when we want to sum a `double` and a `decimal` together: + ```csharp + double a = 1.0; + decimal b = 2.1m; + Console.WriteLine(a + (double)b); + Console.WriteLine((decimal)a + b); + ``` +* [C# Guide: Casting and type conversions](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions) -division +## Assignments (variables) + -modulus (remainder, in Finnish jakojäännös) +[Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/2.1.%20Variables%20&%20Types) -exponentiation +## Assignments (data types) + -Earlier we used an _arithmetic operator _ to subtract b from a: +[Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/2.2.%20Data%20Types) -Console.WriteLine(a - b); +## Arithmetic operations? -# Arithmetic Operators +* ***Arithmetic operations*** are common mathematical operations: + * Addition + * Subtraction + * Multiplication + * Division + * Modulus (remainder, in Finnish *jakojäännös*) +* The operations are represented by **_arithmetic operators_** -| Operator | Name | Example | Description | -| :-: | :-: | :-: | :-: | -| + | Addition | a + b | Adds together two values | -| - | Subtraction | a - b | Subtracts one value from another | -| * | Multiplication | a * b | Multiplies two values | -| / | Division | a / b | Divides one value by another | -| % | Modulus | a % b | Returns the division remainder | -| ++ | Increment | a++ | Increases the value of a variable by 1 | -| -- | Decrement | a–- | Decreases the value of a variable by 1 | +## Arithmetic Operators ---- +| Operator | Name | Example | Description | +|:---------|:---------------|:--------|:---------------------------------------| +| `+` | Addition | `a + b` | Adds together two values | +| `-` | Subtraction | `a - b` | Subtracts one value from another | +| `*` | Multiplication | `a * b` | Multiplies two values | +| `/` | Division | `a / b` | Divides one value by another | +| `%` | Modulus | `a % b` | Returns the division remainder | +| `++` | Increment | `a++` | Increases the value by 1 | +| `--` | Decrement | `a–-` | Decreases the value by 1 | -Tässä on kaikki aritmeettiset operaattorit +## Exercise 1: Trying Out Variables + -# Exercise 1: Trying Out Variables +1) Create a new console application and declare two variables of type `double`. +2) Assign different values for those variables. +3) Print the sum, difference, fraction and product of those values to the console. -Create a new console application as we did in the last exercise and declare two variables of type __double__ _._ +## The assignment operator -Assign different values for those variables. +We have used the assignment operator `=` for assigning values for variables: + ```csharp + int x; + x = 25; + ``` +* ***Note*** the difference between `=` and `==` introduced in [Lecture 3](3-conditionals#comparison-operators)! + * `=` is used for assigning values for variables, `==` is used for ***comparing*** values -Print the __sum__ , __difference__ , __fraction __ and __product __ of those values to the console. +### Assignment operators -# Increment & Decrement +
+
-Increment and decrement operations are operations that can be used to increment or decrement a variable value by 1. +| Operator | Example | Same As | +|:---------|:---------|:------------| +| `=` | `x = 5` | `x = 5` | +| `+=` | `x += 5` | `x = x + 5` | +| `-=` | `x -= 5` | `x = x - 5` | +| `*=` | `x *= 5` | `x = x * 5` | +| `/=` | `x /= 5` | `x = x / 5` | +| `%=` | `x %= 5` | `x = x % 5` | -Most programming languages implement these operations +
+
-Addition example: int a = 3; a = a + 1; _// a is now 4_ Can be written with increment: int a = 3; a++; _// a is now 4_ +* As shown here, there are some assignment operators that work as ***shorthands*** for longer assignments +* Particularly useful when the variable name is longer, so you don't have to write it twice when its value is changed -Decrement is like increment but with just subtraction +
+
-Substraction example: int a = 3; a = a - 1; _// a is now 2_ Can be written with decrement: int a = 3; a--; _// a is now 2_ -Increment and decrement operators can be written in two ways. So sometimes you may also see this: int a = 3; --a; _// a is now 2_ _ _ ++a; _// a is now 3_ +### Assignment operators: An example -This will do the same thing as a++ and a--. There is a small difference between these syntaxes though. +```csharp +int uppercaseLetters = 2; +uppercaseLetters += 4; // is now 6 -int a = 3;const _ _ b = _ _ a++; _// b will be 3_ Console.WriteLine(a); _// this will print out 4_ Here the assignment to b happens before incrementing a, thus b will be assigned value 3. +int specialCharacters = 2; +specialCharacters *= 2; // is now 4 -int a = 3;const _ _ b = _ _ ++a; _// b will be 4_ Console.WriteLine(a); _// this will print out 4_ Here the assignment to b happens after incrementing a, thus b will be assigned value 4. +Console.WriteLine(uppercaseLetters); +Console.WriteLine(specialCharacters); +``` ---- +### Increment and decrement operations -Täällä voi helposti demota: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment +* You can increment or decrement a variable value by 1 with dedicated short-hands + * Most programming languages implement these! -# Assignment Operators +
+
-We have used the assignment operator ' __='__ for assigning values for variables: +* Addition example: + ```csharp + int a = 3; -int x; + a = a + 1; // a is now 4 + a += 1; // a is now 5 + a++; // a is now 6 + ``` -x = 25; +
+
-__Notice __ the difference between '=' and the conditional '=='! +* Subtraction example: + ```csharp + int a = 3; -'=' is used for assigning values for variables, '== is used for comparing values + a = a - 1; // a is now 2 + a -= 1; // a is now 1 + a--; // a is now 0 + ``` -| Operator | Example | Same As | -| :-: | :-: | :-: | -| = | x = 5 | x = 5 | -| += | x += 5 | x = x + 5 | -| -= | x -= 5 | x = x - 5 | -| *= | x *= 5 | x = x * 5 | -| /= | x /= 5 | x = x / 5 | -| %= | x %= 5 | x = x % 5 | ---- +
+
-Tässä on joitakin asetusoperaattoreita, lisäksi loogiset (ei käydä tässä) +* `++` and `--` are called the ***increment and decrement operators*** -# Operators - Example -int uppercaseLetters = 2; +### Extra: Increment/decrement operation precedence + -uppercaseLetters += 4; // is now 6 +* Note that incrementing can be written as ***prefix*** (`++i`) or a ***postfix*** (`i++`) +* In this example, `a++` and `++a` do exactly the same: + ```csharp + int a = 3; + a++; // a is now 4 + ++a; // a is now 5 + ``` +* Their exact difference is [complicated](https://stackoverflow.com/questions/3346450/what-is-the-difference-between-i-and-i-in-c), and in some cases, using either prefix or postfix form can produce different results: -int specialCharacters = 2; +
+
-specialCharacters *= 2; // is now 4 +```csharp +int a = 3; +int b = ++a; +Console.WriteLine(b); // 4 +``` +Assignment of `b` happens after `++`, +so its value is 4 -Console.WriteLine(uppercaseLetters); +
+
-Console.WriteLine(specialCharacters); +```csharp +int a = 3; +int b = a++; +Console.WriteLine(b); // 3 +``` +Assignment of `b` happens before `++`, +so its value is 3 + +
+
-This outputs 6 and 4 -# Strings +## Strings String is a special type, which contains an array of characters. You can declare and assign strings like any other type of variables: @@ -252,7 +344,7 @@ string fullName = firstName + " " + lastName; Console.WriteLine(fullName); // Outputs "Johannes Kantola" -# Character Constants +## Character Constants Character constants are preceded by a backslash '\\' and can be used for formatting strings @@ -276,7 +368,7 @@ Kantola All character constants: [https://www.tutorialspoint.com/csharp/csharp\_constants.htm](https://www.tutorialspoint.com/csharp/csharp_constants.htm) -# String Interpolation +## String Interpolation Concatenating multiple variables into one string with the '+' operator quickly becomes tedious @@ -290,7 +382,7 @@ Console.WriteLine($"{animal} says {sound}!"); // Outputs "Dog says Woof!" -# String Formatting +## String Formatting You can add __format strings__ to change the way variables are interpolated into a string @@ -304,7 +396,7 @@ Console.WriteLine($"Pi to three digits: {pi:G3}"); // Outputs "Pi to three digits: 3.14" -# Console.ReadLine() +## Console.ReadLine() For the next exercise, you'll need the Console.ReadLine() method. The method pauses the program, waits for an input stream from the console that pops up, and returns the value of the input: @@ -312,13 +404,16 @@ string userInput = Console.ReadLine();Console.WriteLine(userInput); ![](imgs/2%20Variables%20and%20Types_1.png) -# Exercise 2: weekday survey + +## Exercise 2: Weekday survey + Create a console application which asks the user which weekday it is and assigns the answer to a string variable. Print "Have a nice weekday!" to the console where weekday is replaced with the string the user wrote. -# Assignments (arithmetic operations) +## Assignments (arithmetic operations) + [Assignments about this topic can be found here](https://gitea.buutti.com/education/academy-assignments/src/branch/master/C%23%20Basics/2.3.%20Arithmetic%20Operations)