C++ fundamentals · Lesson 2 of 21
Variables and types
int, double, char, bool, string, auto and const, and why types matter.
In C++ you state each variable's type when you declare it, and it never changes. That's static typing: the compiler knows everything before the program runs, catches many mistakes early, and reserves exactly the right amount of memory.
#include <iostream>
#include <string>
int main() {
int age = 20;
double gpa = 3.75;
char grade = 'A';
bool enrolled = true;
std::string name = "Laila";
const int maxCourses = 5;
auto score = 98.5; // the compiler works out: double
std::cout << name << " is " << age << ", grade " << grade << "\n";
std::cout << "GPA " << gpa << ", enrolled: " << enrolled << "\n";
std::cout << "max " << maxCourses << ", score " << score << "\n";
return 0;
}Each type takes a known amount of space. (These are the usual sizes; the standard only sets minimums.)
Notice bool printed 1, not true. A char uses single quotes 'A', a string double quotes "Laila". const means the value never changes; try to change it and the compiler refuses.
The division and overflow traps
#include <iostream>
#include <climits>
int main() {
std::cout << 7 / 2 << "\n"; // int / int -> int
std::cout << 7 / 2.0 << "\n"; // one double -> double
int big = INT_MAX;
std::cout << big << "\n";
long long bigger = static_cast<long long>(big) + 1;
std::cout << bigger << "\n";
return 0;
}What's the output?
#include <iostream>
int main() {
int a = 9, b = 4;
double c = a / b;
std::cout << c << "\n";
}What will this code print?
Complete the code
Complete it so the division gives 2.25.
#include <iostream> int main() { int a = 9, b = 4; double c = <double>(a) / b; std::cout << c << "\n"; }
Exercise
You have int total = 17 and int count = 4. Print the average with its fraction (4.25).
Expected output: 4.25
#include <iostream>
int main() {
int total = 17;
int count = 4;
std::cout << total / count << "\n";
return 0;
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.