This is the second Tutorial in C++, in this C++ Tutorial we are going to Create Variables & Data Types. so Variables are used to store data in memory location, which we will use from that variable in our program. for example when I write int number=5;
here variable name is number which is associated with value 5, int is a data type that represents that this variable can hold integer values. there are different data types in c++ that you can use.
Also you can check more article on c++ programming language
1: C++ Introduction & Program Structure
C++ Data Types
int: this data type holds integer value.
char: holds character value like ‘a’, ‘b’, ‘C’, ‘d’ etc.
bool: holds boolean value true or false.
double: double-precision floating point value.
float: Single-precision floating point value.
So now let’s create an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include<iostream> using namespace std; int main() { int Num = 10; float a = 10.5; char b = 'b'; cout << Num << endl; cout << b << endl; cout << a << endl; return 0; } |
So now you can see in the above code we have created different types of variables, we have created int, float and also char data types variables. if you run the code, you will see this result in the screen.
Let’s create another simple example, so in this example we are going to add two numbers together.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include<iostream> using namespace std; int main() { // adding numbers int a = 9; int b = 6; int sum = a + b; cout << sum << endl; return 0; } |
OK you can see in the code that we have two integer numbers, and after that we have a variable that we want to store the sum of these two numbers, after runing this will be the result.
From the view point of scope, we have two types of variable , Local Variable and Global Variable.
Global Variable
If you declare a variable outside the function, it is called global variable. global variables can be accessed anywhere in the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include<iostream> using namespace std; int num = 10; int main() { cout << "My global variable " << num << endl; return 0; } |
If you run the code you will see the result.
1 2 |
<span class="pun">My global variable:</span><span class="pln"> 10 </span> |
Local Variable
If you declare a variable inside the function, it is called local variable. local variables can be accessed in side the function or scope.
Also you can watch the complete video for this article
Subscribe and Get Free Video Courses & Articles in your Email