You are on page 1of 42

Unit 1

PROCEDURAL PROGRAMMING VS OBJECT-ORIENTED PROGRAMMING

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is In object-oriented programming, the program


divided into small parts called functions. is divided into small parts called objects.

Procedural programming follows a top-down Object-oriented programming follows


approach. a bottom-up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

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.

In procedural programming, overloading is not Overloading is possible in object-oriented


possible. programming.

In procedural programming, there is no concept In object-oriented programming, the concept


of data hiding and inheritance. of data hiding and inheritance is used.

In procedural programming, the function is In object-oriented programming, data is more


more important than the data. important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for designing Object-oriented programming is used for


medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the


procedure abstraction. concept of data abstraction.

Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

C++ Program Structure


Before starting the abcd of C++ language, you need to learn how to write, compile and run the
first C++ program.
To write the first C++ program, open the C++ console and write the following code:
1. #include <iostream.h>  
2. #include<conio.h>  
3. void main() {  
4.    clrscr();  
5.    cout << "Welcome to C++ Programming.";   
6.    getch();  
7. }  

#include<iostream.h> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output respectively.

#include <conio.h> includes the console input output library functions. The getch() function is


defined in conio.h file.

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.

How to compile and run the C++ program


There are 2 ways to compile and run the C++ program, by menu and by shortcut.

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

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.

You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

BASIC COMPONENTS OF C++


C++ Basic Input/Output
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.

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.

I/O Library Header Files


Let us see the common header files used in C++ programming are:

Header Function and Description


File

<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.

<fstream> It is used to declare services for user-controlled file processing.


Standard output stream (cout)
The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator
(<<) to display the output on a console

Let's see the simple example of standard output stream (cout):


1. #include <iostream>  
2. using namespace std;  
3. int main( ) {  
4.    char ary[] = "Welcome to C++ tutorial";  
5.    cout << "Value of ary is: " << ary << endl;  
6. }  

Output:
Value of ary is: Welcome to C++ tutorial

Standard input stream (cin)


The cin is a predefined object of istream class. It is connected with the standard input device,
which is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to
read the input from a console.

Let's see the simple example of standard input stream (cin):


1. #include <iostream>  
2. using namespace std;  
3. int main( ) {  
4.   int age;  
5.    cout << "Enter your age: ";  
6.    cin >> age;  
7.    cout << "Your age is: " << age << endl;  
8. }  

Output:
Enter your age: 22
Your age is: 22

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
Let's see the simple example of standard end line (endl):
1. #include <iostream>  
2. using namespace std;  
3. int main( ) {  
4. cout << "C++ Tutorial";     
5. cout << " Javatpoint"<<endl;   
6. cout << "End of line"<<endl;   
7. }   

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.

Let's see the syntax to declare a variable:


1. type variable_list;   

The example of declaring variable is given below:


1. int x;    
2. float y;    
3. char z;    

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';    

Rules for defining variables


A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

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;    

Invalid variable names:


1. int 4;    
2. int x y;    
3. int double;  

C++ Data Types


A data type specifies the type of data that a variable can store such as integer, floating, character
etc.

There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types


The basic data types are integer-based and floating-point based. C++ language supports both
signed and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating system.

Let's see the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 32,767

int 2 byte -32,768 to 32,767

signed int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767

short int 2 byte -32,768 to 32,767

signed short int 2 byte -32,768 to 32,767

unsigned short int 2 byte 0 to 32,767

long int 4 byte

signed long int 4 byte

unsigned long int 4 byte

float 4 byte

double 8 byte

long double 10 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

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

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

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try

typeid typename using virtual wchar_t

Type Casting in C++


This section will discuss the type casting of the variables in the C++ programming language. Type
casting refers to the conversion of one data type to another in a program. Typecasting can be
done in two ways: automatically by the compiler and manually by the programmer or user. Type
Casting is also known as Type Conversion.

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.

Program to use the implicit type casting in C++

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.

Explicit Type Casting or Explicit Type Conversion


o It is also known as the manual type casting in a program.
o It is manually cast by the programmer or user to change from one data type to another
type in a program. It means a user can easily cast one data to another according to the
requirement in a program.
o It does not require checking the compatibility of the variables.
o In this casting, we can upgrade or downgrade the data type of one variable to another in a
program.
o It uses the cast () operator to change the type of a variable.

Syntax of the explicit type casting


1. (type) expression;  

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

Explicit Type Casting:


The value of float variable (res): 4.2

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

The length of the rectangle is: 57.3456


The breadth of the rectangle is: 12.9874
The area of the rectangle is: 744.77

Some different types of the Type Casting

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).

Syntax of the Static Cast


1. static_cast < new_data_type> (expression);  

Program to demonstrate the use of the Static Cast

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.

Program to demonstrate the use of the Dynamic Cast in C++

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.

Reinterpret Cast Type

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.

Syntax of the reinterpret_cast type


1. reinterpret_cast <type> expression;  

Program to use the Reinterpret Cast in C++

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.

Syntax of the Const Cast type


1. const_cast <type> exp;  

Program to use the Const Cast in C++

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

Precedence of Operators in C++


The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left.

Let's understand the precedence by the example given below:


1. int data=5+10*10;    

The "data" variable will contain 105 because * (multiplicative operator) is evaluated before +
(additive operator).

The precedence and associativity of C++ operators is given below:


Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Right to left

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == !=/td> Right to left

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Right to left

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

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.

For accessing the class of a namespace, we need to use namespacename::classname. We can


use using keyword so that we don't have to use complete name all the time.

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

C++ namespace example: by using keyword


Let's see another example of namespace where we are using "using" keyword so that we don't
have to use complete name for accessing a namespace program.
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. using namespace First;  
14. int main () {  
15.    sayHello();  
16.    return 0;  
17. }  

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

C++ IF-else Statement


The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
1. if(condition){    
2. //code if condition is true    
3. }else{    
4. //code if condition is false    
5. }    

ADVERTISEMENT BY ADRECOVER

C++ If-else Example


1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.    int num = 11;    
5.             if (num % 2 == 0)    
6.             {    
7.                 cout<<"It is even number";    
8.             }   
9.             else  
10.             {    
11.                 cout<<"It is odd number";    
12.             }  
13.    return 0;  
14. }  

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

C++ IF-else-if ladder Statement


The C++ if-else-if ladder statement executes one condition from multiple statements.
1. if(condition1){    
2. //code to be executed if condition1 is true    
3. }else if(condition2){    
4. //code to be executed if condition2 is true    
5. }    
6. else if(condition3){    
7. //code to be executed if condition3 is true    
8. }    
9. ...    
10. else{    
11. //code to be executed if all the conditions are false    
12. }    

C++ If else-if Example


1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.        int num;  
5.        cout<<"Enter a number to check grade:";    
6.        cin>>num;  
7.             if (num <0 || num >100)    
8.             {    
9.                 cout<<"wrong number";    
10.             }    
11.             else if(num >= 0 && num < 50){    
12.                 cout<<"Fail";    
13.             }    
14.             else if (num >= 50 && num < 60)    
15.             {    
16.                 cout<<"D Grade";    
17.             }    
18.             else if (num >= 60 && num < 70)    
19.             {    
20.                 cout<<"C Grade";    
21.             }    
22.             else if (num >= 70 && num < 80)    
23.             {    
24.                 cout<<"B Grade";    
25.             }    
26.             else if (num >= 80 && num < 90)    
27.             {    
28.                 cout<<"A Grade";    
29.             }    
30.             else if (num >= 90 && num <= 100)    
31.             {    
32.                 cout<<"A+ Grade";  
33.             }    
34.     }    

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. }    

C++ Switch Example


1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.        int num;  
5.        cout<<"Enter a number to check grade:";    
6.        cin>>num;  
7.            switch (num)    
8.           {    
9.               case 10: cout<<"It is 10"; break;    
10.               case 20: cout<<"It is 20"; break;    
11.               case 30: cout<<"It is 30"; break;    
12.               default: cout<<"Not 10, 20 or 30"; break;    
13.           }    
14.     }    

Output:
Enter a number:
10
It is 10

Output:
Enter a number:
55
Not 10, 20 or 30

C++ For Loop


The C++ for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop than while or do-while loops.

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:

C++ For Loop Example


1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.          for(int i=1;i<=10;i++){      
5.             cout<<i <<"\n";      
6.           }       
7.     }   

Output:
1
2
3
4
5
6
7
8
9
10

C++ Nested For Loop


In C++, we can use for loop inside another for loop, it is known as nested for loop. The inner loop
is executed fully when outer loop is executed one time. So if outer loop and inner loop are
executed 4 times, inner loop will be executed 4 times for each outer loop i.e. total 16 times.

C++ Nested For Loop Example


Let's see a simple example of nested for loop in C++.
1. #include <iostream>  
2. using namespace std;  
3.    
4. int main () {  
5.         for(int i=1;i<=3;i++){      
6.              for(int j=1;j<=3;j++){      
7.             cout<<i<<" "<<j<<"\n";      
8.           }     
9.         }  
10.     }    

Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinite For Loop


If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple
example of infinite for loop in C++.
1. #include <iostream>  
2. using namespace std;  
3.    
4. int main () {  
5.         for (; ;)    
6.           {    
7.                   cout<<"Infinitive For Loop";    
8.           }    
9.     }    

Output:
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c

C++ While loop


In C++, while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed, it is recommended to use while loop than for loop.
1. while(condition){    
2. //code to be executed    
3. }    

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

C++ Nested While Loop Example


In C++, we can use while loop inside another while loop, it is known as nested while loop. The
nested while loop is executed fully when outer loop is executed once.

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

C++ Infinitive While Loop Example:


We can also create infinite while loop by passing true as the test condition.
1. #include <iostream>  
2. using namespace std;  
3. int main () {  
4.         while(true)  
5.           {    
6.                   cout<<"Infinitive While Loop";    
7.           }    
8.     }    
Output:
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c

C++ Do-While Loop


The C++ do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.

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:

C++ do-while Loop Example


Let's see a simple example of C++ do-while loop to print the table of 1.
1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.      int i = 1;    
5.           do{    
6.               cout<<i<<"\n";    
7.               i++;    
8.           } while (i <= 10) ;    
9. }  

Output:
1
2
3
4
5
6
7
8
9
10

C++ Nested do-while Loop


In C++, if you use do-while loop inside another do-while loop, it is known as nested do-while
loop. The nested do-while loop is executed fully for each outer do-while loop.

Let's see a simple example of nested do-while loop in C++.


1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.      int i = 1;    
5.          do{    
6.               int j = 1;          
7.               do{    
8.                 cout<<i<<"\n";        
9.                   j++;    
10.               } while (j <= 3) ;    
11.               i++;    
12.           } while (i <= 3) ;     
13. }  

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);  

C++ Infinitive do-while Loop Example


1. #include <iostream>  
2. using namespace std;  
3. int main() {  
4.       do{    
5.               cout<<"Infinitive do-while Loop";    
6.           } while(true);     
7. }  

Output:
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c

C++ Break Statement


The C++ break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.
1. jump-statement;      
2. break;  

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

C++ Break Statement with Inner Loop


The C++ break statement breaks inner loop only if you use break statement inside the inner loop.

Let's see the example code:


1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.     for(int i=1;i<=3;i++){        
6.             for(int j=1;j<=3;j++){        
7.                 if(i==2&&j==2){        
8.                     break;        
9.                         }        
10.                     cout<<i<<" "<<j<<"\n";             
11.                     }        
12.           }    
13. }  
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3

C++ Continue Statement


The C++ continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it continues
only inner loop.
1. jump-statement;      
2. continue;     

C++ Continue Statement Example


1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.      for(int i=1;i<=10;i++){      
6.             if(i==5){      
7.                 continue;      
8.             }      
9.             cout<<i<<"\n";      
10.         }        
11. }  

Output:
1
2
3
4
6
7
8
9
10

C++ Continue Statement with Inner Loop


C++ Continue Statement continues inner loop only if you use continue statement inside the inner
loop.
1. #include <iostream>  
2. using namespace std;  
3. int main()  
4. {  
5.  for(int i=1;i<=3;i++){        
6.             for(int j=1;j<=3;j++){        
7.              if(i==2&&j==2){        
8.                 continue;        
9.                         }        
10.                 cout<<i<<" "<<j<<"\n";                  
11.                     }        
12.             }            
13. }  

Output:
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

C++ Goto Statement


The C++ goto statement is also known as jump statement. It is used to transfer control to the
other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

C++ Goto Statement Example


Let's see the simple example of goto statement in C++.

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:

You are not eligible to vote!


Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

You might also like