Practical Variable Examples
Real-World Variable Usage
Variables become powerful when they represent real-world data and calculations. The following examples demonstrate how different variable types can be combined in practical programs.
Student Record System
A simple program that uses multiple variable types to represent student information:
Example
#include <iostream>
#include <string>
int main() {
// Student information
int studentId = 1001;
std::string firstName = "John";
std::string lastName = "Doe";
char grade = 'A';
double gpa = 3.8;
bool isGraduating = true;
// Display information
std::cout << "Student ID: " << studentId << '\n';
std::cout << "Name: " << firstName << ' ' << lastName << '\n';
std::cout << "Grade: " << grade << '\n';
std::cout << "GPA: " << gpa << '\n';
std::cout << "Graduating: " << (isGraduating ? "Yes" : "No") << '\n';
return 0;
}
Output
Student ID: 1001 Name: John Doe Grade: A GPA: 3.8 Graduating: Yes
Geometry Calculator
Calculating the area and circumference of a circle with constants and mathematical functions:
Example
#include <iostream>
#include <cmath>
int main() {
constexpr double PI = 3.14159; // constant for readability
double radius = 5.0;
double area = PI * std::pow(radius, 2);
double circumference = 2 * PI * radius;
std::cout << "Circle with radius " << radius << '\n';
std::cout << "Area: " << area << '\n';
std::cout << "Circumference: " << circumference << '\n';
return 0;
}
Output
Circle with radius 5 Area: 78.5397 Circumference: 31.4159
Temperature Converter
Converting Celsius to Fahrenheit using constants for clarity:
Example
#include <iostream>
int main() {
const double FAHRENHEIT_RATIO = 9.0 / 5.0;
const int FAHRENHEIT_OFFSET = 32;
double celsius = 25.0;
double fahrenheit = (celsius * FAHRENHEIT_RATIO) + FAHRENHEIT_OFFSET;
std::cout << celsius << "°C is " << fahrenheit << "°F" << '\n';
return 0;
}
Output
25°C is 77°F
ℹ️ Note: Using named constants makes formulas easier to read and maintain.