Variables act as containers that store data in a program. They allow you to save, modify, and manipulate information while writing efficient code.
Different Types of Variables
C++ provides several data types, each designed for storing specific types of values:
int
→ Stores whole numbers without decimals (e.g.,120
,-45
)double
→ Holds floating-point numbers (e.g.,25.75
,-8.99
)char
→ Stores single characters (e.g.,'M'
,'B'
) within single quotesstring
→ Holds text (e.g.,"Harley Davidson"
,"Ducati"
) within double quotesbool
→ Holds true/false values, useful for logical decisions
Declaring and Assigning Variables
To define a variable, specify its type and give it a value:
Syntax:
C++
x
type variableName = value;
type
→ Defines what kind of data the variable holds (int
,double
, etc.)variableName
→ The name assigned to the variable=
→ Used to assign a value to the variable
Storing a Number
C++
using namespace std;
int main() {
int engineCC = 1000; // Engine capacity in cc
cout << "Engine capacity: " << engineCC << " cc";
return 0;
}
Declaring a Variable Without Assigning a Value
C++
using namespace std;
int main() {
int engineCC; // Declaring the variable
engineCC = 1000; // Assigning the value
cout << "Engine capacity: " << engineCC << " cc";
return 0;
}
Modifying a Variable
Once assigned, a variable can change its value during execution.
Example: Updating a Variable
C++
using namespace std;
int main() {
int engineCC = 1000; // Initial value
engineCC = 650; // Updated value
cout << "Updated engine capacity: " << engineCC << " cc";
return 0;
}
Other Variable Types
C++ offers multiple data types to handle different kinds of values:
C++
using namespace std;
int main() {
int speed = 220; // Whole number (integer)
double mileage = 15.75; // Decimal number (floating point)
char grade = 'A'; // Single character
string brand = "Kawasaki"; // Text (string)
bool isAvailable = true; // Boolean (true/false)
cout << "Speed: " << speed << " km/h" << endl;
cout << "Mileage: " << mileage << " km/L" << endl;
cout << "Grade: " << grade << endl;
cout << "Brand: " << brand << endl;
cout << "Availability: " << isAvailable << endl;
return 0;
}
Displaying Variables in Output
To print a variable along with text, use the cout
object with the <<
operator:
C++
using namespace std;
int main() {
int topSpeed = 180; // Declaring and initializing the variable
cout << "The motorcycle's top speed is " << topSpeed << " km/h.";
return 0;
}
Adding Variables Together
You can perform calculations using multiple variables.
Example: Addition
C++
using namespace std;
int main() {
int speed1 = 120;
int speed2 = 150;
int totalSpeed = speed1 + speed2;
cout << "Total combined speed: " << totalSpeed << " km/h";
return 0;
}
Output: 270