Lesson 4 of 22
Lesson Progress: 0%
A constant in C++ is a variable whose value cannot be changed after it is set. You create a constant by adding the keyword const before the type when you declare the variable. Constants are useful for values that should stay the same throughout your program, like the number of days in a week or the value of pi. Using constants makes your code easier to read and prevents accidental changes to important values. This lesson will show you how to create and use constants in C++.
#include <iostream>
using namespace std;
int main() {
const int DAYS = 7;
cout << DAYS;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
const int DAYS = 7; creates a constant integer with the value 7.const tells C++ that this value must never change.7.#include <iostream>
using namespace std;
int main() {
const double PI = 3.14;
cout << PI;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
const double PI = 3.14; creates a constant decimal value.double.3.14.#include <iostream>
using namespace std;
int main() {
const string GREETING = "Hello";
cout << GREETING;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
const string GREETING = "Hello"; creates a constant string.Hello.#include <iostream>
using namespace std;
int main() {
const int HOURS = 24;
cout << HOURS * 7;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
const int HOURS = 24; stores the number of hours in a day.cout << HOURS * 7; multiplies to find hours in a week.168.#include <iostream>
using namespace std;
int main() {
const int SCORE = 100;
cout << SCORE;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
const int SCORE = 100; sets a value that stays the same.100.#include <iostream>
using namespace std;
int main() {
const int ROWS = 3;
const int COLS = 4;
cout << ROWS * COLS;
return 0;
}Instructions
▼ ← Click the triangle to hide or reveal instructions.Task Incomplete
Editor Input:
Editor Output:
const int ROWS = 3; and const int COLS = 4; are two constants.ROWS * COLS calculates their product to give 12.Test Incomplete