Seconds into hours
Read a number of seconds n (0 ≤ n < 86400) and print the time in the form h:mm:ss – the minutes and seconds always with two digits.
Example 1
Input
3725Output
1:02:05Example 2
Input
86399Output
23:59:59Every piece of data in a program is stored in a variable of a certain type. The type determines which values the variable can hold and which operations are allowed. This lesson covers the basic C# types, operators, keyboard input (Console.ReadLine), converting text into a number and nicely formatted output.
A variable must be declared before it is used: you write the type and then the name. The value is set with the assignment operator =, either immediately or later.
using System;
class Program
{
static void Main()
{
int numberOfStudents; // declaration
numberOfStudents = 28; // assigning a value
double average = 4.37; // declaration with an initial value
char grade = 'A'; // a single character – single quotes
bool passed = true; // a logical value: true or false
string name = "Maria"; // text – double quotes
Console.WriteLine(name + " has an average of " + average);
Console.WriteLine($"There are {numberOfStudents} students in the class.");
Console.WriteLine($"Grade: {grade}, passed: {passed}");
}
}
Text that starts with the $ sign is an interpolated string: an expression in curly brackets {…} is replaced with its value. This is a clearer way than joining the parts with the + operator. Notice that a logical value is printed as True, with a capital first letter.
A variable name starts with a letter or the _ sign; by convention local variables are written in camelCase (numberOfStudents), and methods and classes in PascalCase (WriteLine, Program). Upper-case and lower-case letters are different.
using System;
class Program
{
static void Main()
{
var counter = 10; // the compiler works out the type itself: int
var message = "Hello"; // string
const double PI = 3.14159; // a constant – its value cannot be changed
double r = 2;
Console.WriteLine($"{message}! counter = {counter}");
Console.WriteLine($"Circumference of the circle: {2 * r * PI}");
// PI = 3; // error: a constant cannot be given a new value
}
}
The keyword var does not mean "any type": the type is determined from the initial value and does not change afterwards. That is why var must always have an initial value.
| Type | Size | Values | Example |
|---|---|---|---|
int | 4 bytes | about ±2.1 billion | int n = 150000; |
long | 8 bytes | about ±9.2 · 1018 | long l = 8000000000; |
double | 8 bytes | real numbers, about 15 significant digits | double d = 3.14; |
decimal | 16 bytes | exact decimal numbers (money) | decimal c = 99.90m; |
char | 2 bytes | a single character (Unicode) | char z = 'Ž'; |
bool | 1 byte | true or false | bool ok = false; |
string | – | text of any length | string s = "C#"; |
For whole numbers int is used most often, and when the values can go above 2 billion – long. For real numbers you use double, and for amounts of money decimal (the number ends with the letter m), because it stores decimal values exactly.
using System;
class Program
{
static void Main()
{
Console.WriteLine($"int: {int.MinValue} .. {int.MaxValue}");
Console.WriteLine($"long: {long.MinValue} .. {long.MaxValue}");
int x = int.MaxValue;
x = x + 1; // overflow: the result "wraps around" to the smallest int
Console.WriteLine($"int.MaxValue + 1 = {x}");
Console.WriteLine(0.1 + 0.2 == 0.3); // double is not exact
Console.WriteLine(0.1m + 0.2m == 0.3m); // decimal is
}
}
long.The arithmetic operators are + - * / %. When both operands are whole numbers, / is integer division (the decimals are dropped), and % gives the remainder.
using System;
class Program
{
static void Main()
{
int a = 17, b = 5;
Console.WriteLine($"{a} + {b} = {a + b}");
Console.WriteLine($"{a} - {b} = {a - b}");
Console.WriteLine($"{a} * {b} = {a * b}");
Console.WriteLine($"{a} / {b} = {a / b}"); // integer division
Console.WriteLine($"{a} % {b} = {a % b}"); // remainder of the division
Console.WriteLine($"{a} / {b} = {(double)a / b}"); // real division
int n = 10;
n += 5; // the same as n = n + 5
n++; // increase by 1
Console.WriteLine($"n = {n}");
bool condition = a > b && b != 0; // relational and logical operators
Console.WriteLine($"a > b and b != 0: {condition}");
Console.WriteLine($"Square root of 2: {Math.Sqrt(2):F4}");
Console.WriteLine($"2 to the power of 10: {Math.Pow(2, 10)}");
}
}
| Kind | Operators | Example |
|---|---|---|
| relational | == != < <= > >= | x >= 18 |
| logical | && (and), || (or), ! (not) | x > 0 && x < 10 |
| assignment | = += -= *= /= %= | sum += x |
| increment and decrement | ++ -- | i++ |
The Math class contains mathematical functions: Math.Sqrt, Math.Pow, Math.Abs, Math.Max, Math.Min, Math.Round and the constant Math.PI.
Console.ReadLine() reads a whole line of text and returns it as a string. To get a number, we convert the text with the method int.Parse (or double.Parse, long.Parse…).
using System;
class Program
{
static void Main()
{
Console.Write("Enter your name: "); // Write does not move to a new line
string name = Console.ReadLine();
Console.Write("Enter your year of birth: ");
int year = int.Parse(Console.ReadLine()); // text -> whole number
int age = 2026 - year;
Console.WriteLine($"{name}, this year you turn {age}.");
}
}
When there are several numbers on the same line, the line is split into parts with the method Split, and each part is converted into a number:
using System;
class Program
{
static void Main()
{
// input: 12 30
string[] parts = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);
int a = int.Parse(parts[0]);
int b = int.Parse(parts[1]);
Console.WriteLine($"Sum: {a + b}");
Console.WriteLine($"Product: {a * b}");
}
}
If the user enters something that is not a number, int.Parse stops the program with an error. int.TryParse is safer: it returns true if the conversion succeeded and writes the number into the variable after the word out.
using System;
class Program
{
static void Main()
{
Console.Write("Enter a whole number: ");
string input = Console.ReadLine();
if (int.TryParse(input, out int number)) // success -> number has a value
Console.WriteLine($"Doubled: {2 * number}");
else
Console.WriteLine($"\"{input}\" is not a whole number.");
}
}
The if statement is explained in detail in the next lesson.
From a "smaller" to a "larger" type (for example int to long or double) the value is converted automatically. In the opposite direction you write an explicit conversion – the type in brackets – and part of the value can be lost.
using System;
class Program
{
static void Main()
{
double price = 1499.75;
int whole = (int)price; // the decimals are dropped
long big = whole; // int -> long happens automatically
int fromString = int.Parse("250");
string asString = 42.ToString();
Console.WriteLine(whole);
Console.WriteLine(big * 1000000);
Console.WriteLine($"{Math.Round(2.5)} {Math.Round(3.5)}"); // rounding to an even number
Console.WriteLine(fromString + 1); // adding numbers
Console.WriteLine(asString + 1); // joining text
Console.WriteLine($"{price:F1} dinars"); // one decimal place
Console.WriteLine($"[{whole,8}]"); // width 8, aligned right
Console.WriteLine($"[{"C#",-6}]"); // width 6, aligned left
}
}
Math.Round rounds a value exactly in the middle towards the even number (2.5 → 2, and 3.5 → 4). For the rounding you learned at school, use Math.Round(x, MidpointRounding.AwayFromZero).
1499,8 instead of 1499.8, and double.Parse expects a comma. The outputs in these lessons are shown with a point.Console.OutputEncoding = System.Text.Encoding.UTF8; at the beginning of the Main method.Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
Read a number of seconds n (0 ≤ n < 86400) and print the time in the form h:mm:ss – the minutes and seconds always with two digits.
37251:02:058639923:59:59Read a three-digit number and print the sum of its digits and the number written with its digits in reverse order.
472Sum of digits: 13
Reversed: 274105Sum of digits: 6
Reversed: 501"A" is a string), and a character in single quotes ('A' is a char).7 / 2 is 3, while 7.0 / 2 or (double)7 / 2 is 3.5.Console.ReadLine() always returns text – convert it into a number before calculating.decimal for money, not double.1. What is 17 / 5 if both numbers are of type int?
2. Which type is best for storing the price of a product?
3. What does Console.ReadLine() return?
4. What does int.TryParse do when the text is not a number?