Fundamentals of C++
Learn commonly used data types and operators in C++.
Data types in C++
Every variable in C++ needs to be declared with the help of a data type. For example, whether a variable can store only numbers or can also store other symbols as its value.
Common data types
The following are the commonly used data types in C++:
-
int: Integer values (5,0,-1, etc.) -
double: Floating-point values (2.33333,-2500.001,20.0, etc.) -
bool: Boolean values (true/1,false/0) -
char: Character value (a,0,$, etc) -
string: String values (educative,c++,k2, etc.)
The bool data type is used to store true or false, but whenever we display the Boolean values, true is displayed as 1 and false as 0. In order to use the string data type, we have to add #include <string> at the start of the code.
Variable declaration
The C++ language requires the programmer to tell the data type of the variables used in a program. The following code demonstrates the declaration of variables to input their values with a suitable prompt and to display them with suitable labels:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str; // Declaring a variable of type string
int number; // Declaring a variable of type integer
double real; // Declaring a variable of type double
bool isTrue; // Declaring a variable of type bool
char letter; // Declaring a variable of type char
cout << "Please input a word: ";
cin >> str;
cout << "Please input an integer: ";
cin >> number;
cout << "Please input a real number: ";
cin >> real;
cout << "Please input 0 or 1 [0 for false, 1 for true]: ";
cin >> isTrue;
cout << "Please input a letter: ";
cin >> letter;
cout << "The value of each variable is enclosed in brackets:" << std::endl;
cout << "str (" << str << ")" << endl;
cout << "number (" << number << ")" << endl;
cout << "real number (" << real << ")" << endl;
cout << "isTrue (" << isTrue << ")" << endl;
cout << "letter (" << letter << ")" << endl;
return 0;
}
Note: We don’t use
<and>withstringother than#includebecause it’s a data type. Thestringat line 2 is the name of the file that defines thestringdata type.
Explanation
- Line 7–11: We declare the variables so they can be used to store the values input by the user. There are different types of variables that are declared:
stris a variable of thestringtype.numberis a variable of theinttype.fractionis a variable of thedoubletype.isTrueis a variable of thebooltype.letteris a variable of thechartype.
- Line 13–22: We output a prompt using
coutand demand input from the user usingcinand then store them in the relevant variable. - Line 24–28: We output the variable name