You are on page 1of 21

BCA – IstYr

Programming in C++

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 1 of 21


Unit - II
Looping (Iteration):
The iteration (looping) statements allow a set of instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called loops or looping statements.

C++ provides three kinds of loops:

• For loop
• While loop
• Do-while loop

(1) The while loop:

The while loop is an entry-controlled loop. It means the control conditions are tested before the start of
loop’s execution. If the conditions are not satisfied then body of loop will not be executed and control will
be transferred out of the loop.

The syntax of a while loop is

while(condition)
{
body of loop;
}

Example: Program to calculate the factorial of an entered number.

#include<iostream.h>
#include<conio.h>
void main( )
{
intnum, fact;
clrscr( );
cout<< “Enter the number:-“;
cin>>num;
fact = 1;
while(num>0)
{
fact = fact*num;
num--;
}
cout<<endl<< “The factorial of given number is : -“ << fact;
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 2 of 21


(2) The do-while loop:

The do-while loop is an exit-controlled loop, that is, the control conditions are tested at the bottom of the
loop after executing its loop-body statements. This means that a do-while loop always executes at least once,
even when the condition is false initially. The most common use of this loop is in menu selection function.

The syntax of a do-while loop is

do
{

body of loop;

} while(condition);

Example: Program to calculate the factorial of an entered number.

#include<iostream.h>
#include<conio.h>
void main( )
{
intnum, fact;
clrscr( );
cout<< “Enter the number:-“;
cin>>num;
fact = 1;

if (num = = 0)
{
cout<<endl<< “The factorial of given number is : -“ << fact;
exit( );
}

do
{

fact = fact*num;
num--;

} while(num>0);

cout<<endl<< “The factorial of given number is : -“ << fact;


}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 3 of 21


(3) The for loop:

The For loop is easiest loop to be used in C++. Like while loop it is also an entry-controlled loop. In this
loop, the loop control elements (initialization, condition & increment/decrement) are gathered in one place,
while in other loops they are scattered over the program and difficult to understand.

The syntax of a for loop is

for(initialization; condition; increment/decrement)


{

body of loop;

Here,

Initialization expression: It is executed only once when the loop first starts. It provides the loop variable
an initial value.

Condition expression: It involves relational operators. It is executed every time through the loop before the
body of the loop is executed. If the condition is true, the body of the loop is executed, and if false, the
control comes out of the loop.

Increment/Decrement expression: It is always executed at the end of the loop, after the body of the loop.

Example: Program to calculate the factorial of an entered number.

#include<iostream.h>
#include<conio.h>
void main( )
{
intnum, fact;
clrscr( );
cout<< “Enter the number:-“;
cin>>num;

for(fact=1; num>0; num--)


{

fact = fact*num;

cout<<endl<< “The factorial of given number is : -“ << fact;


}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 4 of 21


• Nested Loops:

Nesting of loops means one or more loop(s) within a loop. In nested loop the inner loop is executed
first and then outer. The nested loop must be used to input or output multi-dimensional array
elements. In nested loops the value of outer loop control variable will change only after the inner
loop has been completely executed.

Example: Program to print the following output

*
**
***
#include<iostream.h>
#include<conio.h>
void main( )
{
intnum, i, j;
cout<<“Enter the number of line to be print:-“;
cin>>num;

for(i=1; i<=num; i++)


{

for(j=1; j<=i; j++)


{
cout<<“*”;
}
cout<<“\n”;
}
}

JUMP Statements:
The jump statements unconditionally transfer program control within a function. C++ has three statements
that perform an unconditional branch: goto, break, and continue.
(a) The goto Statement: A goto statement can transfer the program control anywhere in the
program. The target destination of a goto statement is marked by a label. The target label and
goto must appear in the same function.
Syntax:
goto label;
.
.
label :

herelabel is a user supplied identifier and can appear either before or after goto.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 5 of 21


Example: WAP to print 10 to 1 numbers
#include<iostream.h>
#include<conio.h>
void main( )
{
int n = 10;
loop:
cout<< n;
n = n – 1;
if(n>0)
{
goto loop;
}
getch( );
}

(b) The break Statement: The break statement enables a program to skip over part of the
code. A break statement terminates the smallest enclosing while, do-while, for or switch
statement. Execution resumes at the statement immediately following the body of the terminated
statement.
Example: To stop the countdown before its natural end
#include <iostream.h>
void main ( )
{
int n;
for (n=10; n>0; n--)
{
cout<< n << ", ";
if (n==3)
{
cout<< "countdown aborted!";
break;
}
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 6 of 21


getch();
}

(c) The continue Statement: The continue is another jump statement like the break
statement as both the statements skip over a part of the code. But the continue statement is
somewhat different from break. Instead of forcing termination, it forces the next iteration of the
loop to take place, skipping any code in between.
Example:
#include <iostream.h>
#include <conio.h>
void main ( )
{
int a, b;
charch;
clrscr( );

do
{
cout<< “\n Enter the dividend & divisor : - “;
cin>> a >> b;
if (b == 0)
{
cout<< "\n Illegal Divisior !!!”;
continue;
}

cout<< "\n Quotient is :” << a/b;

cout<< “\n Do you have another one ? (y/n) :”;


cin>>ch;

} while (ch==’y’ || ch==’Y’);

getch( );
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 7 of 21


Pointer: A pointer is a variable that contains the address of another same type of variable.

The general form of a pointer variable declaration is –

type *var_name;

Here, type is the pointer's base type; it must be a valid C++ data type and var-name is the
name of the pointer variable. The symbol (asterisk) * used to declare a pointer.

For Example:

int *a, *b;

char *ch, *ch1;

Initialization of Pointer variable

Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer variable
contains address of variable of same data type. In C++ language address operator(&) is used to determine
the address of a variable. The address operator(&) returns the address of the variable associated with it.

int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization

Benefits of using pointers

• Pointers are more efficient in handling Array and Structure.


• Pointer allows references to function and thereby helps in passing of function as arguments to other
function.
• It reduces length of the program and its execution time.
• It allows C++ to support dynamic memory management.
• Pointers provide direct access to memory
• Pointers provide a way to return more than one value to the functions

Disadvantages of Pointers
• Uninitialized pointers might cause segmentation fault.
• Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
• Pointers are slower than normal variables.
• If pointers are updated with incorrect values, it might lead to memory corruption.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 8 of 21


Functions: Functions are building blocks or self-contained block of statements that perform a
specific task. A large program can be broken down into number of smaller, self-contained components; each
has some unique and identifiable function. Each function has its own name.

There are two types of functions in C++ programming:

• Standard library functions: The standard library functions are built-in functions in C++
programming to handle tasks such as mathematical computations, I/O processing, string handling
etc. These functions are defined in the header file. When the specific header file is included these
functions are available for use.
For example:
isalpha( ), isdigit( ), isupper( ), islower( ), etc. are character functions available in ctype.h
header file.

• User defined functions: C++ allows programmers to define their own functions. These
functions are defined by the user to meet their requirements are known as user defined functions.

Every function in C++ consists of following components:

(a) Function Declaration


(b) Function Definition
(c) Function Call

(a) Function declaration: A function declaration tells the compiler about a function
name and how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts −

return_typefunction_name( parameter list );

For Example
int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so
following is also valid declaration −

int max(int, int);

(b) Function definition: A function definition contains a function declaration and the body of
the function. A function can only have one definition. The function definition consists of the
function header and its body. The header is same like the function prototype, except that it
contains no terminating semicolon.

The general form of a C++ function definition is as follows −

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 9 of 21


return_typefunction_name( parameter list )
{
body of the function;
}

For example:

Following is the function called max(). This function takes two parameters num1 and
num2 and return the biggest of both −

// function returning the max between two numbers

int max(int num1, int num2)


{

int result;

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}

(c) Function Call: To execute the codes of function body, the user-defined function needs
to be called. A function can be called by specifying the function name followed by a list of
arguments separated by commas enclosed in the pair of parentheses. Each function call is
terminated by semicolon.

For example:
int m;
m = max(10, 20);

Example: Finding the factorial of given number using function.

#include<iostream.h>
#include<conio.h>
void main()
{

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 10 of 21


inti,f,num;
int fact(int); // Function Declaration
clrscr();
cout<<"Enter any number: ";
cin>>num;
f=fact(num); // Function Call
cout<<"\n Factorial is: "<<f;
getch();
}

int fact(int n) // Function Definition


{
int x;
if(n ==0)
{
return(1);
}
while(n>0)
{
x = x *n;
n--;
}
return (n);
}

Argument passing techniques: There are two ways for passing the arguments in a functions:

o Call by Value
o Call by Reference

• Call by Value: By default, arguments in C++ are passed by value. This method copies the
actual value of an argument into the formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the argument.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 11 of 21


Example: Swapping of two values with the use of call by value.

#include<iostream.h>
#include<conio.h>
void main()
{
int m = 22, n = 44;
void swap(int, int);
cout<<" Values before swapping “;
cout<< “\n m =” << m <<”and n =” << n;
swap(m, n); // calling swap function by value
}
void swap(int a, int b)
{
inttmp;
tmp = a;
a = b;
b = tmp;
cout<<" \nValues after swapping “
cout<< “\n m =” << a <<”and n =” <<b;
}

• Call by Reference: In call by reference, original value is changed or modified because


address of the variable is passed to the function. In this case actual and formal arguments share the
same address space. Hence, any value changed inside the function, is reflected inside as well as
outside the function. The &(address) operator is used for passing the addresses of the values.

Example: Swapping of two values with the use of call by value.

#include<iostream.h>
#include<conio.h>
void main()
{
int a=100, b=200;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 12 of 21


void swap(int *, int *);
swap(&a,&b); // passing addresses to function
cout<<"Value of a"<<a;
cout<<"Value of b"<<b;
getch();
}
void swap(int*a,int*b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

Difference between call by value and call by reference


Call by value Call by reference

This method copy original value into function


1 This method copy address into function as an arguments.
as an arguments.

Changes made to the parameter inside the Changes made to the parameter affect the argument.
2
function have no effect on the argument. Because address is used to access the actual argument.

Actual and formal arguments will be created Actual and formal arguments will be created in same
3
in different memory location memory location

Advantages of Functions:

• C++ functions are used to avoid rewriting same logic/code again and again in a program.
• There is no limit in calling C++ functions to make use of same functionality wherever required.
• We can call functions any number of times in a program and from any place in a program.
• A large C++ program can easily be tracked when it is divided into functions.
• The core concept of C++ functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large C++ programs.
• It makes the program easier to design and understand.

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 13 of 21


Recursion (Recursive Function) in C++

The function which calls same function is called recursive function. In other words when a function calls
itself then that function is called Recursive function.

Recursive function is very useful to solve many mathematical problems like to calculate factorial of a
number, generating Fibonacci series, etc.

Advantage of Recursion

• Method calling related information will be maintained by recursion.


• Stack evaluation will be take place by using recursion.
• Infix prefix, post-fix notation will be evaluated by using recursion.

Disadvantage of Recursion

• It is a very slow process due to stack overlapping.


• Recursive programs can create stack overflow.
• Recursive method can create as loops.

Example: Finding the factorial of given number using recursion.

#include<iostream.h>
#include<conio.h>
void main()
{
inti,f,num;
int fact(int);
clrscr();
cout<<"Enter any number: ";
cin>>num;
f=fact(num);
cout<<"Factorial: "<<f;
getch();
}

int fact(int n)
{

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 14 of 21


if(a==0)
{
return(1);
}
else
{
return(n*fact(n-1)); // Recursion
}
}

Functions Returning Pointers: The way a function can return an int, a float, or reference or
any other data types, it can even return a pointer. The general form of a function returning a pointer is

type *function_name (argument list);

Here, type specifies the pointer type being returned by the function specified by function_name.

Example:

#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, *c;
int *big(int&, int&);
clrscr( );
cout<<”\nEnter two integers :-“;
cin>>a >>b;
c = big(a,b);
cout<<”\nThe bigger value is :-“ << *c;
getch( );
}
int *big(int&x, int&y)
{
if(x>y)
return(&x);
else
return(&y);
}

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 15 of 21


Passing Pointers as argument:

Same as Call by Reference described in earlier topic

Function Overloading: C++ allows specification of more than one function of the same name
in the same scope. These are called overloaded functions. Function overloading is a feature of C++ that
allows to create multiple functions with the same name, so long as they have different parameters. That
means the same name to more than one function if they have either a different number of parameters or
different types in their parameter.

For example:

int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }

Example:

#include<iostream.h>
#include<conio.h>
Class addition
{
public:
void sum(int a,int b)
{
cout<<a+b;
}
void sum(int a,int b,int c)
{
cout<<a+b+c;
}
void sum(float a, float b)
{
cout<<a+b;
}
};

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 16 of 21


void main()
{
clrscr();
additionobj;
obj.sum(10,20);
cout<<endl;
obj.sum(10,20,30);
cout<<endl;
obj.sum(2.5, 6.5);
getch( );
}

Structures: Structure is a user defined data type. It is a collection of variables of different data
types under a single name. For example, if user wants to store some information about a person: his/her
name, citizenship number and salary. User can easily create different variables name, citNo, salary to store
this information separately.

The struct keyword is used to define a structure type followed by a structure name. Once the structure is
declared the structure variable is defined in the main( ) program. The members of a structure are accessed
using a dot (,) operator.

Syntax
struct<structure name>
{
Members;
};

Example:
struct person
{
char name[50];
int age;
float salary;
};

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 17 of 21


For Example1:

C++ Program to assign data to members of a structure variable and display it.

#include <iostream.h>
#include <conio.h>
struct person
{
char name[50];
int age;
float salary;
};
void main()
{
person p1;
cout<< "Enter Full name: ";
cin.get(p1.name, 50);
cout<< "Enter age: ";
cin>> p1.age;
cout<< "Enter salary: ";
cin>> p1.salary;

cout<< "\nDisplaying Information." <<endl;

cout<< "Name: " << p1.name <<endl;


cout<<"Age: " << p1.age <<endl;
cout<< "Salary: " << p1.salary;
getch( );
}

For Example 2:

Passing structure to function in C++

A structure variable can be passed to a function in similar way as normal argument. Consider this
example:

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 18 of 21


#include <iostream.h>
#include <conio.h>

struct person
{
char name[50];
int age;
float salary;
};

void main()
{
person p1;
voiddisplaydata(person); // function declaration

cout<< "Enter Full name: ";


cin.get(p1.name, 50);
cout<< "Enter age: ";
cin>> p1.age;
cout<< "Enter salary: ";
cin>> p1.salary;

displaydata(p1); // function call

getch( );
}

voiddisplaydata(person p)
{

cout<< "\nDisplaying Information." <<endl;


cout<< "Name: " << p.name <<endl;
cout<<"Age: " <<p.age<<endl;
cout<< "Salary: " <<p.salary;

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 19 of 21


Structures and Pointers: The pointers to structures are known as structure pointers. The
structure pointers are declared by placing asterisk (*) in front of a structure pointer’s name. The general
form is:

struct_name *struct_pointer;

Example
struct date
{
intdd, mm, yy;
}
void main( )
{
date *dt_ptr; // structure pointer
}

The members of structures are accessed using arrow operator (->).

struct date
{
intdd, mm, yy;
}
void main( )
{
date *dt_ptr;
dt_ptr->dd = 15;
}

Containers
Containers are the objects used to store multiple elements of the same type or different. The container
manages the storage space for its elements and provides member functions to access them, either directly or
through iterators (reference objects with similar properties to pointers).Depending on that they can be further
classified as −
• Sequence containers: They are used for data structures that store objects of the same type in
a linear manner.For example: array, vector, list

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 20 of 21


• Associative containers: They provide sorted data structures that provide a fast lookup (O(log
n) time) using keys.For Example: set, map, multimap
• Unordered Associative containers: They provide unsorted data structures that can be accessed
using a hash. Access times are O(n) in the worst-case, but much faster than linear time for most
operations.For Example: unordered_set, unordered_map
• Container Adapter: They are a special type of container class. They are not full container classes
on their own, but wrappers around other container types. For Example:stack, queue

Prof. Amit Singla, HOD (Comp Dept), S D PG College, SGNR Page 21 of 21

You might also like