24CS101 Unit - Ii
24CS101 Unit - Ii
This document is confidential and intended solely for the educational purpose of RMK
Group of Educational Institutions. If you have received this document through email in
error, please notify the system manager. This document contains proprietary information
and is intended only to the respective group / learning community as intended. If you
are not the addressee you should not disseminate, distribute or copy through e-mail. Please
notify the sender immediately by e-mail if you have received this document by mistake
and delete this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on the contents
of this information is strictly prohibited.
24CS101
Programming in C++
1 Contents
2 Course Objectives
3 Prerequisites
4 Syllabus
5 Course Outcomes
6 CO-PO Mapping
7 Lecture Plan
9 Lecture Notes
10 Assignments
12 Part-B Questions
16 Assessment Schedule
1.13 Recursion
1.14 Namespaces
1. Course Objectives
• To learn problem solving and programming fundamentals.
• To gain knowledge on pointers and functions.
• To apply the principles of object orientated programming.
• To understand operator overloading, inheritance and polymorphism.
• To use the functionalities of I/O operations, files build C++ programs
using exceptions.
2. Prerequisites
1. Imagine you are working as a software engineer at a tech company. Your team is
developing a mathematical software library that will be used in various applications
across the company. One of the features that your team lead has asked you to
implement is a function that calculates the number of trailing zeros in the factorial of a
number.
The team lead has emphasized the importance of encapsulation in your
implementation.
2. Create a C++ class Calculator representing a simple calculator. The class should have
the following attributes and methods:
List of Exercise/Experiments:
1. Write a Program to Demonstrate the i) Operator Overloading. ii) Function Overloading.
2. Write a Program to Demonstrate Friend Function and Friend Class.
3. Program to demonstrate inline functions.
4. Program for Overriding of member functions.
5. Write C++ programs that illustrate how the following forms of inheritance are
supported:
a) Single inheritance b) Multiple inheritance c) Multi level inheritance d) Hierarchical
inheritance.
Practice Questions & Scenario Based Questions:
1. Joy is a software developer at a 3D modeling company. The company is developing a
new software tool that will be used by architects and engineers to design and analyze
3D models of various structures. One of the features that her project manager has
asked is to implement a function that calculates the volume of basic 3D shapes like
cylinders and cuboids. The project manager has emphasized the importance of using
function overloading in her implementation..
2. Imagine you are a software developer tasked with creating a utility program for a school
that handles student scores. The school wants a simple program where teachers can
enter the scores of students for a particular test, and the program will then provide the
highest and lowest scores among them. This will help the teachers quickly identify the
top performer and the student who might need extra help.
Your task is to write program that satisfies the above scenario using inline function
3. Develop a software system to manage part-time worker students at a university. These
students have unique attributes such as their name, student ID, hourly wage, and hours
worked per week. Your goal is to create a C++ program that models this system.
3 Ramu is a software developer at a company specializing in developing software
solutions for geometric shapes. Recently, a client approached with a request to
create a program to calculate the areas of rectangles and triangles.
List of Exercise/Experiments:
1. Program to demonstrate pure virtual function implementation.
2. Count the number of account holders whose balance is less than the minimum balance
using sequential access file.
3. Write a Program to Demonstrate the Catching of all Exceptions.
Practice Questions & Scenario Based Questions:
1. Develop a simple library management system. Create a base class Book representing
a book in the library. The class should have attributes such as title, author, and ISBN
(International Standard Book Number). Implement a virtual function displayDetails() to
display information about the book.
2. A software developer working on a banking application. One of the requirements is to
analyze account holders' balances based on a minimum balance threshold. The
application should read account information from a sequential access file, where each
line represents an account record in the format: account_holder_name, balance.
3. The financial company is developing a new software tool that will be used by financial
analysts to perform various calculations. One of the features of that project is to
implement is a function that performs division of two numbers.
Write a program that takes two integer inputs, numerator and denominator, from the
user. Implement error handling to check if the denominator is zero. If the denominator
is zero, display the message "Division by zero is not allowed!" using an exception. If
the denominator is not zero, calculate the result of the division and display it.
4. Mini project.
TOTAL: 45 (L) + 45 (P) = 90 PERIODS
OUTCOMES:
Upon completion of the course, the students will be able to:
CO1: Solve problems using basic constructs in C++.
CO2: Implement C++ programs using pointers and functions.
CO3: Apply object-oriented concepts and solve real world problems.
CO4: Develop C++ programs using operator overloading and polymorphism.
CO5: Implement C++ programs using Files and exceptions.
CO6: Develop applications using C++ concepts
TEXT BOOKS:
1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015.
2. E Balagurusamy,” Object Oriented Programming with C++”, 4th Edition, Tata McGraw-
Hill Education, 2008.
REFERENCES:
1. Karl Beecher,” Computational Thinking: A beginner's guide to problem-solving and
programming”, BCS Learning & Development Ltd, 2017. (Unit 1)
2. Nell Dale, Chip Weems, “Programming and Problem Solving with C++”, 5th Edition,
Jones and Barklett Publishers, 2010.
3. John Hubbard, “Schaum's Outline of Programming with C++”, MH, 2016.
4. Yashavant P. Kanetkar, “Let us C++”, BPB Publications, 2020
5. ISRD Group, “Introduction to Object-oriented Programming and C++”, Tata McGraw-
Hill Publishing Company Ltd., 2007.
6. D. S. Malik, “C++ Programming: From Problem Analysis to Program Design”, Third
Edition, Thomson Course Technology, 2007.
7. Paul Deitel, Harvey Deitel, “C++ How to Program”, 10th Edition, Pearson Education
Inc. 2017.
8. https://infyspringboard.onwingspan.com/web/en/app/toc/
lex_auth_01297200240671948837_shared/overview
LIST OF EQUIPMENTS:
1. Standalone desktops with C/C++ compiler (or) Server with C/C++ compiler.
5. Course Outcomes
PO PO PO PO PO PO PO PO PO PO PO PO PS PS PS
COs 1 2 3 4 5 6 7 8 9 10 11 12 O1 O2 O3
CO1 3 2 1 2 1
CO2 3 2 1 2 1
CO3 3 2 1 2 1
CO4 3 3 3 2 1
CO5 3 2 1 2 1
CO6 3 3 3 1 1 1 2 1
1
7. Lecture Plan - Unit I
2 Pointer Operators & Expressions 1 04-10-2024 04-10-2024 CO2 K1 Chalk & Talk
5 Scope Rules and Function Variables 1 07-10-2024 07-10-2024 CO2 K2 Chalk & Talk
Pointers - Pointer Variables - Pointer Operators & Expressions -Pointers with Arrays –
Storage Classes - Types of storage classes - Create Header Files - User-Defined Functions
Definition
Syntax
datatype *ptrname;
Example
Initializing Pointers:
When (&) is placed before the name of a variable, the address-of operator
Syntax
pointer= &variable;
Example
Syntax
Where data_type is any valid data type and var1, var2, ...., varn are
the names of the pointer variables.
Pointer operators
When a function is called by reference any change made to the reference variable
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int a,b; scanf(“%d%d”,&a,&b); swap(&a, &b);
printf("After Swapping:\ %d %d”,a,b);
return 0;
}
void swap(int *a, int *b)
{
int temp; temp = *a;
*a = *b;
*b = temp;
}
Then the pointer will be moved to other elements in the array using pointer
address arithmetic.
int a[5]={10,20,30,40,45};
int *b; b=&a[0];
Here, ‘b’ is a pointer variable which holds the base address of the array ‘a’.
That is, b=a[0];
The array is in integer type, the integer will have 2 bytes and hence the address
of the next element is incremented by 2.
Example
#include<stdio.h>
void main()
{
int a[2]={10,20};
int *p;
p=&a[0];
printf(“%d”,*p); ---------------------- 10
printf("%d\n",++*p); --------- 11
printf("%u\n",p); -----------------------65522
printf("%u\n",++p); -----------------------65524
}
for(i=0;i<10;i++)
scanf("%d",(x+i));
for(i=0;i<10;i++)
printf("%d",*(x+i));
The indirection operator is used to access the value in that memory location.
Program – Reading and Writing in an array using pointer
#include<stdio.h>
void main()
{
int x[10],i;
printf(“Enter the value of n “);
scanf(“%d”,&n);
printf(“Enter five numbers \n”); for(i=0;i<5;i++)
scanf("%d",(x+i));
hello gupyrsintf("Elements are\n"); for(i=0;i<5;i++)
printf("%d",*(x+i));
}
Pointer to 2D array
for (i=0;i<10;i++)
for(j=0;j<10;j++)
scanf("%d",((x+i)+j));
Print the values of 2D array using pointer
for(i=0;i<10;i++)
for(j=0;j<10;j++)
printf("%d", *(*(ax+i)+j));
Example
Output
11 22 33 44 55
Array of pointer and Initialization of Pointer Arrays
Syntax:
datatype *array_name[size];
It sets each pointer in one array to point to an integer value and then prints the values
Example
int *a[5]; In this array of pointer ‘a’, we can store 5 pointer values.
int x=45,y=67,z=89;
int *a[5];
a[0]=&x;
a[1]=&y;
a[2]=&z;
int x=45,y=67,z=89;
int *a[5]={&x, &y, &z};
Address = 1548824464 Value = 10
Address = 1548824468 Value = 20
Address = 1548824472 Value = 50
Program
#include<stdio.h>
void main()
{
int *p[3];
int a = 10, b = 20, c = 50, i; p[0] = &a;
p[1] = &b;
p[2] = &c;
for(i = 0; i < 3; i++)
{
printf("Address = %u\t Value = %d\n", p[i], *p[i]);
}
}
Pointer Arithmetic
1. Addition operation.
2. Subtraction operation
3. Increment operation
4. Decrement operation
5. Comparison operation
1. Addition operation
Example
2. Subtraction operation
Example
3. Increment operation
Example
Pre-increment Post-increment
Example
Pre-decrement Post-decrement
5. Comparison operation
Example
Example
char st[10]=”GOOD”;
char *p;
p=st;
printf(“%s”,p); ------GOOD
Example
Note that we have to manually append the '\0' to s after the loop.
Note that in doing so we depend
The same way character pointer also passed as argument to the function definition.
Pointer to Pointer
Example
#include<stdio.h>
void main()
{
int a=10,*b,**c; b=&a;
c=&b; //Output
printf("Value of a is %d\n",a); //Value of a is 10
printf("Value of b is %u\n",b); //Value of b is 3532047324
printf("Value of c is %u\n",c); //Value of c is 3532047328
printf("Address of a is %u\n",&a); //Address of a is 3532047324
printf("Address of b is %u\n",&b); //Address of b is 3532047328
printf("Address of c is %u\n",&c); //Address of c is 3532047336
printf("Value of a is %d\n",*b); //Value of a is 10
printf("Address of a is %u\n",*c); //Address of a is 3532047324
printf("Value of a is %d\n",*(&a)); //Value of a is 10
printf("Value of a is %d\n",**c); //Value of a is 10
}
1.4 Functions
Introduction
Functions break large computing tasks into smaller ones and called a number
of times whenever required instead of starting over from scratch. Functions hide details
of operation from parts of the program and provide abstraction.
C++ programs consist of many small functions rather than a few big ones. A
program may reside in one or more source files. Source files may be compiled separately
and loaded together, along with previously compiled functions fromlibraries.
Function declaration and definition: It is possible to declare the type ofarguments
when a function is declared. Function declaration consists of the returntype of the
function, name of the function, and list of arguments with their types. Function
declaration is otherwise called as function prototype or function signature. Each function
declaration or prototype has the form (general syntax):
return-type function-name(comma separated list of argument types);
function.
int z;
z= x+y;
return z;
return a + b;
int main() {
cout << "The sum of " << num1 << " and " << num2 << " is " << sum <<endl;
return 0;
}
Another example of f u n ct i o n is to write a program for finding the factorial of a given
number using a function fact.
int fact (int n)
{
int f=1, i;
for (i=1; i<=n; i++)
f =f * i;
return f;
}
Type of functions:
Based on whether it is created by user or already available in
language library
A. In-Built or Built-In function (Already written by someone and is available in the
system Library
B. User defined function. (Created by the user)
Scope Rules:
Function variable
Function variables are variables that are declared within a function. They are local to
that function and cannot be accessed outside of it. Global variables are declared outside of
all functions, making them accessible from any function within the same program. They have
a global scope.
Local Variables:
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of code. Local
variables are not known to functions outside their own. The following example shows
how local variables are used. Here all the variables a, b, and c are local to main()
function.
#include <iostream>
using namespace std;
int main() {
// Local variable declaration
int a, b;
int c;
// Actual initialization
a = 10;
b = 20;
c = a + b;
// Output the result
cout << "Value of a = " << a << ", b = " << b << " and c = " << c
<< endl;
return 0;
}
Output:
Value of a = 10, b = 20 and c = 30
Global Variables
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and they can
be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.
A program can have same name for local and global variables but the value of
local variable inside a function will take preference. Here is an example:
#include <iostream>
using namespace std;
/* Global variable declaration */
int g = 20;
int main() {
/* Local variable declaration */
int g = 10;
// Output the value of the local variable g
cout << "Value of g = " << g << endl;
return 0;
}
When the above code is compiled and executed, it produces the following
result:
Output:
value of g = 10
No arguments are passed but the function is returning something to the calling
function.
Example: Printing message from a function.
#include <iostream>
using namespace std;
// Function to return the number of cakes
int howManyCakes() {
return 25;
}
int main() {
cout << "I will give you " << howManyCakes() << " cakes, are you happy
now?" << endl;
return 0;
}
Output:
I will give you 25 cakes, are you happy
now?
Type C: Functions with arguments, without return value
A function is called with arguments, the function will do the operation and print the
result there itself and returning nothing.
#include <iostream>
using namespace std;
// Function to add two numbers and print the result
void addTheseNumbers(int x, int y) {
cout << "I have added these numbers, result is: " << (x + y) <<
endl;
}
int main() {
cout << "Add these numbers for me please: 48 and 76" << endl;
addTheseNumbers(48, 76); // Correct function name
cout << "Thank You" << endl;
return 0;
}
Output:
Add these numbers for me please: 48 and 76
I have added these numbers, result is: 124
Thank You
#include <iostream>
using namespace std;
// Function to find the average of four integers
float findAverage(int x1, int x2, int x3, int x4) {
int sum;
float avg;
sum = x1 + x2 + x3 + x4;
avg = sum / 4.0; // Ensure floating-point division
return avg;
}
int main() {
int a = 40, b = 55, c = 87, d = 69;
float f;
f = findAverage(a, b, c, d); // Call the function
cout << "The average is: " << f << endl; // Output the result
return 0;
}
Output:
The average is: 62.75
Functions can be invoked in two ways: (or) Parameter Passing methods in C++
Call By Value:
In this parameter passing method, values of actual parameters are copied
to function’s formal parameters and the two types of parameters are storedin
different memory locations. So any changes made inside functions are not
reflected in actual parameters of the caller.
Call by Reference:
Both the actual and formal parameters refer to the same locations, so
any changes made inside the function are actually reflected in actual parameters
of the caller.
Note: In C, we use pointers to achieve call by reference. In C++, we can either use
pointers or references to for pass by reference.
Key Difference:
• In Call by value method original value is not modified whereas, in Call by reference
method, the original value is modified.
• In Call by value, a copy of the variable is passed whereas in Call by reference, a
variable itself is passed.
• In Call by value, actual and formal arguments will be created in different memory
locations whereas in Call by reference, actual and formal arguments will be createdin
the same memory location.
• Call by value is the default method in programming languages like C++, PHP,
Visual Basic NET, and C# whereas Call by reference is supported only Java language.
• Calls by Value, variables are passed using a straightforward method whereas Callby
#include <iostream>
void callByValue(int x) {
cout << "Inside callByValue function:x = " << x << endl; //Prints modified
value
int main() {
int a = 5;
cout << "Before callByValue: a = " << a << endl; // Prints original value
cout << "After callByValue:a= " <<a<<endl; //Original value remains unchanged
return 0;
Output:
Before callByValue: a = 5
After callByValue: a = 5
#include <iostream>
cout << "Inside callByReference function: x = " << x << endl; // Prints
modified value
int main() {
int a = 5;
cout << "Before callByReference: a = " << a << endl; // Prints original value
cout << "After callByReference: a = " << a << endl; // Original value is
changed
return 0;
Output:
Before callByReference: a = 5
After callByReference: a = 15
The expression will be converted to the return type of the function if necessary.
Parentheses are often used around the expression, but they are optional.
The calling function is free to ignore the returned value. Furthermore, there need to be
no expression after return; in that case, no value is returned to the caller. Control also
returns to the caller with no value when execution “falls off the end'' of the function by
reaching the closing right brace.
In any case, if a function fails to return a value, its “value'' is certain to be
garbage.
The main() should return an integer. Therefore we are always writing the return
statement at last in main as follows:
return 0;
This indicates that all statements in the main function are executed perfectly withoutany
error to the compiler.
Example
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a); // Value of a is 10
}
int main()
{
void (*fun_ptr)(int) = &fun; (*fun_ptr)(10);
return 0;
}
3) A function’s name can also be used to get functions’ address. For example,
in the below program, we have removed address operator ‘&’ in assignment.
We have also changed function call by removing *, the program still works.
Example
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
void (*fun_ptr)(int) = fun; // & removed fun_ptr(10); // * removed
return 0;
}
Pointer to Structure:
Now, you can store the address of a structure variable in the above defined
pointer variable. To find the address of a structure variable, place the '&';
operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure,
you must use the → operator as follows –
struct_pointer->title;
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50]; char author[50]; char subject[100]; int book_id;
};
void printBook( struct Books *book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /*
Declare Book2 of type Book */ strcpy( Book1.title, "C Programming");
strcpy( Book1.author, “Dennis Ritche");
strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;
strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700; printBook( &Book1 ); printBook( &Book2 ); return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
Output:
Like we have array of integers, array of pointers etc, we can also have array
of structure variables. And to use the array of structure variables efficiently,
we use pointers of structure type. We can also have pointer to a single
structure variable, but it is mostly used when we are dealing with array of
structure variables.
#include <stdio.h>
struct Book
{
char name[10]; int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
struct Book b[10]; //Array of structure variables
struct Book* p; //Pointer of Structure type
p = &b;
return 0;
}
#include <stdio.h>
struct my_structure
{
char name[20];
int number;
int rank;
};
int main()
{
struct my_structure variable = {"StudyTonight", 35, 1};
struct my_structure *ptr;
ptr = &variable;
printf("NAME: %s\n", ptr->name);
printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
return 0;
}
Output:
NAME: StudyTonight
NUMBER: 35
RANK: 1
The auto storage class is the default storage class for all local variables.
The auto stands for automatic and all the local variables that are declared
in a block automatically belong to this class.
Example
#include <iostream>
using namespace std;
void test() {
// auto declaration of an int variable.
int x = 10;
Output:
The register storage class is used to define local variables that should be
stored in a register instead of RAM. This means that the variable has a
maximum size equal to the register size (usually one word) and can't have
the unary '&' operator applied to it.
Example
#include<iostream>
using namespace std;
void test() {
// Declaration of a register variable.
register int i=1;
int main() {
// Declaration of another register variable.
register int i=0;
Output:
The register should only be used for variables that require quick access such
as counters. The variables might be stored in a register depending on hardware
and implementation restrictions.
This class allows programmers to declare register variables that are saved
in the microprocessor register when it’s available.
The static storage class is used to declare a variable that once initialized, is
not deallocated when the variable goes out of scope. The life-time of such variable
is the entire program so that variable do not lose their values within function calls.
In C++, when static is used on a class data member, it causes only one copy of
that member to be shared by all objects of its class.
Example:
#include <iostream>
// Function declaration
void fun(void);
static int count=5;/* Global variable */
int main()
{
while(count--){
fun();
}
return 0;
}
// Function definition
void fun(void){
static int i=5; // local static variable
i++;
std::cout<< “I is”<<i;
std::cout<<”and count is”<<count<<std::endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
Static variables retain their value even after a function call ends.
This means that the variable doesn't need to be reinitialized when used in
a new scope.
Static variables are only initialized once, and no new memory is allocated
each time they are used.
When a static variable is used on a class data member, all objects in the
class share a single copy of that data member.
Static variables have a lifetime that lasts the entire program, and can be
accessed from anywhere in the program
When you have multiple files and you define a global variable or function,
which will be used in other files also, then extern will be used in another
file to give reference of defined variable or function. In other words,
extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more
files sharing the same global variables or functions as explained below.
Example:
#include <iostream>
using namespace std;
void externStorageClass() {
// Accessing the extern variable 'x'
cout<< "Value of the variable 'x', declared as extern: " << x << "\n";
int main() {
// Example of extern Storage Class
externStorageClass();
return 0;
}
Output:
The mutable specifier applies only to class objects. It allows a member of an object to
override const member function. That is, a mutable member can be modified by a const
member function
Example:
#include <iostream>
using namespace std;
class Test {
public:
int x;
mutable int y;
Test() {
x = 4;
y = 10;
}
};
int main()
{
const Test t1;
t1.y = 20; // Mutable member can be modified in a const object
cout << t1.y; // Output: 20
return 0;
}
These are the header files created by the user and can be included in the program
Let's save the above code file with the multiply.h name.
Output:
Multiplication is 50
Syntax:
The return_type specifies the data type of the value that the function returns.
If the function does not return a value, the return_type should be void.
A user-defined function in C++ that has no parameters and no return value, also
known as a void function, is a block of code that performs a specific task but does not take
any input and does not return any output.
Example 1:
#include <isostream>
using namespace std;
void print_message()
{
cout<<”welcome”<<endl;
}
int main()
{
print_message();
return 0;
}
Output:
Welcome
A user-defined function in C++ that has no parameters but has a return value, is a
block of code that performs a specific task and returns a value of a specific data type but
doesn’t take any input.
Example 2:
#include <iostream>
#include <cstdlib>
using namespace std;
intget_random_number() {
return rand() % 10 + 1;
}
int main() {
cout<< "Random number: " <<get_random_number() <<endl;
return 0;
}
Output:
Random number: 4
This type has parameters and no return value, also known as a void function,
is a block of code that performs a specific task and takes input in the form
Example 3:
#include <iostream>
using namespace std;
void print_string(string input)
{
cout<< "Input: " << input <<endl;
}
int main()
{
string message = "Hello World";
print_string(message); // Calling the function
return 0;
}
Output:
specific task, takes input in the form of function parameters, and returns a
Example 4:
#include <iostream>
using namespace std;
int multiply(int x, int y)
{
return x * y;
}
int main() {
int a = 2, b = 3;
int result = multiply(a, b);
cout<< "Result: " << result <<endl;
return 0;
}
Output:
Result: 6
1.11 INLINE FUNCTIONS:
Definition:
General Form:
inline function-header
{
function body;
}
Program illustrates the use of inline functions.
Example 1:
#include<iostream>
inline float mul(float x, float y)
{
return (x*y);
}
inline double div(double p, double q)
{
return (p/q);
}
int main()
{
float a=12.345;
float b=9.82;
cout<<mul(a,b);
cout<<div(a,b);
return 0;
}
Function overloading is the process of using the same name for two or more
functions .The secret to overloading is that each redefinition of the function must use
either different types of parameters or a different number of parameters. It is only
through these differences that the compiler knows which function to call in any given
situation. For example, this program overloads myfunc () by using different types of
parameters.
Example:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
#include <iostream>
using namespace std;
int myfunc(int i); // these differ in types of parameters
double myfunc(double i);
int main()
{
cout << myfunc(10) << " "; // calls myfunc(int i)
cout << myfunc(5.4); // calls myfunc(double i)
return 0;
}
double myfunc(double i)
{
return i;
}
int myfunc(int i)
{
return i;
}
#include <iostream>
using namespace std;
int myfunc(int i); // these differ in number of parameters
int myfunc(int i, int j);
int main()
{
cout << myfunc(10) << " "; // calls myfunc(int i)
cout << myfunc(4, 5); // calls myfunc(int i, int j)
return 0;
}
int myfunc(int i)
{
return i;
}
int myfunc(int i, int j)
{
return i*j;
}
As mentioned, the key point about function overloading is that the functions must
differ in regard to the types and/or number of parameters. Two functions differing only in
their return types cannot be overloaded. For example, this is an invalid attempt to overload
myfunc():
Many times you will create a class for which there are two or more possible ways to
construct an object.
Consider this program that creates a class called date, which holds a calendar
date. Notice that the constructor is overloaded two ways:
#include <iostream>
#include <cstdio>
using namespace std;
class date {
int day, month, year;
public:
date(char *d);
date(int m, int d, int y);
void show_date();
};
// Initialize using string.
date::date(char *d)
{
sscanf(d, "%d%*c%d%*c%d", &month, &day, &year);
}
// Initialize using integers.
date::date(int m, int d, int y)
{
day = d;
month = m;
year = y;
}
void date::show_date()
{
cout << month << "/" << day;
cout << "/" << year << "\n";
}
int main()
{
date ob1(12, 4, 2001), ob2("10/22/2001");
ob1.show_date();
ob2.show_date();
return 0;
}
1.13 Recursion:
A function that calls itself is known as are cursive function. And, this technique
is known as recursion.
Process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function
Recursive algorithm, certain problems can be solved quite easily. Example of
such problem is Towers of Hanoi
The recursive program, the solution to the base case is provided and the
solution of the bigger problem is expressed in terms of smaller problems.
Is a programming technique that allows the programmer to express operations
in terms of themselves It takes the form of a function that calls itself.
Useful way to think of recursive functions is to imagine them as a process
being performed where one of the instructions is to “repeat the process".
Makes it sound very similar to a loop because it repeats the same code, and in
some ways it is similar to looping. On the other hand, recursion makes it easier
to express ideas in which the result of the recursive call is necessary to
complete the task.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
From the function, otherwise it will go into an infinite loop. Calculating the factorial
of a number, generating Fibonacci series, etc.
Factorial of a number:
#include <iostream>
using namespace std;
int factorial(int i)
{
if(i <= 1)
{
return 1;
}
else
{
return i * factorial(i -1);
}
}
int main()
{
int i ;
// Enter the factorial value
cin>>i;
cout<<"Factorial number is :"<<factorial(i);
return 0;
}
Output
Status :Successfully executed
Time:0.0000 secs
Memory:3.132 Mb
Sample Input
5
Your Output
Factorial number is :120
Program for Fibonacci Series using recursion :
#include <iostream>
using namesapace std;
int fibonacci(int i)
{
if(i == 0)
return 0;
else if(i == 1)
return 1;
else
return fibonacci(i-1) + fibonacci(i-2);
}
intmain()
{
int i;
for (i = 0; i < 6; i++)
{
printf("%d\t\n", fibonacci(i));
}
return 0;
}
Output:
0
1
1
2
3
5
Sum of Natural Numbers Using Recursion:
#include <iostream>
using namespace std;
Output:
Enter a positive integer:3
sum = 6
1.14 Namespaces:
The creation of the namespace keyword was a response to these problems.
Because it localizes the visibility of names declared within it, a namespace allows the
same name to be used in different contexts without conflicts arising. Perhaps the
most noticeable beneficiary of namespace is the C++ standard library. Prior to
namespace, the entire C++ library was defined within the global namespace (which
was, of course, the only namespace).
Since the addition of namespace, the C++ library is now defined within its own
namespace, called std, which reduces the chance of name collisions. You can also
create your own namespaces within your program to localize the visibility of any
names that you think may cause conflicts. This is especially important if you are
creating class or function libraries.
Namespace Fundamentals
The namespace keyword allows you to partition the global namespace by creating a
declarative region.
In essence, a namespace defines a scope. The general form of namespace is
shown here:
namespace name {
// declarations
}
namespace CounterNameSpace
{
int upperbound;
int lowerbound;
class counter {
int count;
public:
counter(int n)
{
if(n <= upperbound)
count = n;
else
count = upperbound;
}
void reset(int n)
{
if(n <= upperbound) count = n;
}
int run()
{
if(count > lowerbound)
return count--;
else
return lowerbound;
}
};
}
Here, upperbound, lowerbound, and the class counter are part of the scope defined
by the CounterNameSpace namespace
However, since namespace defines a scope, you need to use the scope resolution
operator to refer to objects declared within a namespace from outside that namespace
upperbound from code outside CounterNameSpace, you must use this statement:
CounterNameSpace::upperbound = 10;
CounterNameSpace::counter ob;
// Demonstrate a namespace.
#include <iostream>
using namespace std;
namespace CounterNameSpace {
int upperbound;
int lowerbound;
class counter {
int count;
public:
counter(int n) {
if(n <= upperbound) count = n;
else count = upperbound;
}
void reset(int n) {
if(n <= upperbound) count = n;
}
int run() {
if(count > lowerbound) return count--;
else return lowerbound;
}
};
}
int main()
{
CounterNameSpace::upperbound = 100;
CounterNameSpace::lowerbound = 0;
CounterNameSpace::counter ob1(10);
int i;
do {
i = ob1.run();
cout << i << " ";
} while(i > CounterNameSpace::lowerbound);
cout << endl;
CounterNameSpace::counter ob2(20);
do {
i = ob2.run();
cout << i << " ";
} while(i > CounterNameSpace::lowerbound);
cout << endl;
ob2.reset(100);
CounterNameSpace::lowerbound = 90;
do {
i = ob2.run();
cout << i << " ";
} while(i > CounterNameSpace::lowerbound);
return 0;
}
Using:
The using statement was invented to alleviate this problem. The using statement has
these two general forms:
The following program illustrates using by reworking the counter example from
the previous section.
// Demonstrate using.
#include <iostream>
using namespace std;
namespace CounterNameSpace {
int upperbound;
int lowerbound;
class counter {
int count;
public:
counter(int n) {
if(n <= upperbound) count = n;
else count = upperbound;
}
void reset(int n) {
if(n <= upperbound) count = n;
}
int run() {
if(count > lowerbound) return count--;
else return lowerbound;
}
};
}
int main()
{
// use only upperbound from CounterNameSpace
using CounterNameSpace::upperbound;
// now, no qualification needed to set upperbound
upperbound = 100;
// qualification still needed for lowerbound, etc.
CounterNameSpace::lowerbound = 0;
CounterNameSpace::counter ob1(10);
int i;
do {
i = ob1.run();
cout << i << " ";
} while(i > CounterNameSpace::lowerbound);
cout << endl;
// now, use entire CounterNameSpace
using namespace CounterNameSpace;
counter ob2(20);
do {
i = ob2.run();
cout << i << " ";
} while(i > lowerbound);
cout << endl;
ob2.reset(100);
lowerbound = 90;
do {
i = ob2.run();
cout << i << " ";
} while(i > lowerbound);
return 0;
}
Unnamed Namespaces:
There is a special type of namespace, called an unnamed namespace that allows you
to create identifiers that are unique within a file. Unnamed namespaces are also called
anonymous namespaces.
They have this general form:
Namespace
{
// declarations
}
Unnamed namespaces allow you to establish unique identifiers that are known only
within the scope of a single file. That is, within the file that contains the unnamed
namespace, the members of that namespace may be used directly, without qualification.
But outside the file, the identifiers are unknown.
#include <iostream>
using namespace std;
namespace NS1 {
int i;
namespace NS2 { // a nested namespace
int j;
}
}
int main()
{
NS1::i = 19;
// NS2::j = 10; Error, NS2 is not in view
NS1::NS2::j = 10; // this is right
cout << NS1::i << " "<< NS1::NS2::j << "\n";
// use NS1
using namespace NS1;
Here, the namespace NS2 is nested within NS1. Thus, when the program begins, to
refer to j, you must qualify it with both the NS1 and NS2 namespaces. NS2 by itself is
insufficient. After the statement.
using namespace NS1; executes, you can refer directly to NS2 since the
Standard C++ defines its entire library in its own namespace called std.
This is the reason that most of the programs in this book include the
following statement:
This causes the std namespace to be brought into the current namespace,
which gives you direct access to the names of the functions and classes defined
within the library without having to qualify each one with std::.
// Use explicit std:: qualification.
#include <iostream>
int main()
{
int val;
std::cout << "Enter a number: ";
std::cin >> val;
std::cout << "This is your number: ";
std::cout << std::hex << val;
return 0;
}
Here, cout, cin, and the manipulator hex are explicitly qualified by their
namespace. That is to write to standard output, you must specify std::cout;
to read from standard input, you must use std::cin; and the hex manipulator
must be referred to as std::hex
If you are using only a few names from the standard library, it may make more
sense to specify a using statement for each individually. The advantage
to this approach is that you can still use those names without an std::
qualification, but you will not be bringing the entire standard library into the
global namespace.
For example:
Here, cin, cout, and hex may be used directly, but the rest of the std
namespace has not been brought into view. As explained, the original C++ library
was defined in the global namespace
10. Assignment Questions
n = 24
Test case1:
Input: 24
Output: 2
Test case 2:
Input:2
Output:1
Test case1:
Input: 23
Output: 0
Test case 2:
Input:36
Output:1
An e-commerce company plans to give their K4 CO1
customers a special discount for Christmas. They are
4 planning to offer a flat discount. The discount value is
calculated as the sum of all the prime digits in the total
bill amount.
Input
The input consists of an integer orderValue,
representing the total bill amount.
Output
Print an integer representing the discount value for the
given total bill amount.
Example
Input
578
Explanation 7 and 5 are prime numbers and 7+5=12.
Output
12
A pointer is a variable that stores the memory address of another variable. It allows direct
access to memory locations.
Pointers are commonly used for dynamic memory allocation, efficient array handling,
and implementing data structures like linked lists and trees.
3. What are the two operators used for pointer connection? (K2,CO1).
Syntax
datatype *ptrname;
Where data_type is any valid data type and var1, var2, ...., varn are the names
of the pointer variables.
The & operator is used to obtain the address of a variable. This address can then
be assigned to a pointer variable, enabling the pointer to reference that variable.
The dereference operator (*) accesses the value stored at the address contained
in a pointer variable. For example, *ptr retrieves the value at the memory
location pointed to by ptr.
Using NULL pointers helps prevent dereferencing invalid memory, which can
lead to undefined behaviour or program crashes
15. What are the steps followed to create a header file? (K2,CO1).
a. Write a code in C++ and save it with the .h extension.
b. Include your header file using #include in the c++ program.
S S.No
Built-in Function User defined function
1. These are library function whichT These are created and defined by the
exists in the programming programmer.
language.
2. The header files such as data type function_name(arguments)
<math.h>, <string.h> are {
included based on the function{ Body of function;
used in the program. }
20. what are the different types of functions based on arguments and
22.What are the differences between local and global scope? (K2,CO1).
Scope in C++ defines the visibility of variables and functions. Local scope refers to
variables declared within a function or block, making them accessible only within that
context. Global scope refers to variables declared outside any function, accessible
throughout the program.
23.What is a function variable in C++? How does it differ from a global variable?
(K2,CO1).
24. What is the purpose of the return statement in a C++ function? (K2,CO1).
The return statement is used to exit a function and optionally return a value to the
calling function. It can also indicate the end of a function's execution.
25.Write a C++ program to find the factorial of a given number using
function.(K3,CO1)
2. Describe the different pointer operators in C++. How do the dereference operator
and address-of operator work? Provide code snippets to illustrate their usage. (K2, CO1)
3. What are the differences between a pointer and an array in C++? Explain how
pointers can be used to manipulate array elements. Include examples. (K3, CO1)
4. Discuss pointer arithmetic in C++. How does it work, and what are its
applications? Provide examples with arrays. (K3, CO1)
5. Write a C++ program for swapping Values using Pointers. (K2, CO1)
7. Write a C++ program for function Returning using a Pointer. (K2, CO1)
8. Write a C++ program for String Manipulation with Pointers. (K3, CO1)
12. Describe how to create a header file in C++ with an example? (K3, CO1)
13. Discuss the different ways of creating user defined function in detail? (K3, CO1)
14. Write a C++ program to find the GCD of two numbers using Euclidean distance algorithm?
(K2, CO1)
15. Write a c++ program to find the Fibonacci series of a number using function? (K2, CO1)
16. Explain types of User defined function in C++ with example. (K2, CO1)
17. Write a c++ Program to find the area of circle using function. (K3, CO1)
18. Write a C++ program that demonstrates call by reference. The function should take two
integers, swap their values, and print the values before and after the swap. (K3, CO1)
19. Write a C++ program that demonstrates call by value. The function should take two
integers, swap their values, and print the values before and after the swap. (K3, CO1)
20. Write a C++ program that demonstrates function overloading. (K3, CO1)
13. Supportive online courses
• C++ Basics: Selection and Iteration – Coursera
• Complete Modern C++ Programming – Udemy
• An Introduction to Programming Through C++ - NPTEL
• https://swayam.gov.in
• https://www.coursera.org
• https://www.udemy.com
• https://www.sololearn.com
• https://www.tutorialspoint.com/cplusplus
• https://www.geeksforgeeks.org/course
s/cpp-programming-basic-to-advanced
• https://www.geeksforgeeks.org/c-plus-plus
14. Real Time Applications
15. Content beyond syllabus
Namespace in C++
In C++, there are two ways of accessing namespace variables and functions.
Defining a Namespace:
A namespace definition begins with the keyword namespace followed by the
namespace name as follows:
namespace namespace_name
{
// code declarations i.e. variable (int a;)
method (void add();)
classes ( class student{};)
}
It is to be noted that, there is no semicolon (;) after the closing brace.
To call the namespace-enabled version of either function or variable,
prepend the namespace name as follows:
Namespace name: :code; // code could be variable , function or class.
Program:
#include <iostream>
using namespace std;
// first name space
namespace first_space
{
void func()
{
cout << "Inside first_space" << endl;
}
// second name space
namespace second_space
{
void func()
{
cout << "Inside second_space" << endl;
} } }
using namespace first_space::second_space;
int main () Output:
{
Inside second_space
// This calls function from second name space.
func();
return 0;
}
//C++ program to demonstrate accessing of variables
// in normal way, i.e., using "::“
#include <iostream>
using namespace std;
namespace geek
{
int rel = 300;
} Output :
300
int main()
{
Text Books:
1. Herbert Schildt, “The Complete Reference C++”, 4th edition, MH, 2015.
2. E Balagurusamy,” Object Oriented Programming with C++”, 4th Edition, Tata
McGraw- Hill Education, 2008.
Reference Books:
Pointers Usage:
By building this project, you will comprehend the basics of the pointers.
Furthermore, this C++ project structure will help you in knowing about the system
of file management. The program designed by you will be ready to accumulate all
the students’ data and information correctly. This data can be anyinformation
related to the student, their personal information, academic records, roll number,
etc. This project will teach you how to tackle wrong inputs. ( K1, CO2)
Pointers Usage:
a. Use pointers for dynamic memory allocation and resizing the array
Pointers Usage:
Pointers Usage:
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contentsof this information is strictly prohibited.