OOP - C++ Programming Basics-1
OOP - C++ Programming Basics-1
Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission
Lecture Note
3 Credit Mr. Rajat Behera - Associate Professor
Course Contents
2
Let us look at a simple code that would print the words Hello World.
The C++ language defines
#include <iostream> several headers, which contain
information that is either
using namespace std;
necessary or useful to the
program. For this program, the
// main() is where program header <iostream> is needed.
//execution begins.
The line using namespace std tells
int main() {
the compiler to use the std
// prints Hello World namespace. Namespaces are a
cout << "Hello World"; relatively recent addition to C++
return 0; The line int main() is the main
} function where program execution
cout << " Hello World " causes
begins.
Terminates the the message " Hello World " to be
program displayed on the screen.
main method
Compilation Run
g++ filename.cpp ./a.out
E.g. g++ hello.cpp
Compilation and Execution Process
Source Object
Compiler
Files Files
Library
Files
Executable
Linker
Files
Source Files – Contains source code of the program whose extension is .cpp
and contains main and other functions.
Header Files – Make the subroutines and store them in header file.
Object Files – Generated by compiler after processing the source code file. It
contain a compact binary code of the function definition. The linker uses
this object file to produce an executable file by combining the object files
together. Generally, it have .obj extension
Binary Executable Files – Generated by Linker. The linker links the various
object files to produce a binary file that can be directly executed.
In C++, input and output (I/O) operators are used to take input and
display output. The operator used for taking the input is known as
the extraction or get from operator (>>), while the operator used
for displaying the output is known as the insertion or put to
operator (<<).
Input Operator - The input operator, commonly known as the
extraction operator (>>), is used with the standard input stream,
cin. cin treats data as a stream of characters. These characters flow
from cin to the program through the input operator. The input
operator works on two operands, namely, the c in stream on its left
and a variable on its right. Thus, the input operator takes
(extracts) the value through cin and stores it in the variable.
#include<iostream>
using namespace std;
int main ()
{
int a;
cin>>a;
a = a+1;
return 0;
}
In this example, the statement cin>> a takes an input from the user and stores it
in the variable a.
The output operator, commonly known as the insertion operator (<<), is used.
The standard output stream cout Like cin, also treats data as a stream of
characters. These characters flow from the program to cout through the output
operator. The output operator works on two operands, namely, the cout stream
on its left and the expression to be displayed on its right. The output operator
directs (inserts) the value to cout. A program to demonstrate the working of an
output operator.
#include<iostream>
using namespace std;
int main ()
{
int a;
cin>>a;
a=a+1;
cout<<a;
return 0;
} School of Computer Engineering
Cascading of Input/Output Operators
10
The cascading of the input and output operators refers to the consecutive
occurrence of input or output operators in a single statement. A program with
cascading of the input/output operator is as follows
#include<iostream>
using namespace std;
int main ()
{
int a, b;
cin>>a>>b;
cout<<"The value of b is : "<<b;
cout<<“\nThe value of a is : "<<a;
return 0;
}
Comments are portions of the code ignored by the compiler which allow the user
to make simple notes in the relevant areas of the source code. Comments come
either in block form or as single lines. C++ supports two types of commenting –
Single-line comments (informally, C++ style), start with // and continue until
the end of the line. If the last character in a comment line is a \ the comment
will continue in the next line.
Multi-line comments (informally, C style), start with /* and end with */.
Example:
/* This is a single line comment */
/*
This is a multiple line comment
*/
Keywords are the words that convey a special meaning to the language compiler.
These are the reserved words for special purpose and must not be used as
normal identifier names.
Constants are the data items that never change their value during a program run.
Following is an example program of C++ constants :
#include<iostream>
using namespace std;
int main()
{
const int num=10;
cout<<"The constant integer value is "<<num;
return 0;
}
A variable provides us with named storage that our programs can manipulate.
Each variable in C++ has a specific type, which determines the size and layout of
the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C++ is case-sensitive
Sr# Type Description
1 bool Stores either value true or false.
2 char Typically a single octet (one byte).
3 int The most natural size of integer for the machine.
4 float A single-precision floating point value.
5 double A double-precision floating point value.
6 void Represents the absence of type.
A variable definition tells the compiler where and how much storage to create for
the variable. A variable definition specifies a data type, and contains a list of one
or more variables of that type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, int, float, double, bool or
any user-defined object, etc., and variable_list may consist of one or more
identifier names separated by commas.
int i, j, k;
char c, ch;
float f, salary;
double d;
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
C++ Expression - An expression is a sequence of operators and their operands,
that specifies a computation.
Decision making structures (branching) require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or statements
to be executed if the condition is determined to be true, and optionally, other statements
to be executed if the condition is determined to be false. Following is the general form of a
typical decision making structure found in most of the programming languages −
Sr# Statement Description
There may be a situation, when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. Programming languages provide various
control structures that allow for more complicated execution paths. A loop statement
allows us to execute a statement or group of statements multiple times and following is
the general from of a loop statement in most of the programming languages −
Sr# Loop Type Description
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed. C++ supports the following control statements.
C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of
the same type.
Array Initialization
Compile Time: Run Time:
So far we have explored arrays with only one dimension. It is also possible for arrays to
have two or more dimensions. The two dimensional array is also called a matrix.
Array Declaration Array Representation & Memory Map
When declaring 2-D arrays, specify - int a[4][3];
Name Column 0 Column 1 Column 2
Type of array Row 0 a[0][0] a[0][1] a[0][2]
Number of elements Row 1 a[1][0] a[1][1] a[1][2]
Examples - int c[10][10]; Row 2 a[2][0] a[2][1] a[2][2]
Row 3 a[3][0] a[3][1] a[3][2]
float myArray[3284][100];
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2]
NOTE - number of elements are declared twice. First one for row
and other for column 1000 1002 1004 1006 1008 1010 1012 1014 1016 1018 1020 1022
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ; int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
Below is a sample program that stores roll number and marks obtained by a student.
int main( )
{
int stud[4][2] ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
cout<<"\n Enter roll no. and marks of student “<< i+1 << “:” ) ;
cin>>stud[i][0]>>[i][1] ;
}
for ( i = 0 ; i <= 3 ; i++ )
{
cout<<“\nRoll No:”<< stud[i][0]<<“, Mark:“ << stud[i][1] ;
}
return 0;
}
We aren’t going to show a programming example that uses a three dimensional array.
This is because, in practice, one rarely uses this array. However, an example of
initializing a three-dimensional array will consolidate your understanding of subscripts:
int arr[3][3][3] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31,
32, 33, 34, 35, 36, 37, 38, 39};
Conceptual View
Memory Map
The C-style character string originated The standard C++ library provides a
within the C language and continues to string class type that supports all the
be supported within C++. This string is operations mentioned above,
actually a one-dimensional array of additionally much more functionality.
characters which is terminated by a #include <string> is the header to
null character '\0'. Thus a null- include in the program.
terminated string contains the Example –
characters that comprise the string string str1 = "Hello";
followed by a null. string str2 = "World";
Example – string str3 = str1 + str2;
char greeting[] = "Hello";
School of Computer Engineering
String - Commonly Used Function – C Style
33
2 empty() Returns whether a string is empty or not. It returns 1 if the string length
is 0 and 0 if not.
3 resize() Resizes our string to a specified length.
4 clear() Clears the content of strings.
5 at() Returns the character at some specified position in a string
6 compare() Compares the value of a string str1 with another string str2.
It returns 0 if both the strings are equal.
It returns a positive value if either str1 > str2
It returns a negative value if either str1 < str2
7 find() finds the position of the first occurrence of a character or string in a
string.
8 substr() returns a substring from a string by specifying its position.
cout << "\n Enter another string: " <<flush; str = “I love C++”;
cin >> str; str.clear();
cout << "You entered: "<<str<<endl; cout << str<<endl;
return 0; return 0;
} }
string copy, concatenation and at() compare(), find(), substr() and multiword input
#include <iostream> #include <iostream>
#include <string> #include <string>
using namespace std; using namespace std;
int main() int main()
{ {
string str1 = "Hello"; string str1 = “have apple";
string str2 = "World"; string str2 = “have orange";
string str3;
int len ; cout << str1.compare(str2)<< endl;
cout << str1.find(‘a’)<< endl;
// copy str1 into str3 cout << str2.find(“have”)<< endl;
str3 = str1; cout << str1.substr(3)<< endl;
cout << "str3 : " << str3 << endl; cout << str2.substr(3, 5)<< endl;
// concatenates str1 and str2 string name;
str3 = str1 + str2; getline(cin, name);
cout << "str1 + str2 : " << str3 << endl; cout << name << endl;
cout << str3.at(5)<< endl; return 0;
return 0; }
}
int main () {
std::cout << std::setw(10);
std::cout << 77 << std::endl;
std:: cout << "Hello" << setw(7) << "World" ;
return 0;
}
Output:
Hello<space><space>World
Type Conversion is that which converts from one data type into another. For example
converting a int into float or converting a float into double. The Type Conversion is that
which automatically converts one data type into another. We can store a large data type
into the other. For example we can't store a float into int because a float is greater than int.
Different situations of data conversion between incompatible types:-
Conversion from basic type to class type.
Conversion from class type to basic type.
Conversion from one class type to another class type
C++ uses very strict type checking. A prototype must be known for each function
which is called, and the call must match the prototype. The program
int main()
{
printf("Hello World\n");
return (0);
}
does often compile under C, though with a warning that printf() is not a known
function.
Many C++ compilers will fail to produce code in such a situation. The error is of
course the missing #include<stdio.h> directive.
Consider a situation, when we have two persons with the same name, Zara, in
the same group. Whenever we need to differentiate them definitely we would
have to use some additional information along with their name, like either
the area, if they live in different area or their mother’s or father’s name, etc.
Same situation can arise in C++ applications. For example, you might be
writing some code that has a function called xyz() and there is another
library available which is also having same function xyz(). Now the compiler
has no way of knowing which version of xyz() function you are referring to
within your code.
A namespace is designed to overcome this difficulty and is used as additional
information to differentiate similar functions, classes, variables etc. with the
same name available in different libraries. Using namespace, you can define
the context in which names are defined. In essence, a namespace defines a
scope.
Defining a Namespace
namespace namespace_name {
// code declarations
}
#include <iostream>
using namespace std; int main () {
// Calls function from first name space.
// first name space first_space::func();
namespace first_space {
void func() { // Calls function from second name space.
cout << "Inside first_space" << endl; second_space::func();
}
} return 0;
}
// second name space One can also avoid prepending of namespaces with
namespace second_space { the using namespace directive. This directive tells
void func() { the compiler that the subsequent code is making
cout << "Inside second_space" << endl; use of names in the specified namespace.
} using namespace first_space;
} int main () {.
func(); // calls function from first name space
return 0;
}
Namespaces can be nested where you can define one namespace inside another name
space as follows −
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
Members of nested namespace can be accessed by using resolution operators as follows
#include <iostream>
using namespace std; using namespace first_space::second_space;
int main () {
// first name space // This calls function from second name space.
namespace first_space { func();
void func() {
cout << "Inside first_space" << endl; return 0;
} }
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Life Time – Life time of any variable is the time for which the particular variable
outlives in memory during running of the program.
Scope – The scope of any variable is actually a subset of life time. A variable may
be in the memory but may not be accessible though. So, the area of our program
where we can actually access our entity (variable in this case) is the scope of that
variable. The scope of any variable can be broadly categorized into three
categories :
1. Global scope : When variable is defined outside all functions. It is then
available to all the functions of the program and all the blocks program
contains.
2. Local scope : When variable is defined inside a function or a block, then it is
locally accessible within the block and hence it is a local variable.
3. Function scope : When variable is passed as formal arguments, it is said to
have function scope.
Because
Ordinary variable is a variable which can hold a value as like eg. int, float or
char. It may be signed or unsigned and take different memory space as per
as their data type.
The pointer variable is a variable which hold the address of a another
variable and it is obviously unsigned.
When a variable is declared as reference, it becomes an alternative name
for an existing variable. A variable can be declared as reference by putting
‘&’ in the declaration.
int n=10, *p;
p=&n;
int& ref = n;
Here p is a pointer variable and n is a ordinary variable. p stores the
address of n where as n stores an integer value. ref is the reference variable
and is reference to n.
School of Computer Engineering
Function
53
Sometimes, you may come across a situation, when you want to have a function, which
can take variable number of arguments, i.e., parameters, instead of predefined number of
parameters. The C programming language provides a solution for this situation and you
are allowed to define a function which can accept variable number of parameters based
on your requirement. The following example shows the definition of such a function.
int main()
{
func(1, 2, 3);
func(1, 2, 3, 4);
}
School of Computer Engineering
Variable Arguments cont…
60
It should be noted that the function func() has its last argument as ellipses, i.e. three
dotes (...) and the one just before the ellipses is always an int which will represent the
total number variable arguments passed. To use such functionality, you need to make use
of stdarg.h header file which provides the functions and macros to implement the
functionality of variable arguments and follow the given steps −
Define a function with its last parameter as ellipses and the one just before the
ellipses is always an int which will represent the number of arguments.
Create a va_list type variable in the function definition. This type is defined in
stdarg.h header file. va_list stores the list of arguments.
Use int parameter and va_start macro to initialize the va_list variable to an argument
list. The macro va_start is defined in stdarg.h header file.
Use va_arg macro and va_list variable to access each item in argument list.
No Modified Yes
Multiple functions with same names but different parameters are said to be overloaded.
Function overloading allows to use the same name for different functions, to perform,
either same or different functions.
Function overloading is usually used to enhance the readability of the program. If you
have to perform one single operation but with different number or types of arguments,
then you can simply overload the function.
Ways to overload a function
1. By changing number of Arguments. 2. By having different types of argument.
1. Number of Arguments are different
In this type of function overloading we define functions with same names but different
number of parameters of the same type.
int sum (int x, int y) int sum (int x, int y, int z) int main()
{ { {
sum(10, 20);
cout << x+y; cout << x+y + z;
sum(10,20,30);
} } return 0;
}
School of Computer Engineering
Function Overloading cont…
69
Provides the compiler with the description of functions that will be used
later in the program
1. WAP (Write a program) to print out all Armstrong numbers between 1 and
500. If sum of cubes of each digit of the number is equal to the number itself,
then the number is called an Armstrong number. For example, 153 = ( 1 * 1 *
1)+(5*5*5)+(3*3*3)
2. WAP to find the norm of a matrix. The norm is defined as the square root of
the sum of squares of all elements in the matrix.
3. WAP to sort a set of names stored in an array in alphabetical order.
4. WAP to remove characters in string except alphabets
5. WAP to input a two dimensional array and print lower triangular matrix and
upper triangular matrix. Lower triangular matrix is a matrix which contains
elements below principle diagonal including principle diagonal elements
and rest of the elements are 0. Upper triangular matrix is a matrix which
contains elements above principle diagonal including principle diagonal
elements and rest of the elements are 0.
6. WAP to reverse a string using recursion.
7. WAP to concatenate three strings using recursion.
School of Computer Engineering
Home Work (HW)
75
8. WAP for a matchstick game being played between the computer and a user.
Your program should ensure that the computer always wins. Rules for the
game are as follows:
a. There are 21 matchsticks.
b. The computer asks the player to pick 1, 2, 3, or 4 matchsticks.
c. After the person picks, the computer does its picking.
d. Whoever is forced to pick up the last matchstick loses the game.
9. Write a menu driven program which has following options:
a. Factorial of a number.
b. Prime or not
c. Odd or even
d. Exit
10. WAP to input two matrices A and B. The task is to multiply matrix A and
matrix B recursively. If matrix A and matrix B are not multiplicative
compatible, then generate output “Not Possible”.
18. WAP to input the string expression. Check whether the pairs and the orders of
“{“,”}”,”(“,”)”,”[“,”]” are correct in expression. For example, the program should print
true for exp = “[()]{}{[()()]()}” and false for exp = “[(])”
19. WAP to input a decimal number m. Convert it in binary string and apply n iterations,
in each iteration 0 becomes 01 and 1 becomes 10. Find kth character in the string
after nth iteration.
20. WAP to input an array of distinct integers and a sum value. Find count of any triplets
with sum smaller than given sum value.
21. WAP that calculates the day of the week for any particular date in the past or future.
22. WAP to input two strings. Modify 1st string such that all the common characters of
the 2nd strings have to be removed and the uncommon characters of the 2nd string
have to be concatenated with uncommon characters of the 1st string. If the modified
string is empty then print '-1'.
23. Given a string consisting of only 0, 1, A, B, C where
A = AND, B = OR, C = XOR
Calculate the value of the string assuming no order of precedence and evaluation is
done from left to right.
24. WAP to print the following pattern wherein the input is the character.
A
AB
ABC
ABCD
ABCDE
ABCDEF
25. WAP to print the following pattern wherein the input is the number.
1
22
333
4444
55555