Variables in C++ are storage location where the data(Be it a number or a Name) is stored.It is like a container where something is stored.
Well! C++ takes the same step to add two numbers. The only difference is, you have usedone notebook to write and add the numbers.
But C++ uses different locations to store each number. And they are called as Variables.
Let us see how Variables are used in C++ for addition of two numbers.
#include <iostream> using namespace std; int main() { int x = 5; int y = 8; int z; z = x + y; cout << "The added value is : "<<z; return 0; }
Now, if you look at the above code, x, y and z are Variables.
And below are the steps involved in addition of the numbers.
int x = 5;
int y = 8;
int z;
cout << "The added value is : "<<z;
"The added value is : "
z
The added value is : 13
So far we have seen, how to store a number (i.e. int x = 5) in a Variable.
Now, let us see how to store a string(i.e. It could be a Name or a City) in a Variable.
Let us say, we want to store the string Hello World in a Variable(Say x).
And the process of storing a string is same as storing a number, but with a mild difference.
Below is the C++ Code :
#include <iostream> using namespace std; int main() { string x = "Hello World"; cout << x; return 0; }
So, in the above example, we have used String infront of the variable x to store aString type value.
string x = "Hello World";
Just like any other language, there is a rule to declare the Variables.
Although, the Variables can be of any names with some restriction.
Below are the rules :
So, if you have two numbers and need to assign them to two Variables. You can either declarethe variables as x and y.
int x = 5;
And
int y = 7;
But the preferred way to name the Variables would be firstNumber and secondNumber.
int firstNumber = 5;
And
int secondNumber = 7;
But you can never use Variable names with spaces like first number or variables with a- like first-number.