9.0 KiB
Variables & Types
Overview
Variables
Data Types
Arithmetic Operators
Increment & Decrement
Assignment Operators
Strings
Character Constants
String Interpolation
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
- 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;
using System;
namespace MyAwesomeProgram
{
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
This program prints the value "15" to the console
Why we use variables?
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?
- 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#
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 |
More types listed here:
https://www.w3schools.com/cs/cs_data_types.asp
Data Types in C# - Example
double airPressure = 1.2; // Use generally for everything
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)
bool loggedIn = false;
char previousInput = 'b';
Assignments (variables)
Assignments about this topic can be found here
Assignments (data types)
Assignments about this topic can be found here
What are arithmetic operations?
The arithmetic operations are common mathematical operations:
addition
subtraction
multiplication
division
modulus (remainder, in Finnish jakojäännös)
exponentiation
Earlier we used an _arithmetic operator _ to subtract b from a:
Console.WriteLine(a - b);
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 |
Tässä on kaikki aritmeettiset operaattorit
Exercise 1: Trying Out Variables
Create a new console application as we did in the last exercise and declare two variables of type double .
Assign different values for those variables.
Print the sum , difference , __fraction __ and __product __ of those values to the console.
Increment & Decrement
Increment and decrement operations are operations that can be used to increment or decrement a variable value by 1.
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
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
This will do the same thing as a++ and a--. There is a small difference between these syntaxes though.
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 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.
Täällä voi helposti demota: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment
Assignment Operators
We have used the assignment operator ' =' for assigning values for variables:
int x;
x = 25;
__Notice __ the difference between '=' and the conditional '=='!
'=' is used for assigning values for variables, '== is used for comparing values
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ä)
Operators - Example
int uppercaseLetters = 2;
uppercaseLetters += 4; // is now 6
int specialCharacters = 2;
specialCharacters *= 2; // is now 4
Console.WriteLine(uppercaseLetters);
Console.WriteLine(specialCharacters);
This outputs 6 and 4
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.