Data input and datatypes#
Data input on the console#
Console.ReadLine()
We read instead of write as we did in Console.WriteLine().
Try the following:
Console.WriteLine("Enter your message and then press Enter:");
var line = Console.ReadLine();
Console.WriteLine($"Your message has {line.Length} characters.");
Data types#
A computer works with zeroes and ones. These can be interpreted in different ways:
For example, 0110:
four Boolean values (a Boolean can be true or false): false, true, true, false.
an integer: 6
a floating point number: \(1 \cdot 2^{-2} = 0.25\) (its decimal dot can float to the right). In this example the dot is shifted two times to the right.
a decimal number: 1.2 if we set the decimal dot in the middle
as a letter;
0110binary corresponds to 6 in decimal, so sixth letter: Fas two letters; second (
01) and third (10) letters in sequence: BC
Note that C# does not have a built-in type for four bits, so these are just example interpretations.
Some C# types that are similar to the interpretations above:
an array of
boolsdecimal(more precise version offloat)decimal(compared tofloatanddecimalcan represent monetary values exactly)charstring
Tip
Use decimal for financial and monetary numbers and decimal for all other decimal numbers.
Select datatypes for the following variables:
human height in meters
number of people in a city
door is open or not
price of a product in EUR
capacity of a modern hard disk in bytes
gender: divers, female, male
Using var#
Instead of writing the datatype explicitly, we can simply write var for convenience — but only if it is obvious from the context, which datatype the variable has:
var age = 0; // int
var altitude = 0.0; // decimal
var score = age + altitude; // decimal
var name = "Su";
var numberOfUsers; // ❌ datatype is not clear
Note
Rider will convert statements such as following automatically
int i = 0;
to:
var i = 0;
Arguments and return value in functions#
These act like input and output to a function.
flowchart LR
x[argument/s]:::dashed <--> B[function]
B -- return value --> y:::hidden
classDef hidden display: none;
classDef dashed stroke-dasharray:5;
Functions can have zero, one or many arguments and one return value. Usually arguments are used as input and the return value as output, but it is also possible to input addresses instead of values. If we input addresses, then a function can use them to output values.
Examples:
function |
argument/s |
return value |
|---|---|---|
|
|
none |
|
none |
read line: string |
|
|
|
|
|
true if parsing was possible; else false. |
If we use a function in a wrong way, we get an error:
Console.ReadLine(4);
Output:
Program.cs(1, 9): [CS1501] No overload for method 'ReadLine' takes 1 arguments
Fortunately, our IDE helps us with obvious errors:

Conversion between datatypes#
When we get keyboard input, this is usually a string. To do arithmetic, we need to convert strings to numerical datatypes.
When we want to output data to the user, we need to convert numerical datatypes to strings again.
// Implicit conversion (safe, no data loss)
// Less precise numeric types → more precise numeric types
// e.g., from integer to decimal
var wholeNumber = 42;
decimal bigNumber = wholeNumber; // implicit
Console.WriteLine(bigNumber);
// Does not work with incompatible types, e.g.,
// string s = "23";
// decimal number = s;
// Explicit conversion (cast) – may lose data
var pi = 3.14159;
var piInt = (int)pi; // truncates to 3 (we lost data)
Console.WriteLine(piInt);
// Does not work similar to implicit conversion:
// decimal number = (double) s
// Without explicit conversion - WHAT HAPPENS? ⬅️
// piInt = piDecimal;
// Console.WriteLine(piInt);
// If implicit and explicit conversion do not work:
// Explicit conversion method `Convert.*`:
var deciString = "45.67";
var decimalNumber = Convert.ToDecimal(deciString);
Console.WriteLine(deciString);
// TryParse – converts from string to other datatypes – preferred for user input
//decString = "45..67"; // TRY THIS
if (decimal.TryParse(deciString,
out var parsedDeci)) // Note: We declare `parsedDeci` inside the function instead for readability.
Console.WriteLine(parsedDeci); // parsedDeci == 45.67
else
Console.WriteLine("Not recognized as a decimal");
// ToString() – any value → string
var age = 30;
var ageText = age.ToString(); // "30"
// WriteLine can usually print without any conversion,
// because it calls `ToString()` in the background
Console.WriteLine(age);
Console.WriteLine(ageText);
Why do we use strings and numeric datatypes? Can’t we just use only strings or numeric datatypes?
Math expressions#
int a = 5;
int b = 2;
int sum = a + b; // 7
int diff = a - b; // 3
int product = a * b; // 10
int quotient = a / b; // 2
int remainder= a % b; // 1
decimal x = 5.0;
decimal y = 2.0;
decimal div = x / y; // 2.5
// Exponentiation and root
decimal power = Math.Pow(3, 4); // 3⁴ = 81
decimal sqrt = Math.Sqrt(16); // 4
// Trigonometric functions (angles in radians)
decimal angle = Math.PI / 4; // 45°
decimal sin = Math.Sin(angle); // 0.7071...
decimal cos = Math.Cos(angle); // 0.7071...
// Rounding
decimal raw = 3.14159;
decimal round = Math.Round(raw, 2); // 3.14
Operator precedence#
E.g., \(4 + 5 \cdot 2 \ne (4 + 5) \cdot 2 \), but \(4+(5 \cdot 2)\).
Precedence:
parentheses
modulo, multiplication, division
addition, subtraction
Using variables and constants#
// First define a variable
int age = 30;
// Then use it (`age`)
if (age > 30)
Console.WriteLine("Crisis?")
// Constants
// Convention: begin with a CAPITAL letter
const decimal Pi = 3.1415926535;
We don’t have to use const for functionality, but we humans make mistakes and this extra information lowers the chance of a mistake later. The compiler will warn us if we try to change the variable.
Program structure#
This time you will write a program from scratch. This is the main structure:
// 1. Libraries, e.g., `using System.Text.Json`
// We don't have to use any right now, however.
// 2. Variable declarations
const int threshold = 20;
// 3. Logic
Console.Write("Enter temperature: ");
decimal.TryParse(Console.ReadLine(), out var userInput);
if (userInput > threshold)
Console.WriteLine("No need for the heater.");
else
Console.WriteLine("Turn on the heater.");
Coming back to the problem#
Activity 9
We come back to Activity 8.
Create an empty project called ConveyorBeltCapacityCheck that solves this problem.
Put your flowchart from Activity 7, because you will upload your project to a code forge and submit it later as an assignment.
Steps:
10 min pair programming
one student presents their (half-)solution