CodeBlanks Logo Icon CodeBlanks

Summary - Variables

Declare typed variables to write a small profile program.

Summary - Variables

In this section you learned the basics of variables:

  • declaring variables with int, double, char, bool, float
  • auto for compiler type deduction
  • const for immutable variables
  • constexpr for compile-time constants
  • static_cast for safe type conversion

Now you will reinforce these concepts with two mini tasks.

Practice Print three types on one line

Inside main, declare an int (value 5), a double (value 1.5) and a char (value 'X'). Chain all three in a single std::cout line and end with std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare an int, a double and a char
    // Print all three on one line with std::cout
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    // Declare an int, a double and a char
    int count = 5;
    double rate = 1.5;
    char label = 'X';
    // Print all three on one line with std::cout
    std::cout << count << rate << label << std::endl;
    return 0;
}

Expected output

51.5X

Practice Constant and conversion together

Inside main, declare const double pi = 3.14159;. Use static_cast<int> to convert pi to int and assign it to a variable named rounded. Then print rounded with std::cout using std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Define const double pi
    // Convert pi to int with static_cast and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    // Define const double pi
    const double pi = 3.14159;
    // Convert pi to int with static_cast and print
    int rounded = static_cast<int>(pi);
    std::cout << rounded << std::endl;
    return 0;
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Immutable variable

Question
____ int maxLevel = 50;
Answer
const int maxLevel = 50;

Explanation: const int maxLevel is immutable.

2 Match the section concepts

Term Meaning
auto Type deduction
const Immutable
constexpr Compile time
static_cast Type conversion

All lessons in Beginner