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:

  1. four Boolean values (a Boolean can be true or false): false, true, true, false.

  2. an integer: 6

  3. 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.

  4. a decimal number: 1.2 if we set the decimal dot in the middle

  5. as a letter; 0110 binary corresponds to 6 in decimal, so sixth letter: F

  6. as 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:

  1. an array of bools

  2. int until ~2 billion, long much larger

  3. double (more precise version of float)

  4. decimal (compared to float and double can represent monetary values exactly)

  5. char

  6. string

Tip

Use decimal for financial and monetary numbers and double for all other decimal numbers.

Question to ponder

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

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

Console.WriteLine("Hej Geko 👋");

"Hej Geko 👋": string

none

Console.ReadLine();

none

read line: string

Convert.ToString(4.2);

4.2: double

"4.2": string

double.TryParse("45.67", parsedDouble)

"45.67": string

parsedDouble: variable which the parsed number written to

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#

// Implicit conversion (safe, no data loss)
// Small numeric types → larger numeric types
int wholeNumber = 42;
double bigNumber   = wholeNumber;   // implicit
Console.WriteLine(bigNumber);

// Explicit conversion (cast) – may lose data
double piDouble = 3.14159;
int   piInt    = (int)piDouble;   // truncates to 3 (we lost data)
Console.WriteLine(piInt);

// Without explicit conversion - WHAT HAPPENS? ⬅️
// piInt    = piDouble;
// Console.WriteLine(piInt);

// TryParse – converts from string to other datatypes – preferred for user input
string   txt = "45.67";
//txt = "45..67";  // TRY THIS
if (double.TryParse(txt, out var parsedDouble))  // Note: We declare `parsedDouble` inside the function instead for readability.
    Console.WriteLine(parsedDouble); // parsedDouble == 45.67
else
    Console.WriteLine("Not recognized as a double");

// ToString() – any value → string
int   age = 30;
string ageText = age.ToString();   // "30"

// WriteLine can usually print without any conversion
Console.WriteLine(age);
Console.WriteLine(ageText);
Question to ponder

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

double x = 5.0;
double y = 2.0;
double div = x / y;         // 2.5

// Exponentiation and root
double power = Math.Pow(3, 4);   // 3⁴ = 81
double sqrt  = Math.Sqrt(16);    // 4

// Trigonometric functions (angles in radians)
double angle = Math.PI / 4;      // 45°
double sin   = Math.Sin(angle);  // 0.7071...
double cos   = Math.Cos(angle);  // 0.7071...

// Rounding
double raw   = 3.14159;
double round = Math.Round(raw, 2); // 3.14
Question to ponder

Come up with an example where any of the math expressions be useful in your project?

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 double 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.

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;  // double
var score = age + altitude; // double
var name = "Su";

var numberOfUsers;  // ❌ datatype is not clear

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: ");
double.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:

Appendix#