Skip to content
wannacode

Input and output

Problem

The program knows only one name

The program greets the customer by name:

string name = "Maria";
Console.WriteLine("Hello, " + name + "!");
Output
Hello, Maria!

It works, but it greets everyone as Maria. The name is written in the code. For every new customer you have to change the program and run it again. You want the program to ask on its own.

The idea

Reading from the keyboard

When the program reads, it stops and waits. The person types and presses Enter. What they type is the program's input.

Program.cs
class Program
{
static void Main()
{
Console.Write("What is your name? ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
}
}
Input
Maria
Output
What is your name? Hello, Maria!

Console.ReadLine() reads one line, up to Enter.

The input and the output are shown separately here. In the console the name appears where you type it: after "What is your name? ". That is why the question uses Write: so the answer is on the same line.

More precisely, if you are curious
  • In a project from dotnet new console, the line string name = Console.ReadLine(); gives warning CS8600. The reason is that ReadLine returns null (nothing) if the input has ended. It is a warning, not an error, and the program runs. You will see how to work with null later.
  • Console.Read() reads only one character and returns its code as a number. In this course we always read whole lines.

Problem

12 + 30 = 1230

The cashier enters two payments, €12 and €30. The program has to show the total:

string first = Console.ReadLine();
string second = Console.ReadLine();
string total = first + second;
Console.WriteLine("Total: €" + total);
Input
12
30
Output
Total: €1230

Instead of 42 you got 1230. The program did not get the math wrong. It did no math at all.

The idea

From text to a number

Whatever the person types, Console.ReadLine() returns text. "12" and "30" are two texts, and + between texts glues them together. To do math, turn the text into a number:

int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
int total = first + second;
Console.WriteLine("Total: €" + total);
Input
12
30
Output
Total: €42

Turning text into a value of another type is called parsing.

  • int.Parse(...) gives an int.
  • double.Parse(...) gives a double.
  • The other types have the same: long.Parse, bool.Parse and so on.

The sum here is the first calculation in the course. Subtraction, multiplication and division come in the next lesson.

int first = int.Parse(Console.ReadLine());
int second = int.Parse(Console.ReadLine());
int total = first + second;
Console.WriteLine("Total: €" + total);
Step by step, in words
  1. The person types 12 and Enter. Console.ReadLine() returns the text "12", not a number.
  2. int.Parse turns the text into the number 12. It goes into first.
  3. 30 takes the same path: text, parsing, a number in second.
  4. Now + adds numbers: 12 + 30 = 42.
  5. It prints "Total: €42".
More precisely, if you are curious
  • If the text is not a number (for example "twelve"), the program stops with an error: FormatException. You will see how to catch such an error in the "Errors and exceptions" module.
  • int.TryParse checks without stopping the program. You use it with if and out, which come later.
  • The decimal separator depends on the computer's regional settings. On a computer with Bulgarian settings, double.Parse("3.5") stops with an error and wants a comma: 3,5. The examples in this course use a point.

Try it

How many tickets?

The program reads how many adults and how many children there are.

Input
2
3

What will the program print?

int adults = int.Parse(Console.ReadLine());
int children = int.Parse(Console.ReadLine());
Console.WriteLine("Tickets: " + adults + children);
Answer

The idea

Numbers the way you want them

In the last lesson the price 49.90 came out as 49.9. For a price you always want two digits after the decimal point. This is formatted output:

string product = "Headphones";
double price = 49.9;
int qty = 2;
Console.WriteLine($"{product}: €{price:F2}");
Console.WriteLine($"{qty} in the cart");
string label = $"Price: €{price:F2}";
Console.WriteLine(label);
Output
Headphones: €49.90
2 in the cart
Price: €49.90

$ in front of the quotes lets you write values right inside the text, in curly braces: {product}. This is called string interpolation.

After a colon you write the format: {price:F2} means a decimal number with exactly 2 digits after the point. F0 has no digits after the point, F3 has three.

The value in the variable does not change. The format only decides how it looks when it is printed.

More precisely, if you are curious
  • Thousands separators and lining up in columns:
double total = 1234.5;
Console.WriteLine($"Total: €{total:N2}");
Console.WriteLine($"{"Coffee",-10}|{2.5,8:F2}");
Console.WriteLine($"{"Laptop",-10}|{1299.0,8:F2}");
Output
Total: €1,234.50
Coffee | 2.50
Laptop | 1299.00

N2 adds a thousands separator. The number after the comma is the width: {2.5,8:F2} takes 8 characters, aligned right, and -10 aligns left.

There is also an older form with the same meaning: Console.WriteLine("{0}: €{1:F2}", product, price);. You will see it in other people's code.

  • Regional settings matter here too. On a computer with Bulgarian settings, F2 gives 49,90, and the thousands separator is a space: 1 234,50. The output in the lessons uses a point.

In C# even a plain "Price: €" + price follows the settings. On a computer with Bulgarian settings, the price from the last lesson comes out as 49,9.

Try it

Two digits

A night at the hotel costs €65.5. You want it to come out as "Per night: €65.50". What goes in the blank?

Console.WriteLine($"Per night: €{price:}");

Try it

Find the bug

The program asks how many tickets to reserve. It does not compile. Which line is the bug on?

Pick the line with the bug.

Exercise

Programs that ask

Solve the tasks in your editor. The input is one line for each value. Do not print questions like "Enter a name:", so your output matches the sample.

1. Greeting by name. Read a name and greet the person.

Input
Maria
Output
Hello, Maria!

2. Sum of two numbers. Read two whole numbers and print the calculation.

Input
17
25
Output
17 + 25 = 42

3. Two texts in one. Read two texts and print them together, with a space between them.

Input
Veliko
Tarnovo
Output
Veliko Tarnovo

4. π with two digits. Store π in a variable as 3.14159265358979 and print it with two digits after the point. The ready value Math.PI comes in the next lesson.

Output
3.14

More tasks

  • Age. Read a name and an age (a whole number) and print "Maria is 19 years old."
  • A business card from the keyboard. Read a name, a job and a phone number and print the business card from the "Your first program" lesson with them.
  • A price with two digits. Read a price as a decimal number and print it with two digits and the euro sign: for input 7.5 the output is Price: €7.50.
  • Sum of two prices. Read two decimal prices and print their sum with two digits: for input 12.4 and 3.15 the output is Total: €15.55.

Test

Check yourself

1. What does Console.ReadLine() return?
2. You read the texts "12" and "30". What does first + second give?
3. What does int.Parse("25") do?
4. int a = 2; int b = 3; What does "Sum: " + a + b print?
5. How do you print 7.5 as 7.50?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·