C, Unit-1
C, Unit-1
Unit-1
Introduction to C++;
2. C++ has a large, active community of developers and users, and a wealth
of resources and tools available for learning and using the language.
Some of the key features of C++ include:
3. Object-Oriented Programming: C++ supports object-oriented
programming, allowing developers to create classes and objects and to
define methods and properties for these objects.
4. Templates: C++ templates allow developers to write generic code that
can work with any data type, making it easier to write reusable and
flexible code.
5. Standard Template Library (STL): The STL provides a wide range of
containers and algorithms for working with data, making it easier to
write efficient and effective code.
6. Exception Handling: C++ provides robust exception handling capabilities,
making it easier to write code that can handle errors and unexpected
situations.
Overall, C++ is a powerful and versatile programming language that is
widely used for a range of applications and is well-suited
well suited for both low-level
low
system programming and high level application development.
high-level
1.Hello World:
C++
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Output
Hello, World!
Advantages of C++:
Disadvantages of C++:
Class
The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds
its own data members and member functions, which can be
accessed and used by creating an instance of that class. A class is
like a blueprint for an object. For Example: Consider the Class of
Cars. There may be many cars with different names and brands but
all of them will share some common properties like all of them will
have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is
the class, and wheels, speed limits, and mileage are their properties.
A Class is a user-defined data type that has data members and
member functions.
Data members are the data variables and member functions are
the functions used to manipulate these variables together these
data members and member functions define the properties and
behavior of the objects in a Class.
In the above example of class Car, the data member will be
speed limit, mileage, etc and member functions can apply brakes,
increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group
of objects which shares some common properties and behaviors.
Object
An Object is an identifiable entity with some characteristics and
behavior. An Object is an instance of a Class. When a class is
defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
C++
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
{
Encapsulation in C++
Encapsulation also leads to data abstraction or data hiding. Using
encapsulation also hides the data. In the above example, the data of
any of the sections like sales, finance, or accounts are hidden from
any other section.
To know more about encapsulation, refer to this article –
Encapsulation in C++
Abstraction
Data abstraction is one of the most essential and important features
of object-oriented programming in C++. Abstraction means
displaying only essential information and hiding the details. Data
abstraction refers to providing only essential information about the
data to the outside world, hiding the background details or
implementation. Consider a real-life example of a man driving a car.
The man only knows that pressing the accelerator will increase the
speed of the car or applying brakes will stop the car but he does not
know how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car
or the implementation of an accelerator, brakes, etc. in the car. This
is what abstraction is.
Abstraction using Classes: We can implement Abstraction in
C++ using classes. The class helps us to group data members
and member functions using available access specifiers. A Class
can decide which data member will be visible to the outside world
and which is not.
Abstraction in Header files: One more type of abstraction in
C++ can be header files. For example, consider the pow() method
present in math.h header file. Whenever we need to calculate the
power of a number, we simply call the function pow() present in
the math.h header file and pass the numbers as arguments
without knowing the underlying algorithm according to which the
function is actually calculating the power of numbers.
To know more about C++ abstraction, refer to this article –
Abstraction in C++
Polymorphism
The word polymorphism means having many forms. In simple words,
we can define polymorphism as the ability of a message to be
displayed in more than one form. A person at the same time can
have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person possesses different
behavior in different situations. This is called polymorphism. An
operation may exhibit different behaviors in different instances. The
behavior depends upon the types of data used in the operation. C++
supports operator overloading and function overloading.
Operator Overloading: The process of making an operator
exhibit different behaviors in different instances is known as
operator overloading.
Function Overloading: Function overloading is using a single
function name to perform different types of tasks. Polymorphism
is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some
integers, sometimes there are 2 integers, and sometimes there are 3
integers. We can write the Addition Method with the same name
having different parameters, the concerned method will be called
according to parameters.
Polymorphism in C++
Inheritance in C++
class GFG {
public:
void call_Function() // function that call print
{
print();
}
void print() // the display function
{
cout << "Printing the Base class Content" << endl;
}
};
class GFG2 : public GFG // GFG2 inherit a publicly
{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content"
<< endl;
}
};
int main()
{
GFG geeksforgeeks; // Creating GFG's object
geeksforgeeks.call_Function(); // Calling call_Function
GFG2 geeksforgeeks2; // creating GFG2 object
geeksforgeeks2.call_Function(); // calling call_Function
// for GFG2 object
return 0;
}
Output
Printing the Base class Content
Printing the Base class Content
As we can see, the print() function of the parent class is called even
from the derived class object. To resolve this we use virtual
functions.
Above Example with virtual Function:
C++
#include<bits/stdc++.h>
using namespace std;
class GFG {
public:
void call_Function() // function that call print
{
print();
}
virtual void print() // using "virtual" for the display function
{
cout << "Printing the Base class Content" << endl;
}
};
class GFG2 : public GFG // GFG2 inherit a publicly
{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content"
<< endl;
}
};
int main()
{
GFG geeksforgeeks; // Creating GFG's object
geeksforgeeks.call_Function(); // Calling call_Function
GFG2 geeksforgeeks2; // creating GFG2 object
geeksforgeeks2.call_Function(); // calling call_Function
// for GFG2 object
return 0;
}
Output
Printing the Base class Content
Printing the Derived class Content
Message Passing
Objects communicate with one another by sending and receiving
information. A message for an object is a request for the execution
of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function, and the
information to be sent.
Example:
C++
#include <iostream>
using namespace std;
int main() {
// Create a Car object named myCar
Car myCar;
return 0;
}
Oops advantages ;
OOP stands for Object-Oriented Programming. As you can guess
from it’s name it breaks the program on the basis of the objects in it.
It mainly works on Class, Object, Polymorphism, Abstraction,
Encapsulation and Inheritance. Its aim is to bind together the data
and functions to operate on them.
Some of the well-known object-oriented languages are Objective C,
Perl, Java, Python, Modula, Ada, Simula, C++, Smalltalk and some
Common Lisp Object Standard. Here we are discussing its benefits
on C++.
Benefits of OOP
We can build the programs from standard working modules that
communicate with one another, rather than having to start writing
the code from scratch which leads to saving of development time
and higher productivity,
OOP language allows to break the program into the bit-sized
problems that can be solved easily (one object at a time).
The new technology promises greater programmer productivity,
better quality of software and lesser maintenance cost.
OOP systems can be easily upgraded from small to large
systems.
It is possible that multiple instances of objects co-exist without
any interference,
It is very easy to partition the work in a project based on objects.
It is possible to map the objects in problem domain to those in the
program.
The principle of data hiding helps the programmer to build secure
programs which cannot be invaded by the code in other parts of
the program.
By using inheritance, we can eliminate redundant code and
extend the use of existing classes.
Message passing techniques is used for communication between
objects which makes the interface descriptions with external
systems much simpler.
The data-centered design approach enables us to capture more
details of model in an implementable form.
While it is possible to incorporate all these features in an OOP, their
importance depends upon the type of project and preference of the
programmer. These technology is still developing and current
products may be superseded quickly.
Developing a software is easy to use makes it hard to build.
Disadvantages of OOP
The length of the programmes developed using OOP language is
much larger than the procedural approach. Since the programme
becomes larger in size, it requires more time to be executed that
leads to slower execution of the programme.
We can not apply OOP everywhere as it is not a universal
language. It is applied only when it is required. It is not suitable
for all types of problems.
Programmers need to have brilliant designing skill and
programming skill along with proper planning because using OOP
is little bit tricky.
OOPs take time to get used to it. The thought process involved in
object-oriented programming may not be natural for some people.
Everything is treated as object in OOP so before applying it we
need to have excellent thinking in terms of objects.
C++ comes with libraries that provide us with many ways for
performing input and output. In C++ input and output are performed
in the form of a sequence of bytes or more commonly known
as streams.
Input Stream: If the direction of flow of bytes is from the
device(for example, Keyboard) to the main memory then this
process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e.
from main memory to device( display screen ) then this process is
called output.
int main()
{
char sample[] = "GeeksforGeeks";
cout << sample << " - A computer science portal for geeks";
return 0;
}
Output:
GeeksforGeeks - A computer science portal for geeks
In the above program, the insertion operator(<<) inserts the value of
the string variable sample followed by the string “A computer
science portal for geeks” in the standard output stream cout which is
then displayed on the screen.
standard input stream (cin): Usually the input device in a
computer is the keyboard. C++ cin statement is the instance of
the class istream and is used to read input from the standard
input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for
reading inputs. The extraction operator extracts the data from the
object cin which is entered using the keyboard.
C++
#include <iostream>
using namespace std;
int main()
{
int age;
return 0;
}
Input :
18
Output:
Enter your age:
Your age is: 18
The above program asks the user to input the age. The object cin is
connected to the input device. The age entered by the user is
extracted from cin using the extraction operator(>>) and the
extracted data is then stored in the variable age present on the right
side of the extraction operator.
Un-buffered standard error stream (cerr): The C++ cerr is the
standard error stream that is used to output the errors. This is
also an instance of the iostream class. As cerr in C++ is un-
buffered so it is used when one needs to display the error
message immediately. It does not have any buffer to store the
error message and display it later.
The main difference between cerr and cout comes when you
would like to redirect output using “cout” that gets redirected to
file if you use “cerr” the error doesn’t get stored in file.(This is
what un-buffered means ..It cant store the message)
C++
#include <iostream>
int main()
{
cerr << "An error occurred";
return 0;
}
Output:
An error occurred
int main()
{
clog << "An error occurred";
return 0;
}
Output:
An error occurred
Control structures in C++ are constructs that allow you to control the flow of
execution within a program. They determine the order in which statements are
executed based on certain conditions or criteria. Control structures enable you
to make decisions, iterate over a set of instructions, and perform different
actions based on specific conditions.
Selection Structures
Selection structures in C++ allow you to make decisions based on certain
conditions. They help in choosing a particular path or branch of execution
based on the evaluation of an expression or variable.
1. if statement
if (condition) {
2. if-else statement
if (condition) {
} else {
Nested if-else statements are multiple if-else statements nested within each
other. They allow you to perform more complex decision-making by checking
multiple conditions.
if (condition1) {
if (condition2) {
} else {
} else {
Iteration Structures
Iteration structures, also known as loop structures, allow you to repeatedly
execute a block of code as long as a specified condition is true. They are
useful when you need to perform repetitive tasks or iterate over a collection of
items.
1. while loop
while (condition) {
// Code to be executed
2. do-while loop
The do-while loop is similar to the while loop but with a crucial difference:
it executes the code block at least once before checking the condition.
do {
// Code to be executed
} while (condition);
3. for loop
The for loop provides a compact and structured way to iterate over a range
of values. It consists of three parts: initialization, condition, and
increment/decrement.
// Code to be executed
The range-based for loop is a C++11 feature that simplifies iterating over
elements of a container or a range of values.
Jump Structures
Jump structures in C++ allow you to transfer control from one part of the
program to another. They alter the normal sequential flow of execution.
1. break statement
while (condition) {
if (some_condition) {
// Code to be executed
}
2. continue statement
if (i % 2 == 0) {
3. return statement
int square(int x) {
return x * x;
1. try-catch block
The try-catch block is used to catch and handle exceptions. It consists of a try
block where you place the code that might throw an exception, and one or
more catch blocks that handle specific types of exceptions.
try {
} catch (...) {
In the above code, the try block contains the code that could potentially throw
an exception. If an exception is thrown, the catch blocks are evaluated
sequentially to find a matching exception type. The first matching catch block
is executed, and the program flow continues from there.
Conclusion
Control structures in C++ provide the mechanisms to control the flow of
execution, make decisions, repeat tasks, transfer control, and handle errors.
Understanding and effectively using these control structures is crucial for
writing robust and flexible programs.
By combining and nesting these control structures, you can create complex
program flows and solve a wide range of programming problems. It’s
important to choose the appropriate control structure for each situation and
understand their syntax and usage.
Take the time to experiment with control structures in C++ and explore their
capabilities. Practice using them in different scenarios to become comfortable
with their usage and leverage their power to write efficient and robust code.
Remember that good programming practices involve writing code that is clear,
concise, and maintainable. Use meaningful variable names, provide proper
indentation, and include comments to enhance the readability of your code.
// than 18 or not
#include <iostream>
int main()
return 0;
}
Output
allowed to vote
2. if-else in C++
The if-else decision-making statement allows us to make a decision
based on the evaluation of a given condition. If the given condition
evaluates to true then the code inside the ‘if’ block is executed and in
case the condition is false, the code inside the ‘else’ block is
executed.
Syntax of if-else in C++
if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}
Flowchart of if-else in C++
Example of if-else in C
The below example demonstrates the use of an if-else statement to
find if the given number is positive or nonpositive.
C++
// non positive
#include <iostream>
int main()
int num = 5;
// or non positive
if (num > 0) {
else {
return 0;
}
Output
number is positive.
Example of if-else-ladder
ladder in C++
The below example demonstrates the use of an if-else else-if ladder. In
the program, you are given an age and if the age is less the 13 print
child, if the age is between 13 to 18 print the growing stage, else
print adult.
C++
int main()
// growing age
else {
return 0;
Output
Growing stage
// odd
#include <iostream>
int main()
if (number > 0) {
// to check if the positive number is
even or odd
if (number % 2 == 0) {
else {
else if (number == 0) {
else {
return 0;
Output
positive and even number
#include <iostream>
int main()
switch (input) {
case 'A':
cout << "GFG" << endl;
break;
case 'B':
break;
default:
// invalid input
return 0;
Output
GeeksforGeeks
#include <iostream>
int main()
int max;
Output
40
// i become 3
#include <iostream>
int main()
if (i == 3) {
break;
}
cout << i << endl;
// next statements
return 0;
Output
0
1
2
B) continue
The continue statement is used to skip the loop body for the current
iteration and continue from the next iteration. Unlike the break
statement which terminates the loop completely, continue allows us
just to skip one iteration and continue with the next iteration.
Syntax
continue;
Flowchart of continue
Flow diagram of continue
Example
The below example demonstrates the use of continue to manage the
control flow.
C++
int main()
if (i == 3) {
continue;
return 0;
Output
0
1
2
4
C) goto
It is a jump statement that is used to transfer the control to another
part of the program. It transfers the control unconditionally to the
labeled statement.
Syntax
goto label;
// ...
label:
// Statement or block of code
Flowchart of goto
Flow Diagram of goto
Example
The below example demonstrates the use of the goto statement.
C++
#include <iostream>
int main()
goto Noteligible;
else {
Noteligible:
Output
You are not eligible to vote!
Example
The below example demonstrates the use of a return statement to
return a value from a function.
C++
// calculated by a function
#include <iostream>
int sum = a + b;
}
int main()
cout << "The sum is: " << res << endl;
return 0;
Output
The sum is: 8
Conclusion
Decision-making is an essential factor of programming in C++,
presenting flexibility and management over program execution.
When used correctly, it enhances application performance and
adaptability. However, overuse or mismanagement of decision-
making statements can lead to code complexity, decreased clarity,
and protection challenges. Striking a balance and using those
statements properly is essential to enhance your code.
Loops in c++;
In computer programming, loops are used to repeat a block of code.
For example, let's say we want to show a message 100 times. Then
instead of writing the print statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency
and sophistication in our programs by making effective use of loops.
for loop
while loop
do...while loop
This tutorial focuses on C++ for loop. We will learn about the other
type of loops in the upcoming tutorials.
Here,
int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Run Code
Output
1 2 3 4 5
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
Run Code
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
#include <iostream>
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
return 0;
}
Run Code
Output
The sum variable is assigned with 0 and the num variable is assigned
with the value provided by the user.
Note that we have used a for loop.
Here,
1 + 2 + ... + 10 .
Ranged Based for Loop
In C++11, a new range-based for loop was introduced to work with
collections such as arrays and vectors. Its syntax is:
Here, for every value in the collection , the for loop is executed and the
value is assigned to the variable .
int main() {
return 0;
}
Run Code
Output
1 2 3 4 5 6 7 8 9 10
In the above program, the condition is always true which will then run
the code for infinite times.
The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
while loop
1 Repeats a statement or group of statements while a given condition is true. It tests the condition
before executing the loop body.
for loop
2 Execute a sequence of statements multiple times and abbreviates the code that manages the loop
variable.
do...while loop
3
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
nested loops
4
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
C++ Functions
A function is a block of code that performs a specific task.
When the function is invoked from any part of the program, it all
executes the codes defined in the body of the function.
// function declaration
void greet() {
cout << "Hello World";
}
Here,
Calling a Function
In the above program, we have declared a function named greet() . To
use the greet() function, we need to call it.
Here's how we can call the above greet() function.
int main() {
// calling a function
greet();
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
return 0;
}
Run Code
Output
Hello there!
Function Parameters
As mentioned above, a function can be declared with parameters
(arguments). A parameter is a value that is passed when declaring a
function.
For example, let us consider the function below:
int main() {
int n = 7;
return 0;
}
#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main() {
int num1 = 5;
double num2 = 5.5;
;
return 0;
}
Run Code
Output
C++ function
with parameters
Note: The type of the arguments passed while calling the function
must match with the corresponding parameters defined in the function
declaration.
Return Statement
In the above programs, we have used void in the function declaration.
For example,
void displayNumber() {
// code
}
It's also possible to return a value from a function. For this, we need to
specify the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a
function.
For example,
#include <iostream>
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
return 0;
}
Run Code
Output
100 + 78 = 178
In the above program, the add() function is used to find the sum of two
numbers.
We pass two int literals 100 and 78 while calling the function.
We store the returned value of the function in the variable sum , and
then we print it.
Working of
C++ Function with return statement
Notice that sum is a variable of int type. This is because the return
value of add() is of int type.
Function Prototype
In C++, the code of function declaration should be before the function
call. However, if we want to define a function after the function call, we
need to use the function prototype. For example,
// function prototype
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}
// function definition
void add(int a, int b) {
cout << (a + b);
}
This provides the compiler with information about the function name
and its parameters. That's why we can use the code to call a function
before the function has been defined.
#include <iostream>
// function prototype
int add(int, int);
int main() {
int sum;
return 0;
}
// function definition
int add(int a, int b) {
return (a + b);
}
Run Code
Output
100 + 78 = 178
The above program is nearly identical to Example 3. The only
difference is that here, the function is defined after the function call.
That's why we have used a function prototype in this example.
Functions make the program easier as each small task is divided into
a function.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header
file in which these library functions are defined.
int main() {
double number, squareRoot;
number = 25.0;
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Run Code
Output
Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the
square root of a number.
The function declaration of sqrt() is defined in the cmath header file.
That's why we need to use the code #include <cmath> to use
the sqrt() function.
When the program executes the function call instruction the CPU
stores the memory address of the instruction following the function
call, copies the arguments of the function on the stack, and finally
transfers control to the specified function. The CPU then executes
the function code, stores the function return value in a predefined
memory location/register, and returns control to the calling function.
This can become overhead if the execution time of the function is
less than the switching time from the caller function to called function
(callee).
For functions that are large and/or perform complex tasks, the
overhead of the function call is usually insignificant compared to the
amount of time the function takes to run. However, for small,
commonly-used functions, the time needed to make the function call
is often a lot more than the time needed to actually execute the
function’s code. This overhead occurs for small functions because
the execution time of a small function is less than the switching time.
int main()
return 0;
Output
The cube of 3 is: 27
Example:
C++
#include <iostream>
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
cin >> a;
cin >> b;
}
add = a + b;
sub = a - b;
mul = a * b;
cout << "Product of two numbers: " << a * b
<< "\n";
div = a / b;
int main()
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
Output:
Enter first value: 45
Enter second value: 15
Addition of two numbers: 60
Difference of two numbers: 30
Product of two numbers: 675
Division of two numbers: 3
#include <iostream>
int m;
public:
// error
#define MAC(S::m)
};
Output:
Error: "::" may not appear in macro parameter list
#define MAC(S::m)
The parameters should follow any one or more than one of the
following conditions for Function overloading:
Parameters should have a different type
add(int a, int b)
add(double a, double b)
Below is the implementation of the above discussion:
C++
#include <iostream>
using namespace std;
// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
Output
sum = 12
sum = 11.5
#include <iostream>
using namespace std;
// Driver code
int main()
{
add(10, 2);
add(5, 6, 4);
return 0;
}
Output
sum = 12
sum = 15
#include<iostream>
using namespace std;
// Driver code
int main()
{
add(10,2.5);
add(5.5,6);
return 0;
}
Output
sum = 12.5
sum = 11.5
#include <iostream>
using namespace std;
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output
Here is int 10
Here is float 10.1
Here is char* ten
C++
#include<iostream>
using namespace std;
main()
{
add(10,2);
add(5,6,4);
return 0;
}
C++
#include<iostream>
using namespace std;
main()
{
add(10,2.5);
add(5.5,6);
return 0;
}
How does Function Overloading work?
Exact match:- (Function name and Parameter)
If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
If no match is found:
->C++ tries to find a match through the standard
conversion.
ELSE ERROR
Note: In C++, function overloading is primarily based on the function
name and the types or number of its parameters. The return type
alone does not distinguish overloaded functions. Therefore,
changing only the return type of a function without changing its
parameters does not create an overload and may lead to a
compilation error due to ambiguity.