Data Structure using C++
BCAMJ23402
Unit 1 [C++ Programming Basics]
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. C++ is an object-
oriented programming language, so it is safer and well-structured programming language than
C.
C++ history
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.
It was developed for adding a feature of OOP (Object Oriented
Programming) in C without significantly changing the C component.
C++ programming is "relative" (called a superset) of C, it means any
valid C program is also a valid C++ program.
First Program
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++ Programming.";
return 0;
}
Explanation:
1. #include <iostream>
o This is a preprocessor directive that includes the iostream (input-output
stream) library.
o This library is needed for using cout and cin for printing output and taking
input.
2. using namespace std;
o This allows us to use the std namespace, which contains standard C++
functions like cout, cin, etc.
o Without this line, we would need to write std::cout instead of just cout.
3. int main() {
o This defines the main function of the program.
1
o Execution of the program starts from the main() function.
4. cout << "Welcome to C++ Programming.";
o cout (Console Output) is used to display text on the screen.
o The << operator is used to send output to the console.
o "Welcome to C++ Programming." is a string message that gets printed.
5. return 0;
o The return statement indicates that the program has successfully executed.
o 0 is a standard return value that tells the operating system the program ended
without errors.
6. }
o This closes the main() function.
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:
2
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 character 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
1. A variable can have alphabets, digits and underscore.
2. A variable name can start with alphabet and underscore only. It can't start with digit.
3. No white space is allowed within variable name.
4. 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;
3
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 255
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 65535
4
int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 65535
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 65535
long int 4 byte -2,147,483,648 to 2,147,483,647
signed long int 4 byte same as long int
unsigned long int 4 byte 0 to 4,294,967,295
float 4 byte 3.4E-38 to 3.4E+38
double 8 byte 1.7E-308 to 1.7E+308
long double 10 byte 3.4E-4932 to 3.4E+4932
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.
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:
5
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 behaviours 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 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.
6
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
By creating functions in C++, you can call it many times. So we don't need to write the same
code again and again.
2) Code optimization
It makes the code optimized, we don't need to write much code. Suppose, you have to check
3 numbers (531, 883 and 781) whether it is prime number or not. Without using function, you
need to write the prime number logic 3 times. So, there is repetition of code.
But if you use functions, you need to write the logic only once and you can reuse it several
times.
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:
1. return_type function_name(data_type parameter...)
2. {
3. //code to be executed
4. }
7
C++ Function Example
Let's see the simple example of C++ function.
1. #include <iostream>
2. using namespace std;
3. void func() {
4. static int i=0; //static variable
5. int j=0; //local variable
6. i++;
7. j++;
8. cout<<"i=" << i<<" and j=" <<j<<endl;
9. }
10. int main()
11. {
12. func();
13. func();
14. func();
15. }
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
Call by value in C++
In call by value, original value is not modified. In call by value, value being passed to the
function is locally stored by the function parameter in stack memory location. If you change
the value of function parameter, it is changed for the current function only. It will not change
the value of variable inside the caller method such as main().
Let's try to understand the concept of call by value in C++ language by the example
given below:
1. #include <iostream>
2. using namespace std;
3. void change(int data);
4. int main()
5. {
6. int data = 3;
7. change(data);
8. cout << "Value of the data is: " << data<< endl;
9. return 0;
10. }
11. void change(int data)
12. {
13. data = 5;
14. }
Output:
Value of the data is: 3
Call by reference in C++
8
Reference is nothing but alias to an existing variable. When you declare a reference, you
create a new name for existing variable and any change done in reference is treated as it is
the original variable. 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;
}
Output:
Value of x is: 100
Value of y is: 500
Call by address in C++
Call By Address is also referred to as Call By Pointers. In this Call By Address method, the
developer passes the actual arguments addresses to the formal parameters. After that, the
function utilizes these addresses to access the actual arguments in the system. In other words,
the function arguments are passed as address when utilizing the Call by address/Pass by
address technique. The calling function passes the address of the parameters. There are pointer
variables utilized in the definition of the function. The function can access and modify the
actual parameters with the aid of the Call by address mechanism.
Example for Call by address:
Let's take an example to illustrate the Call by Address in C++.
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
9
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
Value of x is: 100
Value of y is: 500
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++. 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.
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.
// program of function overloading when number of arguments vary.
1. #include <iostream>
2. using namespace std;
3. class Cal {
4. public:
5. int add(int a,int b){
6. return a + b;
7. }
8. int add(int a, int b, int c)
9. {
10. return a + b + c;
11. }
12. };
13. int main(void) {
14. Cal C; // class object declaration.
15. cout<<C.add(10, 20)<<endl;
16. cout<<C.add(12, 20, 23);
17. return 0;
18. }
Output:
30
55
Let's see the simple example when the type of the arguments vary.
10
// Program of function overloading with different types of arguments.
1. #include<iostream>
2. using namespace std;
3. int mul(int,int);
4. float mul(float,int);
5. int mul(int a,int b)
6. {
7. return a*b;
8. }
9. float mul(double x, int y)
10. {
11. return x*y;
12. }
13. int main()
14. {
15. int r1 = mul(6,7);
16. float r2 = mul(0.2,3);
17. cout << "r1 is : " <<r1<< endl;
18. cout <<"r2 is : " <<r2<< endl;
19. return 0;
20. }
Output:
r1 is : 42
r2 is : 0.6
C++ inline function
C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the function
is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled
because compiler would need to replace all the code once again otherwise it will continue with
old functionality.
To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline qualifier
in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use
of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers −
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
11
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result –
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
C++ Enumeration
Enum in C++ is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST)
etc. The C++ enum constants are static and final implicitly.
C++ Enums can be thought of as classes that have fixed set of constants.
Points to remember for C++ Enum
o enum improves type safety
o enum can be easily used in switch
o enum can be traversed
o enum can have fields, constructors and methods
o enum may implement many interfaces but cannot extend any class because it
internally extends Enum class
C++ Enumeration Example
Let's see the simple example of enum data type used in C++ program.
1. #include <iostream>
2. using namespace std;
3. enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
4. int main()
5. {
6. week day;
7. day = Friday;
8. cout << "Day: " << day+1<<endl;
9. return 0;
10. }
Output:
Day: 5
Source
1. C++ Programming Language - GeeksforGeeks
2. C++ Tutorial | Learn C++
3. C++ Tutorial | Learn C++ Programming for Beginners - Tpoint Tech
12