Variables in C++ are essential components used to store, manipulate, and interact with data. They act as symbolic names for memory locations where data is stored, allowing for dynamic data handling and efficient programming.
type variable_name; // Declaration
type variable_name = value; // Declaration with initialization
• Integer (int): Stores whole numbers.
• Floating-point (float, double): Stores numbers with decimal points.
• Character (char): Stores a single character.
• Boolean (bool): Stores true or false.
int age; // Declares an integer variable named 'age'
float height; // Declares a floating-point variable named 'height'
char initial; // Declares a character variable named 'initial'
int age = 25; // Declares an integer variable 'age' and initializes it to 25
float height = 5.9; // Declares a floating-point variable 'height' and initializes it to 5.9
char initial = 'A'; // Declares a character variable 'initial' and initializes it to 'A'
• Variable names can include letters (both uppercase and lowercase), digits, and underscores (_).
• Must start with a letter or an underscore, not a digit.
• Cannot use reserved keywords (e.g., int, float, if).
int count; // Valid
int _total; // Valid
int result1; // Valid
int 1stNumber; // Invalid: Starts with a digit
int total amount; // Invalid: Contains space
int double; // Invalid: Reserved keyword
• Storing Data: Variables are used to hold various types of data, such as user inputs, calculated results, and constants.
• Dynamic Operations: They allow for dynamic data manipulation through assignment, modification, and reuse.
• Data Types: Different types of variables (int, float, char) are used based on the nature of data being handled.
• Scope and Lifetime: Variables can have different scopes (local or global) and lifetimes (automatic or static).
• Object-Oriented Programming: Variables within classes (data members) help in modeling real-world entities.
#include <iostream>
using namespace std;
int main() {
// Variable declarations
int age = 18; // Integer variable
float salary = 72000.75; // Floating-point
variable
char grade = 'A'; // Character variable
// Outputting values
cout << "Age: " << age << std::endl;
cout << "Salary: $" << salary << std::endl;
cout << "Grade: " << grade << std::endl;
// Modifying values
age = 31;
salary += 2000.00;
grade = 'B';
// Outputting updated values
cout << "Updated Age: " << age << std::endl;
cout << "Updated Salary: $" << salary << std::endl;
cout << "Updated Grade: " << grade << std::endl;
return 0;
}
Age: 18
Salary: $72000.8
Grade: A
Updated Age: 31
Updated Salary: $74000.8
Updated Grade: B