You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
12 KiB
12 KiB
marp | paginate | math | theme | title |
---|---|---|---|---|
true | true | mathjax | buutti | 2. Variables and Types |
Variables and Types
Overview
- Variables
- Comments
- 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# consoleConsole.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.
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 a) explain your code b) comment out actual code for testing and debugging
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
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 |
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 adecimal
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
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 |
Exercise 1: Trying Out Variables
- Create a new console application 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.
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
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 |
- 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 that contains an array of characters.string name = "Sini Aalto";
- You can concatenate (i.e., combine) multiple strings with the
+
operator:string firstName = "Sini"; string lastName = "Aalto"; string fullName = firstName + " " + lastName; Console.WriteLine(fullName); // Outputs "Sini Aalto"
Character Constants
- Character constants are preceded by a backslash
\
and can be used for formatting strings \n
represents a newlinestring firstName = "Johannes"; string lastName = "Kantola"; string fullName = firstName + "\n" + lastName; Console.WriteLine(fullName); /* This outputs Johannes Kantola */
- All character constants are listed here
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"
User input with 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 that 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.