Unit-II NOTEScontrolstructure Excercises
Unit-II NOTEScontrolstructure Excercises
Write a program in C++ Program to swap two numbers without third variable
#include <iostream>
using namespace std;
int main()
{
int a=5, b=10;
cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
a=a*b; //a=50 (5*10)
b=a/b; //b=5 (50/10)
a=a/b; //a=10 (50/5)
cout<<"After swap a= "<<a<<" b= "<<b<<endl;
return 0;
}
Control statements
The flow of execution of statements in a program is called as control.
Control statement is a statement which controls flow of execution of the
program.
Control statements are classified into following categories.
1.Decision making statements
2.Looping statements
(a) if Statement
The if statement is the powerful decision making statement, and is used to
control the flow of execution of statements.
It is basically a two-way decision making statement, and is used with an
expression
if statement is used to test the condition.
There are various types of if statements in C++.
Simple if statement
if-else statement
nested if …else statement
if-else-if ladder
(i)Simple if statement
Here, test condition after evaluation will be either true or false.
if the value is true then it will execute the block of statements below it otherwise the
statement block will be skipped and the execution will jump to the statement-x .
the statement block may be a single statement or a group of statements.
If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if
statement will consider the first immediately below statement to be inside its block..
When the condition is true, both the statement-block and statement-x are executed
in sequence.
Syntax:
if(test condition)
{
//statement block
}
statement-x;
flowchart
Example program
#include <iostream.h>
int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
Example: Program to print positive number entered by the user.If the user
enters a negative number, it is skipped
#include <iostream.h>
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}
Output 1
Enter an integer: 5
You entered a positive number: 5
This statement is always executed.
Output 2
Enter a number: -5
This statement is always executed
(ii)if-else Statement
The if-else statement is an extension of the simple if statement.
The C++ if-else statement also tests the condition.
If the test expression is true, then the true block statements are executed. Otherwise
false-block statements are executed.
After execution of true-block or false-block statements, the control is transferred
subsequently to statement-x.
It executes if block if condition is true otherwise else block is executed.
syntax
if(test expression)
{
true-block statements;
}
else
{
false-block statements;
}
Statement-x
flowchart
If-else Example
#include <iostream.h>
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}
This contruct is known as the else…if ladder. The conditions are evaluated
from the top,downwards. As soon as a true condition is found, the statement
associated with it is executed and the control is transferrd to the statement-X.
When all the ‘n’ conditions become false, then the final else containing the
default-statement will be executed.
Example: grading using else…if ladder
……..
if(marks>79)
Grade=”Honours”;
else if(marks>59)
Grade=”first”;
else if (marks>49)
Grade=”second”;
else if(marks>39)
Grade=”third”;
else
Grade=”fail”;
………..
#include <iostream.h>
int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
cout << "i is 10";
// Since i is not 10
// Check if i is 15
else if (i == 15)
cout << "i is 15";
// Since i is not 15
// Check if i is 20
else if (i == 20)
cout << "i is 20";
return 0;
}
Output:
i is 20
#include <iostream.h>
int main ()
{
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}
#include <iostream.h>
#include<conio.h>
int main()
{
float n1, n2, n3;
clrscr();
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if((n1 >= n2) && (n1 >= n3))
cout << "Largest number: " << n1;
else if ((n2 >= n1) && (n2 >= n3))
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
getch();
return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
}
Statement-x;
Example:Nested if…
// using nested if statements
#include <iostream.h>
int main()
{
int num;
cout << "Enter an integer: ";
cin >> num;
// outer if condition
if (num != 0)
{
// inner if condition
if ((num % 2) == 0)
{
cout << "The number is even." << endl;
}
// inner else condition
else
{
cout << "The number is odd." << endl;
}
}
// outer else condition
else
{
cout << "The number is 0 and is neither even nor odd." << endl;
}
cout << "This line is always printed." << endl;
}
Excercises
1. Write a C++ program that prompts the user to input three integer values and find the greatest
value of the three values.(nested if)
3. Write a C++ program to compute the real roots of the equation: ax2+bx+c=0.(switch or else…if
ladder)
The program will prompt the user to input the values of a, b, and c. It then computes the real roots
of the equation based on the following rules:
-if a and b are zero=> no solution
-if a is zero=>one root (-c/b)
-if b2-4ac is negative=>no roots
-Otherwise=> two roots
The roots can be computed using the following formula:
x1=-b+(b2-4ac)1/2/2a
x=-b-(b2-4ac)1/2/2a
b) Switch statement
The switch statement is a multi-way branch statement and an alternative to if-else-if
ladder.
The C++ switch statement executes one statement from multiple conditions.
The switch statement required only one argument, which is then checked with number of
case options.
The switch statement evaluates the expression and looks for its value among the case
constants.
If the value is matched with a case constant then that Case constant is executed until a
break statement is found or end of switch block is executed.
Every case statement ends with a colon(:)
The syntax of the switch() case statement is shown below.
switch(expression)
{
case value1:
//code to be executed;
block1;
break;
case value2:
//code to be executed;
block2;
break;
case value3:
//code to be executed;
block3;
break;
......
……..
default:
//code to be executed if all cases are not matched;
default block;
break;
}
include <iostream.h>
int main ()
{
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}
Output:
Enter a number:
10
It is 10
Excercises
1. write a program to enter a month number of year 2010 and display the number of
days in a month.
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int month,days;
cout << "\n enter a month of year 2020 ";
cout << "-----------------------------\n";
cin >> month;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 10:
case 12:
days=31;
break;
case 2: days=29;
break;
case 4:
case 6:
case 9:
case 11: days=30;
break;
}
cout << "\n No.of days= "<<days;
getch();
}
Output:
enter a month of year 2020
6
No.of days=30
int main()
{
int n, num = 0, i;
cout << "\n\n Print a number in words:\n";
cout << "-----------------------------\n";
cout << " Input any number: ";
cin >> n;
while (n != 0)
{
num = (num * 10) + (n % 10); n /= 10;
}
for (i = num; i > 0; i = i / 10)
{
switch (i % 10)
{
case 0: cout << "Zero "; break;
case 1: cout << "One ";
break;
case 2:
cout << "Two ";
break;
case 3: cout << "Three ";
break;
case 4:cout << "Four ";
break;
case 5:
cout << "Five ";
break;
case 6:
cout << "Six ";
break;
case 7: cout << "Seven ";
break;
case 8: cout << "Eight ";
break;
case 9: cout << "Nine ";
break;
}
}
cout << endl;
}
Output:
Print a number in words:
-----------------------------
Input any number: 8309
Eight Three Zero Nine
Excercises:
1. (switch) Write a program that determines a student’s grade. The program will read three types
of scores (quiz, mid-term, and final scores) and determine the grade based on the following rules:
-if the average score =90% =>grade=A
-if the average score >= 70% and <90% => grade=B
-if the average score>=50% and <70% =>grade=C
-if the average score<50% =>grade=F
Code: cin>>x>>y>>z;
avg=(x+y+z)/3;
if(avg>=90)cout<<"Grade A";
else if((avg>=70) && (avg<90)) cout<<"Grade B";
else if((avg>=50) && (avg<70))cout<<"Grade C";
else if(avg<50) cout<<"Grade F";
else cout<<"Invalid";
c)The ? : Operator
conditional operator “? :” can be used to replace if...else statements.
It has the following general form
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true,
then Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1
is false, then Exp3 is evaluated and its value becomes the value of the expression
It can be visualized into if-else statement as:
if(Exp1)
{
var = Exp2;
}
else
{
var= Exp3;
}
#include <iostream.h>
void main()
{
// variable declaration
int n1 = 5, n2 = 10, max;
Excercises
1. Write a C program to find maximum between three numbers using conditional operator.
2. Write a C program to check whether a number is even or odd using conditional operator.
3. Write a C program to check whether year is leap year or not using conditional operator.
4. Write a C program to check whether character is an alphabet or not using conditional
operator.
2. LOOPS IN C++
In looping, a sequence of statements are executed until some conditions for
termination of the loop are satisfied.
A program loop consists of two segments one known as the body of the loop and the
other known as control statement.
The control statement tests conditions and then directs the repeated execution of the
statements contained in the body of the loop.
Depending on the position of the control statement in the loop, control structure may
be classified as entry-controlled loop or exit-controlled loop.
Three loop contructs for performing loop operations. They sre,
1. The while statement
2. The do statement
3. The for statement
A loop statement allows us to execute a statement or group of statements multiple
times
Output
12345
return 0;
}
Output
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25
2. The do statement
On some occasions it is necessary to execute the body of the loop before the test is
performed.
Such situations can be handled with the help of the do statement.
The syntax of do statement is,
On reaching the do statement, the program proceeds to evaluate the body of the
loop first.
At the end of the loop, the test condition in the while statement is evaluated.
if the condition is true, the program continues to evaluate the body of the loop once
again.
This process continues as long as the condition is true.
when the condition becomes false, the loop will be terminated and the control goes
to the statement that appears immediately after the while statement.
Output:
1
2
3
4
5
6
7
8
9
10
Example: program to print numbers and their cubes up to 10
#include <iostream.h>
# include<conio.h>
void main()
{
clrscr();
int x=1;
cout<<“\n number and cubes”;
//do while loop
do
{
cout << x << " “<<x*x*x;
x++;
} while (x <= 10);
getch();
}
Output
12345
Syntax
for(initialization; condition; incr/decr)
{
body of the loop
//code to be executed
}
Flowchart
void main()
{
clrscr();
for(int i=1;i<=10;i++)
{
cout<<i <<"\n";
}
getch();
}
Output:
1
2
3
4
5
6
7
8
9
10
Sample 0utput
Find power of any number using for loop:
---------------------------------------------
Input the base: 2
Input the exponent: 5
2 ^ 5 = 32
Exercises
Program flow
Nested for loops
Whenever a loop construct appears within another loop construct, it is said to be
nested loop structure.
The loops should not overlap each other.
The variable names used in the expressions of for loop constructs must be different
from one loop to another.
Syntax:
for(initialization1; condition1; incr/decr)
{
statement-1;
for(initialization2; condition2; incr/decr)
{
//statement;
}
}
Example2:print the number pattern 1
2 3
4 5 6
7 8 9 10…..
#include <iostream.h>
#include <conio.h>
void main()
{ int i,j,k=0;
clrscr();
for( j=1;j<5;j++)
{
for( i=1;i<=j;i++)
{
cout<<++k <<"\t";
}
cout<<“\n”;
}
getch();
}
Exercises:
1. Write a C++ program that will print the following pattern(while…..)
*******
******
*****
****
***
**
*
2.Write a program that will print the following pattern(looping statements)
1******
12*****
123****
1234***
12345**
123456*
3. Write a C++ program that will print the pattern as shown below:
*
***
*****
*******
*********
*********
*******
*****
***
*
4. Write a program that will ask the user to input n positive numbers. The program will terminate if
one of those number is not positive.(while or do…while)
8. Write a C++ program using two for loops to produce the following pattern of asterisks
*
**
***
****
*****
******
*******
********
Can one write the code with only one for loop?
5. Write a C++ program which calculates the sum 1/1 + 1/2 + 1/3 + 1/4 + ... + 1/N
where N is a positive integer. (for……)
#include <iostream>
using namespace std;
int main()
{
int n, i, m=0, flag=0;
cout << "Enter the Number to check Prime: ";
cin >> n;
m=n/2;
for(i = 2; i <= m; i++)
{
if(n % i == 0)
{
cout<<"Number is not Prime."<<endl;
flag=1;
break;
}
}
if (flag==0)
cout << "Number is Prime."<<endl;
return 0;
}
Output:
#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
return 0;
}
371 = (3*3*3)+(7*7*7)+(1*1*1)
where:
(3*3*3)=27
(7*7*7)=343
(1*1*1)=1
So:
27+343+1=371
#include <iostream>
using namespace std;
int main()
{
int n,r,sum=0,temp;
cout<<"Enter the Number= ";
cin>>n;
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
cout<<"Armstrong Number."<<endl;
else
cout<<"Not Armstrong Number."<<endl;
return 0;
}
11. Sum of digits program in C++(while)
include <iostream>
using namespace std;
int main()
{
int n,sum=0,m;
cout<<"Enter a number: ";
cin>>n;
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
cout<<"Sum is= "<<sum<<endl;
return 0;
}
12.C++ Program to reverse number(while)
include <iostream>
using namespace std;
int main()
{
int n, reverse=0, rem;
cout<<"Enter a number: ";
cin>>n;
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
cout<<"Reversed Number: "<<reverse<<endl;
return 0;
}
Output:
Syntax-1
goto label;
--------------
--------
---------
label: statement;
# include <iostream.h>
int main()
{
float num, average, sum = 0.0;
int i, n;
cout << "Maximum number of inputs: ";
cin >> n;
for(i = 1; i <= n; ++i)
{
cout << "Enter n" << i << ": ";
cin >> num;
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Maximum number of inputs: 10
Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6
Average = 3.95
Reason to Avoid goto Statement
The goto statement gives power to jump to any part of program but,
makes the logic of the program complex and tangled.
In modern programming, goto statement is considered a harmful
construct and a bad programming practice.
The goto statement can be replaced in most of C++ program with the use
of break and continue statements.
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
(ii)break
The break statement is extensively used in loops and switch statements.
A break statement immediately terminates the loop or the switch statement,
bypassing the remaining statements.
The control then passes to the statement that immediately follows the loop or
the switch statement.
A break statement can be used in any of the three C++ loops.
Note that a break statement used in a nested loop affects only the inner loop
in which it is used and not any of the outer loops.
Similarly, a break statement used in a switch statement breaks out of that
switch statement and not out of any loop that contains the switch statement.
Syntax:
break;
Example program
#include <iostream.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15)
{
// terminate the loop
break;
}
} while( a < 20 );
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Example program :1
// program to print the value of i
#include <iostream.h>
int main()
{
for (int i = 1; i <= 5; i++)
{
// condition to continue
if (i == 3)
{
continue;
}
cout << i << endl;
}
return 0;
}
Example program :2
// program to print the sum value of I except multiples of 5
#include <iostream.h>
int main()
{
int sum=0;
for (int i = 1; i <= 50; i++)
{
// condition to continue
if (i %5==0)
{
continue;
}
sum+=i;
}
cout <<“sum=“<< sum<<endl;
return 0;
}
Example program :3
// display sum of factors of a number
#include<iostream.h>
int main ()
{
int x=0, y, sum=0;
cout<<"Enter a number: ";
cin>>y;
while(1)
{
x++;
if (x>y)
break;
if(y%x!=0)
continue;
sum=sum+x;
}
cout<<"\n Sum of factors: "<<sum;
return 0;
}
Output
Enter a number: 8
Sum of factors: 15
Functions in C++
A large size program can be divided into smaller ones.
The smaller programs can be written in the form of functions.
The process of dividing a large program into small subprograms and manipulating
them independently is known as modular programming.
The concept of modular approach of C++is obtained from functions.
The advantages of functions are are,
Support for modular programming
Reduction in program size
Code duplication is avoided
Code reusability is provided
Functions can be called repetitively
A set of functions can be used to form libraries
C ++ program is a combination of one or more functions.
Execution of every C/C + + program starts with user defined function main().
C ++ supports two types of functions,
(i) Library function
(ii) User defined function
Library function can be used in any program by including respective header files
using #include
(ex) #include<string.h>
The programmer can also define their own functions for performing specific task.
such functions are called user-defined functions
the user defined functions defined in C++ are called member functions
__________________________________________________________
PARTS OF FUNCTION
A function is a group of statements that together perform a task.
Every C++ program has at least one function, which is main(), and all the most trivial programs
can define additional functions.
A function is known with various names like a method or a sub-routine or a procedure etc.
A function has 5 parts:
(a) function prototype declaration
(b) definition of your function (function declarator)
(c) function call
(d) actual and formal argument
(e) the return statement
The parameter list is optional hence we can have function to have the data type of each
parameter without mentioning the parameter
void show(void);
(b)Defining a Function
A function definition provides the actual body of the function The general form of
a C++ function definition is as follows −
In the function definition, the first line is called function declarator and is followed
by function body.
Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
Function Body − The function body contains a collection of statements that define
what the function does.
Syntax
function_name(argument_list);
For example –
max(a, b);
Syntax
return(variable name);
Or
return variable name;
Example Program:1
Example Program:2
#include <iostream.h>
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
OUTPUT:
Max value is : 200
Example Program:3
// program to check odd or even using function
#include <iostream.h>
#include <conio.h>
void main ()
{
void check(int);
// local variable declaration:
int a;
clrscr();
cout << "enter the number to check odd or even:
";
cin>>a;
// calling a function
check(a);
getch();
}
void check(int k)
{
if (k%2==0)
cout << "\n The number is even ";
else
cout << "\n The number is odd ";
}
OUTPUT:
enter the number to check odd or even:205
The number is odd
While calling a function, there are three ways that arguments can be passed
to a function −
1 Call 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.
2 Call by Pointer(address)
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
#include <iostream.h>
void fun(int a)
{
a=20;
}
int main()
{
int a =10;
fun(a);
cout<<"Value of A: "<<a<<endl;
return 0;
}
Output
Value of A: 10
#include <iostream>
using namespace std;
int main()
{
int a =10;
fun(a);
cout<<"Value of A: "<<a<<endl;
return 0;
}
Output
Value of A: 20
Consider the function definition (or declaration) void fun(int &b), while
calling the function fun(), reference of a will be passed in the function
body, whatever changes will be made in the function body, will change
the original value. Thus, value of a is changed and it is now 20 in main().
Another example
return 0;
}
The above code is put together in a file, compiled and executed, it produces the
following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
3) Pass by Reference
In case of pass by reference, we pass argument to the
function at calling position. That reflects changes into
parent function. Scope of modification is reflected in calling
function also.
The call by reference method of passing arguments to a function
copies the reference of an argument into the formal parameter.
Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the
functions just like any other value. So accordingly you need to
declare the function parameters as reference types as in the
following function swap(), which exchanges the values of the two
integer variables pointed to by its arguments.
#include <iostream>
using namespace std;
int main()
{
int a =10;
fun(&a);
cout<<"Value of A: "<<a<<endl;
return 0;
}
Output
Value of A: 20
Another example:
return;
}
#include <iostream.h>
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
Return by Reference
In C++ Programming, not only can you pass values by
reference to a function but you can also return a value by
reference.
Functions in C++ can return a reference as it’s returns a pointer.
A reference allows creating alias for the pre-existing variable.
A reference that returns reference variable is an alias for referred variable.
When function returns a reference it means it returns a implicit pointer.
Return by reference is very different from Call by reference. Functions
behaves a very important role when variable or pointers are returned as
reference.
See this function signature of Return by Reference Below:
dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
Example:
#include <iostream.h>
# include<conio.h>
void main()
{
clrscr();
int &min(int&j,int &k);
int a=18,b=11,c;
c=min(a,b);
cout<<“minimum value=“<<c;
getch();
}
int &min(int&j,int&k)
{
if(k<j ) return k;
else return j;
}
Output
minimum value=11
In this program, the statement int &min(int&j,int &k) declares prototype
of function min(). The & reference operator is used because the function
returns reference to int and also receives arguments as reference,. The
function min() receives two integers as reference and returns minimum
value out of two by reference
#include <iostream.h>
#include <conio.h>
int main ()
{
// function declaration:
int sum(int a, int b = 10, int c=15, int d=20);
// local variable declaration:
int a = 2;
int b = 3;
int c = 4;
int d = 5;
#include <iostream.h>
1. Write a program in C++ to show the 5. Write a program in C++ to find the
simple structure of a function. sum of the series
Expected Output : 1!/1+2!/2+3!/3+4!/4+5!/5 using the
function.
The total is : 11
Expected Output :
2. Write a program in C++ to find the The sum of the series is : 34
square of any number using the 6. Write a program in C++ to convert
function. decimal number to binary number
using the function.
Expected Output : Test Data :
Input any decimal number : 65
The square of 20 is : 400.00
Expected Output :
3. Write a program in C++ to swap two
numbers using function. The Binary value is : 1000001
Expected Output :
7. Write a program in C++ to check
Before swapping: n1 = 2, n2 = whether a number is a prime number
4
After swapping: n1 = 4, n2 = 2 or not using the function.
The number 5 is a prime
number.
4. Write a program in C++ to check a 8. Write a program in C++ to get the
given number is even or odd using the largest element of an array using the
function. function.
The entered number is odd. Test Data :
Input the number of elements to be
stored in the array :5 The perfect numbers between 1
to 100 are :
Input 5 elements in the array : 6 28
element - 0 : 1
element - 1 : 2 11. Write a program in C++ to check
element - 2 : 3 whether two given strings are an
element - 3 : 4 anagram.
element - 4 : 5 Test Data :
Expected Output : Input the first String : spare
Input the second String : pears
The largest element in the
array is : 5 Expected Output :
9. Write a program in C++ to check spare and pears are Anagram.
armstrong and perfect numbers using 12. Write a C++ programming to find
the function. out maximum and minimum of some
Test Data : values using function which will return
Input any number: 371 an array.
Expected Output : Test Data :
The 371 is an Armstrong Input 5 values
number. 25
The 371 is not a Perfect 11
number.
35
10. Write a program in C++ to print all
65
perfect numbers in given range using
20
the function.
Expected Output :
Test Data :
Input lowest search limit of perfect Number of values you want to
input: Input 5 values
numbers : 1 Minimum value is: 11
Input lowest search limit of perfect Maximum value is: 65
numbers : 100
Expected Output :
Syntax:
Example program:
#include<iostream.h>
# include<conio.h>
inline float square(float j)
{
return(j*j);
}
void main()
{
clrscr();
int p=4;
s=square(p);
cout<<”Square value:”<<s;
getch();
}
Output
Square value:16
Function Overloading
Defining member functions with the same name and different parameters
is known as function overloading or function polymorphism
Polymorphism means one function having many forms
The overloaded function must be different in its argument list and with
different data types
The function would perform different operation depending on the
argument list in the function call
The correct function to be invoked is determined by checking the number
and type of arguments
The examples of overloaded function are given below. All the functions
defined should be equivalent to their prototypes.
Principles of Overloading
1. If two functions have the similar type and the number of
arguments( data type), the function cannot be overloaded. The return
type may be similar or void, but argument data type or number of
arguments must be different.
For example,
sum(int,int,int);
sum(int,int);
these functions can be overloaded. Here the type of arguments
in both functions, but number of arguments are different.
sum(int,int,int);
sum(float,float, float);
these functions can be overloaded. Here the number of
arguments is same but the data types are different.
2. Passing constant values directly instead of variables result in
ambiguity. For example,
int sum(int,int);
float sum(float,float,float);
here sum() is an overloaded function for integer and float
values.
If values are passed as
sum(2,3);
sum(1.1,2.3);
the compiler will flag an error because the compiler cannot
distinguish between these two functions. Hence in both the above calls,
integer version of function sum() is executed.
LIBRARY FUNCTIONS
Mathematical Functions
Some of the important mathematical functions in header file <math.h> are
Function Meaning
sin(x) Sine of an angle x (measured in
radians)
cos(x) Cosine of an angle x (measured in
radians)
tan(x) Tangent of an angle x (measured in
radians)
asin(x) Sin-1 (x) where x (measured in
radians)
acos(x) Cos-1 (x) where x (measured in
radians)
exp(x) Exponential function of x (ex)
log(x) logarithm of x
log 10(x) Logarithm of number x to the base
10
sqrt(x) Square root of x
pow(x, y) x raised to the power y
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x
function
Function Meaning
isalpha(c) It returns True if C is an uppercase
letter and False if c is lowercase.
isdigit(c) It returns True if c is a digit (0 through
9) otherwise False.
isalnum(c) It returns True if c is a digit from 0
through 9 or an alphabetic character
(either uppercase or lowercase)
otherwise False.
islower(c) It returns True if C is a lowercase letter
otherwise False.
isupper(c) It returns True if C is an uppercase
letter otherwise False.
toupper(c) It converts c to uppercase letter.
tolower(c) It converts c to lowercase letter.
character Functions
All the character functions require <ctype.h> header file. The following table
lists the