Professional Documents
Culture Documents
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
void main() The main() function is the entry point of every program in C++ language. The
void keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks the
screen.
By menu
Now click on the compile menu then compile sub menu to compile the c++ program.
Then click on the run menu then run sub menu to run the c++ program.
By shortcut
You can view the user screen any time by pressing the alt+f5 keys.
If bytes flow from main memory to device like printer, display screen, or a network connection,
etc, this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to main
memory, this is called as input operation.
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard
output stream, standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such
as setprecision and setw.
Output:
Value of ary is: Welcome to C++ tutorial
Output:
Enter your age: 22
Your age is: 22
Output:
C++ Tutorial Javatpoint
End of line
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
1. int x=5,b=10; //declaring 2 variable of integer type
2. float f=30.8;
3. char c='A';
A variable name can start with alphabet and underscore only. It can't start with digit.
A variable name must not be any reserved word or keyword e.g. char, float etc.
Valid variable names:
1. int a;
2. int _ab;
3. int a30;
Let's see the basic data types. It size is given according to 32 bit OS.
float 4 byte
double 8 byte
C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of
32 Keywords in C++ Language which are also available in C language are given below.
auto break case char const continue default do
double else enum extern float for goto if
A list of 30 Keywords in C++ Language which are not available in C language are given
below.
asm dynamic_cast namespace reinterpret_cast bool
For example, suppose the given data is an integer type, and we want to convert it into float type.
So, we need to manually cast int data to the float type, and this type of casting is called the Type
Casting in C++.
1. int num = 5;
2. float x;
3. x = float(num);
4. x = 5.0
2nd example:
1. float num = 5.25;
2. int x;
3. x = int(num);
4. Output: 5
Type Casting is divided into two types: Implicit conversion or Implicit Type Casting and Explicit
Type Conversion or Explicit Type Casting.
Implicit Type Casting or Implicit Type Conversion
o It is known as the automatic type casting.
o It automatically converted from one data type to another without any external intervention
such as programmer or user. It means the compiler automatically converts one data type to
another.
o All data type is automatically upgraded to the largest type without losing any information.
o It can only apply in a program if both variables are compatible with each other.
1. char - sort int -> int -> unsigned int -> long int -> float -> double -> long double, etc.
Note: Implicit Type Casting should be done from low to higher data types. Otherwise, it affects the
fundamental data type, which may lose precision or data, and the compiler might flash a warning to this
effect.
Let's create an example to demonstrate the casting of one variable to another using the implicit
type casting in C++.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. short x = 200;
6. int y;
7. y = x;
8. cout << " Implicit Type Casting " << endl;
9. cout << " The value of x: " << x << endl;
10. cout << " The value of y: " << y << endl;
11.
12. int num = 20;
13. char ch = 'a';
14. int res = 20 + 'a';
15. cout << " Type casting char to int data type ('a' to 20): " << res << endl;
16.
17. float val = num + 'A';
18. cout << " Type casting from int data to float type: " << val << endl;
19. return 0;
20. }
Output:
Implicit Type Casting
The value of x: 200
The value of y: 200
Type casting char to int data type ('a' to 20): 117
Type casting from int data to float type: 85
In the above program, we declared a short data type variable x is 200 and an integer variable y.
After that, we assign x value to the y, and then the compiler automatically converts short data
value x to the y, which returns y is 200.
In the next expressions, we declared an int type variable num is 20, and the character type
variable ch is 'a', which is equivalent to an integer value of 97. And then, we add these two
variables to perform the implicit conversion, which returns the result of the expression is 117.
Similarly, in the third expression, we add the integer variable num is 20, and the character variable
ch is 65, and then assign the result to the float variable val. Thus the result of the expression is
automatically converted to the float type by the compiler.
type: It represents the user-defined data that converts the given expression.
expression: It represents the constant value, variable, or an expression whose data type is
converted.
For example, we have a floating pointing number is 4.534, and to convert an integer value, the
statement as:
1. int num;
2. num = (int) 4.534; // cast into int data type
3. cout << num;
When the above statements are executed, the floating-point value will be cast into an integer
data type using the cast () operator. And the float value is assigned to an integer num that
truncates the decimal portion and displays only 4 as the integer value.
Program to demonstrate the use of the explicit type casting in C++
Let's create a simple program to cast one type variable into another type using the explicit type
casting in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // declaration of the variables
6. int a, b;
7. float res;
8. a = 21;
9. b = 5;
10. cout << " Implicit Type Casting: " << endl;
11. cout << " Result: " << a / b << endl; // it loses some information
12.
13. cout << " \n Explicit Type Casting: " << endl;
14. // use cast () operator to convert int data to float
15. res = (float) 21 / 5;
16. cout << " The value of float variable (res): " << res << endl;
17.
18. return 0;
19. }
Output:
Implicit Type Casting:
Result: 4
In the above program, we take two integer variables, a and b, whose values are 21 and 2. And
then, divide a by b (21/2) that returns a 4 int type value.
In the second expression, we declare a float type variable res that stores the results of a and b
without losing any data using the cast operator in the explicit type cast method.
Program to cast double data into int and float type using the cast operator
Let's consider an example to get the area of the rectangle by casting double data into float and
int type in C++ programming.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // declaration of the variables
6. double l, b;
7. int area;
8.
9. // convert double data type to int type
10. cout << " The length of the rectangle is: " << endl;
11. cin >> l;
12. cout << " The breadth of the rectangle is: " << endl;
13. cin >> b;
14. area = (int) l * b; // cast into int type
15. cout << " The area of the rectangle is: " << area << endl;
16.
17. float res;
18. // convert double data type to float type
19. cout << " \n \n The length of the rectangle is: " << l << endl;
20. cout << " The breadth of the rectangle is: " << b << endl;
21. res = (float) l * b; // cast into float type
22. cout << " The area of the rectangle is: " << res;
23. return 0;
24. }
Output:
The length of the rectangle is:
57.3456
The breadth of the rectangle is:
12.9874
The area of the rectangle is: 740
In type cast, there is a cast operator that forces one data type to be converted into another data
type according to the program's needs. C++ has four different types of the cast operator:
1. Static_cast
2. dynamic_cast
3. const_cast
4. reinterpret_cast
Static Cast:
The static_cast is a simple compile-time cast that converts or cast one data type to another. It
means it does not check the data type at runtime whether the cast performed is valid or not. Thus
the programmer or user has the responsibility to ensure that the conversion was safe and valid.
The static_cast is capable enough that can perform all the conversions carried out by the implicit
cast. And it also performs the conversions between pointers of classes related to each other
(upcast - > from derived to base class or downcast - > from base to derived class).
Let's create a simple example to use the static cast of the type casting in C++ programming.
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5. // declare a variable
6. double l;
7. l = 2.5 * 3.5 * 4.5;
8. int tot;
9.
10. cout << " Before using the static cast:" << endl;
11. cout << " The value of l = " << l << endl;
12.
13. // use the static_cast to convert the data type
14. tot = static_cast < int > (l);
15. cout << " After using the static cast: " << endl;
16. cout << " The value of tot = " << tot << endl;
17.
18. return 0;
19. }
Output:
Before using the static cast:
The value of l = 39.375
After using the static cast:
The value of tot = 39
Dynamic Cast
The dynamic_cast is a runtime cast operator used to perform conversion of one type variable to
another only on class pointers and references. It means it checks the valid casting of the variables
at the run time, and if the casting fails, it returns a NULL value. Dynamic casting is based on RTTI
(Runtime Type Identification) mechanism.
Let's create a simple program to perform the dynamic_cast in the C++ programming language.
1. #include <iostream>
2. using namespace std;
3.
4. class parent
5. {
6. public: virtual void print()
7. {
8.
9. }
10. };
11. class derived: public parent
12. {
13.
14. };
15.
16. int main ()
17. {
18. // create an object ptr
19. parent *ptr = new derived;
20. // use the dynamic cast to convert class data
21. derived* d = dynamic_cast <derived*> (ptr);
22.
23. // check whether the dynamic cast is performed or not
24. if ( d != NULL)
25. {
26. cout << " Dynamic casting is done successfully";
27. }
28. else
29. {
30. cout << " Dynamic casting is not done successfully";
31. }
32. }
Output:
Dynamic casting is done successfully.
The reinterpret_cast type casting is used to cast a pointer to any other type of pointer whether the
given pointer belongs to each other or not. It means it does not check whether the pointer or the
data pointed to by the pointer is the same or not. And it also cast a pointer to an integer type or
vice versa.
Let's write a program to demonstrate the conversion of a pointer using the reinterpret in C++
language.
1. #include <iostream>
2. using namespace std;
3.
4. int main ()
5. {
6. // declaration of the pointer variables
7. int *pt = new int (65);
8.
9. // use reinterpre_cast operator to type cast the pointer variables
10. char *ch = reinterpret_cast <char *> (pt);
11.
12. cout << " The value of pt: " << pt << endl;
13. cout << " The value of ch: " << ch << endl;
14.
15. // get value of the defined variable using pointer
16. cout << " The value of *ptr: " << *pt << endl;
17. cout << " The value of *ch: " << *ch << endl;
18. return 0;
19.
20. }
Output:
The value of pt: 0x5cfed0
The value of ch: A
The value of *ptr: 65
The value of *ch: A
Const Cast
The const_cast is used to change or manipulate the const behavior of the source pointer. It means
we can perform the const in two ways: setting a const pointer to a non-const pointer or deleting
or removing the const from a const pointer.
Let's write a program to cast a source pointer to a non-cast pointer using the const_cast in C++.
1. #include <iostream>
2. using namespace std;
3.
4. // define a function
5. int disp(int *pt)
6. {
7. return (*pt * 10);
8. }
9.
10. int main ()
11. {
12. // declare a const variable
13. const int num = 50;
14. const int *pt = # // get the address of num
15.
16. // use const_cast to chnage the constness of the source pointer
17. int *ptr = const_cast <int *> (pt);
18. cout << " The value of ptr cast: " << disp(ptr);
19. return 0;
20.
21. }
Output:
The value of ptr cast: 500
C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before +
(additive operator).
C/C++ Preprocessors
As the name suggests Preprocessors are programs that process our source code before compilation.
There are a number of steps involved between writing a program and executing a program in C / C++.
Let us have a look at these steps before we actually start learning about Preprocessors.
You can see the intermediate steps in the above diagram. The source code written by programmers is
stored in the file program.c. This file is then processed by preprocessors and an expanded source code
file is generated named program. This expanded file is compiled by the compiler and an object code
file is generated named program .obj. Finally, the linker links this object code file to the object code of
the library functions to generate the executable file program.exe.
Preprocessor programs provide preprocessors directives which tell the compiler to preprocess the
source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The
‘#’ symbol indicates that, whatever statement starts with #, is going to the preprocessor program, and
preprocessor program will execute this statement. Examples of some preprocessor directives
are: #include, #define, #ifndef etc. Remember that # symbol only provides a path that it will go to the
preprocessor, and command such as include is processed by preprocessor program. For example,
include will include extra code to your program. We can place these preprocessor directives anywhere
in our program.
There are 4 main types of preprocessor directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
Let us now learn about each of these directives in detail.
Macros: Macros are a piece of code in a program which is given some name. Whenever this name
is encountered by the compiler the compiler replaces the name with the actual piece of code. The
‘#define’ directive is used to define a macro. Let us now understand the macro definition with the
help of a program:
#include <iostream>
// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++) {
std::cout << i << "\n";
}
return 0;
}
Output:
0
1
2
3
4
In the above program, when the compiler executes the word LIMIT it replaces it with 5. The word
‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
Note: There is no semi-colon(‘;’) at the end of macro definition. Macro definitions do not need a semi-
colon to end.
Macros with arguments: We can also pass arguments to macros. Macros defined with arguments
works similarly as functions. Let us understand this with a program:
#include <iostream>
// macro with parameter
#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5, area;
area = AREA(l1, l2);
std::cout << "Area of rectangle is: " << area;
return 0;
}
Output:
Area of rectangle is: 50
We can see from the above program that, whenever the compiler finds AREA(l, b) in the program it
replaces it with the statement (l*b) . Not only this, the values passed to the macro template AREA(l, b)
will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5.
File Inclusion: This type of preprocessor directive tells the compiler to include a file in the source
code program. There are two types of files which can be included by the user in the program:
Header File or Standard files: These files contains definition of pre-defined functions
like printf(), scanf() etc. These files must be included for working with these functions.
Different function are declared in different header files. For example standard I/O
functions are in ‘iostream’ file whereas functions which perform string operations are in
‘string’ file.
Syntax:
#include< file_name >
where file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the compiler to look
for the file in standard directory.
user defined files: When a program becomes very large, it is good practice to divide it into smaller
files and include whenever needed. These types of files are user defined files. These files can be
included as:
#include"filename"
Conditional Compilation: Conditional Compilation directives are type of directives which helps to
compile a specific portion of the program or to skip compilation of some specific part of the
program based on some conditions. This can be done with the help of two preprocessing commands
‘ifdef‘ and ‘endif‘.
Syntax:
#ifdef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
#endif
If the macro with name as ‘macroname‘ is defined then the block of statements will execute normally
but if it is not defined, the compiler will simply skip this block of statements.
Other directives: Apart from the above directives there are two more directives which are not
commonly used. These are:
#undef Directive: The #undef directive is used to undefine an existing macro. This
directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement every “#ifdef
LIMIT” statement will evaluate to false.
#pragma Directive: This directive is a special purpose directive and is used to turn on or off some
features. This type of directives are compiler-specific, i.e., they vary from compiler to compiler.
Some of the #pragma directives are discussed below:
#pragma startup and #pragma exit: These directives helps us to specify the functions that are
needed to run before program startup( before the control passes to main()) and just before
program exit (just before the control returns from main()).
Note: Below program will not work with GCC compilers.
Look at the below program:
#include <bits/stdc++.h>
using namespace std;
void func1();
void func2();
#pragma startup func1
#pragma exit func2
void func1()
{
cout << "Inside func1()\n";
}
void func2()
{
cout << "Inside func2()\n";
}
int main()
{
void func1();
void func2();
cout << "Inside main()\n";
return 0;
}
// This code is contributed by shivanisinghss2110
Output:
Inside func1()
Inside main()
Inside func2()
The above code will produce the output as given below when run on GCC compilers:
Inside main()
This happens because GCC does not supports #pragma startup or exit. However, you can use the below
code for a similar output on GCC compilers.
#include <iostream>
using namespace std;
void func1();
void func2();
void __attribute__((constructor)) func1();
void __attribute__((destructor)) func2();
void func1()
{
printf("Inside func1()\n");
}
void func2()
{
printf("Inside func2()\n");
}
// Driver code
int main()
{
printf("Inside main()\n");
return 0;
}
// This code is contributed by Shivani
#pragma warn Directive: This directive is used to hide the warning message which are displayed
during compilation.
We can hide the warnings as shown below:
#pragma warn -rvl: This directive hides those warning which are raised when a function which is
supposed to return a value does not returns a value.
#pragma warn -par: This directive hides those warning which are raised when a function does not
uses the parameters passed to it.
#pragma warn -rch: This directive hides those warning which are raised when a code is
unreachable. For example: any code written after the return statement in a function is unreachable.
C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be easy to handle the
application.
In C++, global namespace is the root namespace. The global::std will always refer to the
namespace "std" of C++ Framework.
C++ namespace Example
Let's see the simple example of namespace which include variable and functions.
1. #include <iostream>
2. using namespace std;
3. namespace First {
4. void sayHello() {
5. cout<<"Hello First Namespace"<<endl;
6. }
7. }
8. namespace Second {
9. void sayHello() {
10. cout<<"Hello Second Namespace"<<endl;
11. }
12. }
13. int main()
14. {
15. First::sayHello();
16. Second::sayHello();
17. return 0;
18. }
Output:
Hello First Namespace
Hello Second Namespace
Output:
Hello First Namespace
CONTROL STRUCTURES
C++ if-else
In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.
1. if(condition){
2. //code to be executed
3. }
C++ If Example
1. #include <iostream>
2. using namespace std;
3.
4. int main () {
5. int num = 10;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number";
9. }
10. return 0;
11. }
Output:/p>
It is even number
ADVERTISEMENT BY ADRECOVER
Output:
It is odd number
C++ If-else Example: with input from user
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int num;
5. cout<<"Enter a Number: ";
6. cin>>num;
7. if (num % 2 == 0)
8. {
9. cout<<"It is even number"<<endl;
10. }
11. else
12. {
13. cout<<"It is odd number"<<endl;
14. }
15. return 0;
16. }
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number
Output:
Enter a number to check grade:66
C Grade
Output:
Enter a number to check grade:-2
wrong number
C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement in C++.
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
12. break;
13. }
Output:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.
1. for(initialization; condition; incr/decr){
2. //code to be executed
3. }
Flowchart:
Output:
1
2
3
4
5
6
7
8
9
10
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output:
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c
Flowchart:
C++ While Loop Example
Let's see a simple example of while loop to print table of 1.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }
Output:
1
2
3
4
5
6
7
8
9
10
Let's see a simple example of nested while loop in C++ programming language.
1. #include <iostream>
2. using namespace std;
3. int main () {
4. int i=1;
5. while(i<=3)
6. {
7. int j = 1;
8. while (j <= 3)
9. {
10. cout<<i<<" "<<j<<"\n";
11. j++;
12. }
13. i++;
14. }
15. }
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
The C++ do-while loop is executed at least once because condition is checked after loop body.
1. do{
2. //code to be executed
3. }while(condition);
Flowchart:
Output:
1
2
3
4
5
6
7
8
9
10
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
C++ Infinitive do-while Loop
In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.
1. do{
2. //code to be executed
3. }while(true);
Output:
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c
Flowchart:
C++ Break Statement Example
Let's see a simple example of C++ break statement which is used inside the loop.
1. #include <iostream>
2. using namespace std;
3. int main() {
4. for (int i = 1; i <= 10; i++)
5. {
6. if (i == 5)
7. {
8. break;
9. }
10. cout<<i<<"\n";
11. }
12. }
Output:
1
2
3
4
Output:
1
2
3
4
6
7
8
9
10
Output:
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
It can be used to transfer control from deeply nested loop or switch case label.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. ineligible:
6. cout<<"You are not eligible to vote!\n";
7. cout<<"Enter your age:\n";
8. int age;
9. cin>>age;
10. if (age < 18){
11. goto ineligible;
12. }
13. else
14. {
15. cout<<"You are eligible to vote!";
16. }
17. }
Output: