0% found this document useful (0 votes)
8 views

Notes-All

The document provides an overview of C and C++ programming languages, detailing their features, history, and basic syntax. C is described as a foundational procedural programming language, while C++ is introduced as an object-oriented extension of C with additional capabilities. Key topics include data types, variables, operators, keywords, and input/output operations in C++, along with examples and rules for defining identifiers.

Uploaded by

furryk24
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Notes-All

The document provides an overview of C and C++ programming languages, detailing their features, history, and basic syntax. C is described as a foundational procedural programming language, while C++ is introduced as an object-oriented extension of C with additional capabilities. Key topics include data types, variables, operators, keywords, and input/output operations in C++, along with examples and rules for defining identifiers.

Uploaded by

furryk24
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

UNIT-1

What is C?

C is a structural or procedural oriented programming language which is machine-


independent and extensively used in various applications.

C is the basic programming language that can be used to develop from the operating
systems (like Windows) to complex programs like Oracle database, Git, Python
interpreter, and many more. C programming language can be called a god's
programming language as it forms the base for other programming languages. If we
know the C language, then we can easily learn other programming languages. C
language was developed by the great computer scientist Dennis Ritchie at the Bell
Laboratories. It contains some additional features that make it unique from other
programming languages.

What is C++?

C++ is a special-purpose programming language developed by Bjarne Stroustrup at


Bell Labs circa 1980. C++ language is very similar to C language, and it is so
compatible with C that it can run 99% of C programs without changing any source of
code though C++ is an object-oriented programming language, so it is safer and well-
structured programming language than C.

C++ history

History of C++ language is interesting to know. Here we are going to discuss brief
history of C++ language.

C++ programming language was developed in 1980 by Bjarne Stroustrup at bell


laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.

Bjarne Stroustrup is known as the founder of C++ language.

C++ Features

C++ is a widely used programming language.

It provides a lot of features that are given below.

1. Simple
2. Abstract Data types
3. Machine Independent or Portable
4. Mid-level programming language
5. Structured programming language
6. Rich Library
7. Memory Management
8. Quicker Compilation
9. Pointers
10. Recursion
11. Extensible
12. Object-Oriented
13. Compiler based
14. Reusability
15. National Standards
16. Errors are easily detected
17. Power and Flexibility
18. Strongly typed language
19. Redefine Existing Operators
20. Modeling Real-World Problems
21. Clarity

1) Simple

C++ is a simple language because it provides a structured approach (to break the
problem into parts), a rich set of library functions, data types, etc.

2) Abstract Data types

In C++, complex data types called Abstract Data Types (ADT) can be created using
classes.

4) Mid-level / Intermediate programming language

C++ includes both low-level programming and high-level language so it is known as a


mid-level and intermediate programming language. It is used to develop system
applications such as kernel, driver, etc.

5) Structured programming language

C++ is a structured programming language. In this we can divide the program into
several parts using functions.

6) Rich Library

C++ provides a lot of inbuilt functions that make the development fast. Following are
the libraries used in C++ programming are:
o <iostream>
o <cmath>
o <cstdlib>
o <fstream>

7) Memory Management

C++ provides very efficient management techniques. The various memory


management operators help save the memory and improve the program's efficiency.
These operators allocate and deallocate memory at run time. Some common memory
management operators available C++ are new, delete etc.

8) Quicker Compilation

C++ programs tend to be compact and run quickly. Hence the compilation and
execution time of the C++ language is fast.

9) Pointer

C++ provides the feature of pointers. We can use pointers for memory, structures,
functions, array, etc. We can directly interact with the memory by using the pointers.

10) Recursion

In C++, we can call the function within the function. It provides code reusability for
every function.

11) Extensible

C++ programs can easily be extended as it is very easy to add new features into the
existing program.

12) Object-Oriented

In C++, object-oriented concepts like data hiding, encapsulation, and data abstraction
can easily be implemented using keyword class, private, public, and protected access
specifiers. Object-oriented makes development and maintenance easier.

13) Compiler based

C++ is a compiler-based programming language, which means no C++ program can


be executed without compilation. C++ compiler is easily available, and it requires
very little space for storage. First, we need to compile our program using a compiler,
and then we can execute our program.

14) Reusability
With the use of inheritance of functions programs written in C++ can be reused in any
other program of C++. You can save program parts into library files and invoke them
in your next programming projects simply by including the library files. New
programs can be developed in lesser time as the existing code can be reused. It is also
possible to define several functions with same name that perform different task. For
Example: abs () is used to calculate the absolute value of integer, float and long
integer.

16) Errors are easily detected

It is easier to maintain a C++ programs as errors can be easily located and rectified. It
also provides a feature called exception handling to support error handling in your
program.

17) Power and Flexibility

C++ is a powerful and flexible language because of most of the powerful flexible and
modern UNIX operating system is written in C++. Many compilers and interpreters
for other languages such as FORTRAN, PERL, Python, PASCAL, BASIC, LISP, etc.,
have been written in C++. C++ programs have been used for solving physics and
engineering problems and even for animated special effects for movies.

19) Redefine Existing Operators

C++ allows the programmer to redefine the meaning of existing operators such as +, -
. For Example, The "+" operator can be used for adding two numbers and
concatenating two strings.

21) Clarity

The keywords and library functions used in C++ resemble common English words.

To write the first C++ program, open the C++ console and write the following code:

#include <iostream>
int main() {
std::cout << "hi";
return 0;
}
#include<iostream>
using namespace std;
int main()
{

Cout<<”hello”;
return 0;
};

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


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

main() The main() function is the entry point of every program in C++ language.

cout << "Welcome " is used to print the data "Welcome " on the console.

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.

Header File Function and Description

<iostream> It is used to define the cout, cin , which correspond to standard


output stream, standard input stream and standard error stream, respectively.
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

#include <iostream>
using namespace std;
int main( ) {
char ary[] = "cse";
cout << "Value of ary is: " << ary << endl;
}

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.

#include <iostream>
using namespace std;
int main( )
{
int grade ;
cout << "Enter your grade";
cin >>grade ;
cout << "hgjfguvfmh bhj Your grade: " << grade << endl;
}

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.
#include <iostream>
using namespace std;
int main( ) {
cout << ”hi"<<endl;
cout << " hello"<<endl;
cout << "welcome"<<endl;
}

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.

the syntax to declare a variable:

type variable_list;

int x;
float y;
char z;

int x=5,b=10; //declaring 2 variable of integer type


float f=30.8;
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.

1. int a;
2. int _ab;
3. int a30;
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

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.

C++ Keywords

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

A list of 30 Keywords in C++ Language.

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

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.

int data=5+10*10;

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

C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions,
arrays, or other user-defined data types created by the programmer. They are the basic
requirement of any language. Every language has its own rules for naming the
identifiers.

In short, we can say that the C++ identifiers represent the essential elements in a
program which are given below:

o Constants
o Variables
o Functions
o Labels
o Defined data types

Some naming rules are common in both C and C++. They are as follows:

o Only alphabetic characters, digits, and underscores are allowed.


o The identifier name cannot start with a digit, i.e., the first letter should be
alphabetical. After the first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that
C++ identifiers are case-sensitive.
o A declared keyword cannot be used as a variable name.

For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'.
Both the identifiers will be different as the letter 'N' in the first case in uppercase
while lowercase in second. Therefore, it proves that identifiers are case-sensitive.

Valid Identifiers

The following are the examples of valid identifiers are:

Result
Test2
_sum
power

Invalid Identifiers
The following are the examples of invalid identifiers:

Examples:

Sum-1 // containing special character '-'.


2data // the first letter is a digit.
break // use of a keyword.
#include <iostream>
using namespace std;
int main()
{
int a;
int A;
cout<<"Enter the values of 'a' and 'A'";
cin>>a;
cin>>A;
cout<<"The values "<<a<<endl<<A;
return 0;
}

What are the keywords?

Keywords are the reserved words that have a special meaning to the compiler. They
are reserved for a special purpose, which cannot be used as the identifiers. For
example, 'for', 'break', 'while', 'if', 'else', etc. are the predefined words where
predefined words are those words whose meaning is already known by the compiler.
Whereas, the identifiers are the names which are defined by the programmer to the
program elements such as variables, functions, arrays, objects, classes.

Differences between Identifiers and Keywords

The following is the list of differences between identifiers and keywords:


Identifiers Keywords

Identifiers are the names defined by the programmer to the Keywords are the reserved words whose meaning
basic elements of a program. is known by the compiler.

It is used to identify the name of the variable. It is used to specify the type of entity.

It can consist of letters, digits, and underscore. It contains only letters.

It can use both lowercase and uppercase letters. It uses only lowercase letters.

No special character can be used except the underscore. It cannot contain any special character.

The starting letter of identifiers can be lowercase, It can be started only with the lowercase letter.
uppercase or underscore.

Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.

C++ Comments

The C++ comments are statements that are not executed by the compiler. The
comments in C++ programming can be used to provide explanation of the code,
variable, method or class. By the help of comments, you can hide the program code
also.

There are two types of comments in C++.

o Single Line comment


o Multi Line comment

C++ Single Line Comment

The single line comment starts with // (double slash). Let's see an example of single
line comment in C++.

#include <iostream>
using namespace std;
int main()
{
int x = 11; // x is a variable
cout<<x;
Return 0;
}

C++ Multi Line Comment

The C++ multi line comment is used to comment multiple lines of code. It is
surrounded by slash and asterisk (/∗ ..... ∗/). Let's see an example of multi line
comment in C++.

#include <iostream>
using namespace std;
int main()
{
/* declare and
print variable in C++. */
int x = 35;
cout<<x;
return 0;
}
C++ Expression

C++ expression consists of operators, constants, and variables which are arranged
according to the rules of the language. It can also contain function calls which return
values. An expression can consist of one or more operands, zero or more operators to
compute a value. Every expression produces some value which is assigned to the
variable with the help of an assignment operator.

#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration.
x=(3/2) + 2; // constant expression
cout<<"Value of x is : "<<x; // displaying the value of x.
return 0;
}

#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration.
int y; // variable declaration
int z; // variable declaration
cout<<"Enter the values of x and y";
cin>>x>>y;

z=x+y;
cout<<"Value of z is :"<<z;
Return 0;
}

Relational Expressions
A relational expression is an expression that produces a value of type bool, which can
be either true or false. It is also known as a boolean expression.

#include <iostream>
using namespace std;
int main()
{
int a=45; // variable declaration
int b=78; // variable declaration
bool y= a>b; // relational expression
cout<<"Value of y is :"<<y; // displaying the value of y.
return 0;
}

Value of y is :0

Logical Expressions

A logical expression is an expression that combines two or more relational


expressions and produces a bool type value. The logical operators are '&&' and '||' that
combines two or more relational expressions.

#include <iostream>
using namespace std;
int main()
{
int a=2;
int b=7;
int c=4;
cout<<!((a>b)&&(a<c));
return 0;
}
0
Bitwise Expressions

A bitwise expression is an expression which is used to manipulate the data at a bit


level. They are basically used to shift the bits.

For example:

x=3

x>>3 // This statement means that we are shifting the three-bit position to the right.

In the above example, the value of 'x' is 3 and its binary value is 0011. We are shifting
the value of 'x' by three-bit position to the right. Let's understand through the
diagrammatic representation.
#include <iostream>
using namespace std;
int main()
{
int x=5; // variable declaration
cout << (x>>1) ;
return 0;
}
In the above code, we have declared a variable 'x'. After declaration, we applied the
bitwise operator, i.e., right shift operator to shift one-bit position to right.
2

}
#include <iostream>
using namespace std;
int main()
{
int x=1; // variable declaration
std::cout << (x<<1) << std::endl;
return 0;
}

Assignment operator

In the above code, we have declared a variable 'x'. After declaration, we applied the
left shift operator to variable 'x' to shift the three-bit position to the left.56
#include <iostream>
using namespace std;
int main()
{
int a; // variable declaration
int b; // variable declaration
a=b=c=80; // chained assignment
cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< ;
return 0;
}

In the above code, we have declared two variables, i.e., 'a' and 'b'. Then, we have
assigned the same value to both the variables using chained assignment expression.

o Embedded Assignment Expression

An embedded assignment expression is an assignment expression in which


assignment expression is enclosed within another assignment expression.

#include <iostream>
using namespace std;
int main()
{
int a; // variable declaration
int b; // variable declaration
a=10+(b=90); // embedded assignment expression
cout <<"Values of 'a' is " <<a<<;
return 0;
}
o compound Assignment

A compound assignment expression is an expression which is a combination of an


assignment operator and binary operator.

For example,

1. a+=10;
#include <iostream>
using namespace std;
int main()
{
int a=10; // variable declaration
a-=10; // compound assignment
cout << "Value of a is :" <<a<<; // displaying the value of a.
return 0;
}

UNIT-2

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 if-else-if ladder
o switch statement

C++ IF Statement

The C++ if statement tests the condition. It is executed if condition is true.

#include <iostream>

using namespace std;

int main () {
int num = 20;
if (num % 5 == 0)
{
cout<<"It is divisible by 5";
}
return 0;
}

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.

if(condition){
//code if condition is true
}
Else
{
//code if condition is false
}

#include <iostream>
using namespace std;
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else
{
cout<<"It is odd number"<<endl;
}
return 0;
}

C++ IF-else-if ladder Statement

The C++ if-else-if ladder statement executes one condition from multiple statements.

if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}
Enter a number to check grade:66
C Grade

C++ switch

The C++ switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement in C++.

switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......

default:
//code to be executed if all cases are not matched;
break;
}

C++ Switch Example

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num; 3
switch (num)
{
case 1: cout<<"It is 10"; break;
case 2: cout<<"It is 20"; break;
case 3: cout<<"It is 30"; break;

default: cout<<"Not 10, 20 or 30"; break;


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

Entry cpntrolled loop

Top tested loop

for(initialization; condition; incr/decr)


{
//code to be executed
}

#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i <<"\n";
}
}

1
2

1
2
3
4
5
6
7
8
9
10

5
6

C++ Nested For Loop Example

Let's see a simple example of nested for loop in C++.

#include <iostream>
using namespace std;
int main()
{
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for(int i = 1; i <= rows; i++)
{
for(int j = 1; j <= i; j++)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}

10Output:

**

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.

Top tested loop

Entry controlled loop


while(condition)
{
//code to be executed
}

#include <iostream>
using namespace std;
int main()
{
int i=11;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
return 0;
}

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.

Bottom tested loop

Exit controlled loop

Do
{
//code to be executed
}
while(condition);
#include <iostream>
using namespace std;
int main() {
int i = 1;
do
{
cout<<i<<"\n";
i++;
}
while (i >= 10) ;
return 0;
}

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.

jump-statement;
break;

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

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.

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

Syntax :

Goto statement :

statement:

#include <iostream>
using namespace std;
int main()
{
ineligible: cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age; 15
if (age < 18)
{
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}
}

UNIT-3
C++ Functions
The function in C++ language is also known as
procedure or subroutine in other programming languages.

To perform any task, we can create function. A function


can be called many times. It provides modularity and
code reusability.

Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

2) Code optimization

It makes the code optimized, we don't need to write much code.

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are


declared in the C++ header files such as ceil(x), cos(x),
exp(x), etc.

2. User-defined functions: are the functions which are


created by the C++ programmer, so that he/she can use it
many times. It reduces complexity of a big program and
optimizes the code.
Declaration of a function

The syntax of creating function in C++ language is given


below:

Function with no return type no arguments.

Function with return type and no arguments

Function with return and with arguments

Function with no return type and with arguments.

Syntax :

Function defintion

return type function name(datatype parameter...)


{
//code to be executed
}
Syntax of function call
Functionname(parameters);
#include <iostream>
using namespace std;
void func()
{

cout<<”hello”<<endl;
}
int main()
{
func();
func();
func();
cout<<”the program has ended”;
}
Call by value and call by reference in C++
There are two ways to pass value or data to function in C
language: call by value and call by reference. Original
value is not modified in call by value but it is modified
in call by reference.

#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}
Value of the data is: 3

Call by reference in C++

In call by reference, original value is modified because


we pass reference (address).

Here, address of the value is passed in the function, so


actual and formal arguments share the same address
space. Hence, value changed inside the function, is
reflected inside as well as outside the function.

#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}

Value of x is: 100


Value of y is: 500

C++ Recursion

When function is called within the same function, it is


known as recursion in C++. The function which calls the
same function, is known as recursive function.

A function that calls itself, and doesn't perform any task


after function call, is known as tail recursion. In tail
recursion, we generally call the same function with
return statement.

#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}

Enter any number: 5


Factorial of a number is: 120

Inline function in C++

If make a function as inline, then the compiler replaces


the function calling location with the definition of the
inline function at compile time.

Syntax for an inline function:

inline return_type function_name(parameters)


{
// function code?
}

When the inline function is encountered, then the definition of the function is copied
to it. In this case, there is no control transfer which saves a lot of time and also
decreases the overhead.

#include<iostream>
using namespace std;
Class cal
{
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
Cal c;
cout<<"Addition of 'a' and 'b' is:"<<c.add(2,3);
return 0;
}

If we create two or more members having the same name


but different in number or type of parameter, it is known
as C++ overloading.
C++ Function Overloading

Function Overloading is defined as the process of having


two or more function with the same name, but different
in parameters is known as function overloading in C++.

The advantage of Function overloading is that it increases the readability of the


program because you don't need to use different names for the same action.

C++ Function Overloading Example

Let's see the simple example of function overloading


where we are changing number of arguments of add()
method.

#include <iostream>
using namespace std;
class Cal {
public:
int add(int a,int b){
return a + b;
}
int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}

30
55

Arrays
Like other programming languages, array in C++ is a
group of similar types of elements that have contiguous
memory location.

An array is a collection of elements of same datatype.

C++ Array Types

There are 2 types of arrays in C++ programming:

1. Single Dimensional Array


2. Multidimensional Array

#include <iostream>
using namespace std;
int main()
{
int a[5]={10, 0, 20, 0, 30};
for (int i = 0; i < 5; i++)
{
cout<<a[i]<<"\n";
}
}

C++ Multidimensional Arrays

The multidimensional array is also known as rectangular


arrays in C++. It can be two dimensional or three
dimensional. The data is stored in tabular form (row ∗
column) which is also known as matrix.

#include <iostream>
using namespace std;
int main()
{
int test[3][3]={{1,2,3},{4,5,6},{7,8,9}}; //declaration of 2D array

//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}

5 10 0
0 15 20
30 0 10

C++ OOPs Concepts

The major purpose of C++ programming is to introduce


the concept of object orientation to the C programming
language.

Object Oriented Programming is a paradigm that


provides many concepts such as inheritance, data
binding, polymorphism etc.

The programming paradigm where everything is


represented as an object is known as truly object-
oriented programming language. Smalltalk is considered
as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table


etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects.
It simplifies the software development and maintenance
by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Any entity that has state and behavior is known as an


object. For example: chair, pen, table, keyboard, bike etc.
It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and


behaviors of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism

When one task is performed by different ways /many


forms i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g.
shape or rectangle etc.

In C++, we use Function overloading and Function


overriding to achieve polymorphism.

Abstraction
Hiding internal details and showing functionality is
known as abstraction. For example: phone call, we don't
know the internal processing.

In C++, we use abstract class and interface to achieve


abstraction.

Encapsulation

Binding (or wrapping) code and data together into a


single unit is known as encapsulation. For example:
capsule, it is wrapped with different medicines.

Advantage of OOPs over Procedure-oriented programming language

1. OOPs makes development and maintenance easier where as in Procedure-


oriented programming language it is not easy to manage if code grows as project
size grows.
2. OOPs provide data hiding whereas in Procedure-oriented programming
language a global data can be accessed from anywhere.
3. OOPs provide ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.

Object and Class

Since C++ is an object-oriented language, program is


designed using objects and classes in C++.

Object

In C++, Object is a real world entity, for example, chair,


car, pen, mobile, laptop etc.

In other words, object is an entity that has state and


behavior. Here, state means data and behavior means
functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through
object.
Let's see an example to create object of student class using s1 as the reference
variable.

1. Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class.

Class

In C++, class is a group of similar objects. It is a


template from which objects are created. It can have
fields, methods, constructors etc.

Let's see an example of C++ class that has three fields


only.

class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}

Object and Class Example

Let's see an example of class that has two fields: id and


name. It creates instance of the class, initializes the
object and prints the object value.

Class classname

Data members; ----access specifiers datatype


variablename;

Memberfunctions;----accessspecifiers returntype
functionname(parameters)

body

}
};

#include <iostream>
using namespace std;
class Student
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 1;
s1.name = "a";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
1
a

Class Example: Initialize and Display data through method

Let's see another example of C++ class where we are


initializing and displaying object through method.

#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main( ) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(1, "alekhya");
s2.insert(2, "alli");
s1.display();
s2.display();
return 0;
}
1 alekhya
2 alli

Class Example: Store and Display Employee Information

Let's see another example of C++ class where we are


storing and displaying employee information using
method.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main() {
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
e1.insert(1, "alekhya”,2000);
e2.insert(2, "ali", 3000);
e1.display();
e2.display();
return 0;
}
alekhya 2000
ali 3000

Constructor

In C++, constructor is a special method which is invoked


automatically at the time of object creation. It is used to
initialize the data members of new object generally. The
constructor in C++ has the same name as class or
structure.

There can be three types of constructors in C++.

o Default constructor
o Parameterized constructor
o Copy constructor

Default Constructor

A constructor which has no argument is known as


default constructor. It is invoked at the time of creating
object.

Let's see the simple example of C++ default Constructor.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Default Constructor Invoked
Default Constructor Invoked

Parameterized Constructor

A constructor which has parameters is called


parameterized constructor. It is used to provide different
values to distinct objects.

#include <iostream>

using namespace std;

class Employee {

public:

int id;//data member (also instance variable)

string name;//data member(also instance variable)

float salary;

Employee(int i, string n, float s)

id = i;
name = n;

salary = s;

void display()

cout<<id<<" "<<name<<" "<<salary<<endl;

};

int main(void) {

Employee e1 =Employee(1, "ISBAT", 8000); //creating an object of Employee

e1.display();

return 0;

Copy Constructor

A Copy constructor is an overloaded constructor used to


declare and initialize an object from another object.

copy constructor has the following general function prototype:


ClassName(const ClassName &old_obj);

#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
// Copy constructor
Point(const Point &temp)
{
x = temp.x;
y = temp.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor of p2 is called here
// Let us access values assigned by constructors
cout<< "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout<< "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
}

Destructor

A destructor works opposite to constructor; it destructs


the objects of classes. It can be defined only once in a
class. Like constructors, it is invoked automatically.

A destructor is defined like constructor. It must have


same name as class. But it is prefixed with a tilde sign
(~).

Constructor and Destructor Example

Let's see an example of constructor and destructor in


C++ which is called automatically.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ Friend function

If a function is defined as a friend function in C++, then


the protected and private data of a class can be accessed
using the function.

By using the keyword friend compiler knows the given


function is a friend function.

For accessing the data, the declaration of a friend


function should be done inside the body of a class
starting with the keyword friend.

Declaration of friend function in C++

class class_name
{
friend data_type function_name(argument/s); // syntax of f
riend function.
};
#include <iostream>
using namespace std;

class A
{
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
value of x is : 5

Scope Resolution Operator( ::)

when the global and local variable or function has the same name in a program, and
when we call the variable, by default it only accesses the inner or local variable
without calling the global variable. In this way, it hides the global variable or function.
To overcome this situation, we use the scope resolution operator to fetch a program's
hidden variable or function.

Program to access the hidden value using the scope resolution (::) operator
#include <iostream>
using namespace std;
// declare global variable
int num = 50;
int main ()
{
// declare local variable
int num = 100;

// print the value of the variables


cout << " The value of the local variable num: " << num;

// use scope resolution operator (::) to access the global variable


cout << "\n The value of the global variable num: " << ::num;
return 0;
}
The value of the local variable num: 100
The value of the global variable num: 50

Program to define the member function outside of the class using the scope resolution
(::) operator

#include <iostream>
using namespace std;
class Operate
{
public:
// declaration of the member function
void fun();
};
// define the member function outside the class.
void Operate::fun() /* return_type Class_Name::function_name */
{
cout << " It is the member function of the class. ";
}
int main ()
{
// create an object of the class Operate
Operate op;
op.fun();
return 0;
}
It is the member function of the class.

Program to demonstrate the standard namespace using the scope resolution (::)
operator

#include <iostream>
int main ()
{
int num = 0;

// use scope resolution operator with std namespace


std :: cout << " Enter the value of num: ";
std::cin >> num;
std:: cout << " The value of num is: " << num;
}
Enter the value of num: 50
The value of num is: 50

Strings

string class that represents sequence of characters. We


can perform many operations on strings such as
concatenation, comparison, conversion etc.

#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Hello
C++

C++ String Compare Example

#include <iostream>
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char a[] = "mango";
char b[50];
do {
cout<<"What is my favourite fruit? ";
cin>>b;
} while (strcmp (a,b) != 0);
cout<<"Answer is correct!!"<<endl;
return 0;
}
What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

C++ String Concat Example

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[25], b[25];
cout << "Enter the first string: ";
cin>>a;
cout << "Enter the second string: ";
cin>>b;
strcat(a, b);
cout << "a = " << a << endl;
cout << "b = " << b<<endl;
return 0;
}
Enter the key string: Welcome to
Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.

C++ String Copy Example

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[25], b[25];
cout << "Enter the string: ";
cin>>a;
strcpy(b, a);
cout << "string = "<< a << endl;
cout << "copy string = "<< b<<endl;
return 0;
}
Enter the string: ISBAT
String= ISBAT
copy string = ISBAT

C++ String Length Example

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char ary[] = "Welcome to C++ Programming";
cout << "Length of String = " << strlen(ary)<<endl;
return 0;
}

Length of String = 26

UNIT-4
Inheritance
In C++, inheritance is a process in which one object
acquires all the properties and behaviors of its parent
object automatically.

Advantage of C++ Inheritance


Code reusability: Now you can reuse the members of
your parent class. So, there is no need to define the
member again. So less code is required in the class.

Types Of Inheritance
C++ supports five types of inheritance:

o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance

Derived Classes
A Derived class is defined as the class derived from the
base class.

The Syntax of Derived class:

class derived_class_name :visibility-mode base_class_name


{
// body of the derived class.
}

derived_class_name: It is the name of the derived class.


visibility mode: The visibility mode specifies whether the features of the base class
are publicly inherited or privately inherited. It can be public or private.

Single Inheritance
Single inheritance is defined as the inheritance in which
a derived class is inherited from the only one base class.

Where 'A' is the base class, and 'B' is the derived class.

Single Level Inheritance Example: Inheriting Fields


When one class inherits another class, it is known as
single level inheritance. Let's see the example of single
level inheritance which inherits the fields only.

#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
Salary: 60000
Bonus: 5000

Single Level Inheritance Example: Inheriting Methods

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
int main(void) {
Dog d1;
d1.eat();
d1.bark();
return 0;
}
Eating...
Barking...

Multilevel Inheritance
Multilevel inheritance is a process of deriving a class
from another derived class.
Multi Level Inheritance Example
When one class inherits another class which is further
inherited by another class, it is known as multi level
inheritance in C++. Inheritance is transitive so the last
derived class acquires all the members of all its base
classes.

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}
Eating...
Barking...
Weeping...

Multiple Inheritance
Multiple inheritance is the process of deriving a new
class that inherits the attributes from two or more classes.

Syntax of the Derived class:


class D : visibility B-1, visibility B-2, ?
{
// Body of the class;
}
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};

class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
std::cout << "The value of a is : " <<a<< std::endl;
std::cout << "The value of b is : " <<b<< std::endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();

return 0;
}
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30

Hybrid Inheritance
Hybrid inheritance is a combination of more than one
type of inheritance.

#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};

class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}
Enter the value of 'a' :
10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000
Hierarchical Inheritance
Hierarchical inheritance is defined as the process of
deriving more than one class from a base class.

Syntax of Hierarchical inheritance:

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}
Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5

UNIT-5
Polymorphism
The term "Polymorphism" is the combination of "poly"
+ "morphs" which means many forms. It is a greek word.
In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.

o Compile time polymorphism: The overloaded functions are invoked by


matching the type and number of arguments. This information is available at
the compile time and, therefore, compiler selects the appropriate function at
the compile time. It is achieved by function overloading and operator
overloading which is also known as static binding or early binding. Now, let's
consider the case where function name and prototype is same.

class A // base class declaration.


{
int a;
public:
void display()
{
cout<< "Class A ";
}
};
class B : public A // derived class declaration.
{
int b;
public:
void display()
{
cout<<"Class B";
}
};
the prototype of display() function is the same in both the base and derived class. Therefore, the
static binding cannot be applied. It would be great if the appropriate function is selected at the run
time. This is known as run time polymorphism.

o Run time polymorphism: Run time polymorphism is achieved when the


object's method is invoked at the run time instead of compile time. It is
achieved by method overriding which is also known as dynamic binding or
late binding.

Types of overloading in C++ are:


Function overloading/Method overloading

Operator overloading
Method Overloading
Function Overloading is defined as the process of
having two or more function with the same name,
but different in parameters is known as function
overloading in C++. In function overloading, the
function is redefined by using either different types
of arguments or a different number of arguments. It
is only through these differences compiler can
differentiate between the functions.

//program of function overloading when number of arguments vary.

#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55

welcome bridget in becse enginnering


C++

Operator Overloading

Syntax of Operator Overloading

return_type class_name : : operator op(argument_list)


{
// body of the function.
}

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being


overloaded, and the operator is the keyword.

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
The Count is: 10

Method Overriding
If derived class defines same function as defined in
its base class, it is known as function overriding in
C++. It is used to achieve runtime polymorphism. It
enables you to provide specific implementation of
the function which is already provided by its base
class.

Function/Method Overriding Example


In this example, we are overriding the eat() function.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}
Output:

Eating bread...

Runtime Polymorphism Example


Let's see a simple example of run time
polymorphism in C++.

// an example without the virtual keyword.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main() {
Dog d = Dog();
d.eat();
return 0;
}
Output:

Eating bread...
Run time Polymorphism Example: By
using two derived class (an example with virtual
keyword.)

Let's see another example of run time polymorphism in C++


where we are having two derived classes.

// an example with virtual keyword.

#include <iostream>
using namespace std;
class Shape { // base class
public:
virtual void draw(){ // virtual function
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape // inheriting Shape class.

{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main() {
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=&cir;
s->draw();
}
drawing...
drawing rectangle...
drawing circle...

Pure Virtual Function


o A virtual function is not used for performing any task. It only serves as a placeholder.

o When the function has no definition, such function is known as "do-nothing" function.

o The "do-nothing" function is known as a pure virtual function. A pure virtual function is a
function declared in the base class that has no definition relative to the base class.

Pure virtual function can be defined as:

virtual void display() = 0;

#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}

Derived class is derived from the base class.

Exception Handling
Exception Handling in C++ is a process to handle runtime errors. We
perform exception handling so the normal flow of the application can
be maintained even after runtime errors.

In C++, exception is an event or object which is thrown at runtime. All


exceptions are derived from std::exception class. It is a runtime error
which can be handled. If we don't handle the exception, it prints
exception message and terminates the program.

Exception Handling Keywords


In C++, we use 3 keywords to perform exception handling:

Try
Catch

throw

The try statement allows you to define a block of code to be tested for errors while it is
being executed.

The throw keyword throws an exception when a problem is detected, which lets us create
a custom error.

The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.

try

{
// Block of code to try
throw exception; // Throw an exception when a problem
arise
}
catch () {
// Block of code to handle errors
}

o try

o catch, and

o throw

#include <iostream>
using namespace std;
float division(int x, int y)
{
if( y == 0 )
{
throw "Attempted to divide by zero!";
}
return (x/y);
}
int main () {
int i = 25;
int j = 0;
float k = 0;
try {
k = division(i, j);
cout << k << endl;
}
catch (const char* e) {
cerr << e << endl;
}
return 0;
}
Output:
Attempted to divide by zero!

#include <iostream>
using namespace std;

int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}

Multiple try and catch statements

#include <iostream>

using namespace std;

int main()

try {
try{

throw 20;

catch (int n) {

cout<< "Handle Partially ";

throw;//Re-throwing an exception

catch (int n) {

cout<< "Handle remaining ";

return 0;

Files and Streams


In C++ programming we are using the iostream standard library, it
provides cin and cout methods for reading from input and writing to
output respectively.File is a collection of records or collection od data.

To read and write from a file we are using the standard C++ library
called fstream. Let us see the data types define in fstream library is:
Data Type Description

fstream It is used to create files, write information to files, and read information from files.

ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.

Writing data to a file

#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream filestream("a.txt");
if (filestream.is_open())
{
filestream << "Welcome \n";
filestream << "C++ \n";
filestream.close();
}
else cout <<"File opening is fail.";
return 0;
}

reading from a file


#include <iostream>
#include <fstream>
using namespace std;
int main () {
string srg;
ifstream filestream("testout.txt");
if (filestream.is_open())
{
while ( getline (filestream,srg) )
{
cout << srg <<endl;
}
filestream.close();
}
else {
cout << "File opening is fail."<<endl;
}
return 0;
}

You might also like