C++ fundamentals · Lesson 3 of 21
Operators and input
%, ++, compound operators, cin, and operator precedence.
8 minutes3 games
The arithmetic operators + - * / work as in maths, plus %, which gives the remainder: 17 % 5 is 2. It's very handy: check even or odd (n % 2 == 0), or take the last digit (n % 10).
C++
#include <iostream>
int main() {
int xp = 10;
xp += 5; // xp = xp + 5
xp *= 2; // xp = xp * 2
xp++; // xp = xp + 1
std::cout << "xp = " << xp << "\n";
int minutes = 135;
std::cout << minutes / 60 << "h " << minutes % 60 << "m\n";
std::cout << (1234 % 10) << " is the last digit\n";
return 0;
}Step by step1 / 4
- ▶int xp = 10;
- 2xp += 5;
- 3xp *= 2;
- 4xp++;
Variables
| xp | 10 |
Output
…
Input with cin
C++
#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Name and age? ";
std::cin >> name >> age; // reads two values separated by spaces
std::cout << "Hi " << name << ", next year you'll be " << age + 1 << "\n";
}The runner here can't take typed input, so try this one on your machine. std::getline(std::cin, line) reads a whole line, spaces included.
What's the output?
#include <iostream>
int main() {
int a = 5;
int b = a++;
int c = ++a;
std::cout << a << " " << b << " " << c << "\n";
}What will this code print?
Quick question
What is 2 + 3 * 4 % 5?
Exercise
You have int seconds = 3725. Print it as 1h 2m 5s.
Expected output: 1h 2m 5s
C++
#include <iostream>
int main() {
int seconds = 3725;
return 0;
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.