C++ Progrmming Unit II
C++ Progrmming Unit II
C++ Progrmming Unit II
Programming in C++
• For loop
• While loop
• Do-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.
while(condition)
{
body of loop;
}
#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;
}
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.
do
{
body of loop;
} while(condition);
#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);
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.
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.
#include<iostream.h>
#include<conio.h>
void main( )
{
intnum, fact;
clrscr( );
cout<< “Enter the number:-“;
cin>>num;
fact = fact*num;
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.
*
**
***
#include<iostream.h>
#include<conio.h>
void main( )
{
intnum, i, j;
cout<<“Enter the number of line to be print:-“;
cin>>num;
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.
(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;
}
}
(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;
}
getch( );
}
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:
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
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.
• 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.
(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.
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 −
(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.
For example:
Following is the function called max(). This function takes two parameters num1 and
num2 and return the biggest of both −
int 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);
#include<iostream.h>
#include<conio.h>
void main()
{
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.
#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;
}
#include<iostream.h>
#include<conio.h>
void main()
{
int a=100, b=200;
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.
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
Disadvantage of 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)
{
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
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);
}
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;
}
};
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;
};
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;
For Example 2:
A structure variable can be passed to a function in similar way as normal argument. Consider this
example:
struct person
{
char name[50];
int age;
float salary;
};
void main()
{
person p1;
voiddisplaydata(person); // function declaration
getch( );
}
voiddisplaydata(person p)
{
struct_name *struct_pointer;
Example
struct date
{
intdd, mm, yy;
}
void main( )
{
date *dt_ptr; // structure pointer
}
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