Lab 08 April11 - 2019
Lab 08 April11 - 2019
The general form of a function definition in C++ is as follows:
1 2 3
Parts Of Function
1‐ Type of the value that the function will return
2‐ Name of the function
3‐ Zero or more variables that becomes the input to the functions
4‐ Body of the function, contains the code which is executed when the function is called
5‐ The values that function wants to return
Key Note: When a function don’t want to return a value, it tells the compiler by means of void,
There can be following forms of a functions
A. Function with no return values and no arguments
B. Functions with arguments with no return value
C. Functions with return value with no arguments
D. Functions with return value and arguments
Example 1:
void DisplayMyName(void){
printf(”My Name is Ahmed\n”);
}
About this function:
Name: DisplayMyName
Return Type: void (The function will not return a value)
Parameter: void (The function will not take any parameters)
Body :{printf(”My Name is Ahmed\n”);}
CF‐Lab Exercise prepared by Nauman Shamim Page 1
Example 2:
void EvenOrOdd(int num){
if(num%2==0)
printf(”Even”);
else
printf(”Odd”);
}
Invalid Calls:
evenOrOdd(45) : Function name is incorrect
EvenOrOdd(23,34): Number of parameters mismatched
EvenOrOdd(“45”): Parameter Type mismatched
CF‐Lab Exercise prepared by Nauman Shamim Page 2
Task‐01
Try to identify the various parts of the following functions and valid function calls
Function-01
float DollaRate(void){
return 85.6;
}
Function -2
Task‐02
Look again at function in program-2 and try to understand what this function is doing,
expect what this function will do, write a program to use this function, compare expected
working of the function with actual output
Declaring and Using a Function
Following are two main approaches to define a function
1. Using a prototype
2. Without Prototype
Prototype: The prototype of a function is header of the function without its body, it is
necessary to define the type of the parameters, writing names of the parameters is
optional. To better understand the concept look at the following prototype
CF‐Lab Exercise prepared by Nauman Shamim Page 3
Example-3 (Approach 1):
#include<stdio.h>
#include<conio.h>
main(){
int a;
a=add(10,20);
printf(”Sum of 10 and 20 is %d”,a);
getch();
}
CF‐Lab Exercise prepared by Nauman Shamim Page 4
Q: Why use prototype?
To understand why prototyping is important look at the following program
void a(void){
Can we call function a() and b()
printf(“Function a”);
inside main() ? Yes as the prototype
b(); of b() is declared before a()
}
void b(void){
printf(“Function b”);
}
void main(){
a();
b();
}
Another Version
void a(void)
void b(void)
Prototype of functions a() and b() is
void main(){ declared before main, the program will
a(); try to locate the function inside header
b(); files, before main and after main.
}
void a(void){
printf(“Function a”);
b();
}
void b(void){
printf(“Function b”);
}
CF‐Lab Exercise prepared by Nauman Shamim Page 5
Important Point
Prototyping allows user to forget about the order in which functions are defined
Example ‐5 Using Functions to Write Better Programs
Let’s write a program that produces a good looking output for even odd problem.
#include<stdio.h>
#include<conio.h>
void printLine(void){
printf("\n**************************************************\n");
}
void main () {
int num;
printLine();
printf("Enter a Number :");
scanf("%d",&num);
if(num%2==0)
printf("Even Number");
else
printf("Odd Number");
printLine();
getch();
}
Output
************************************************
Enter a Number :13
Odd Number
************************************************
CF‐Lab Exercise prepared by Nauman Shamim Page 6
Example‐5A let’s add information about the author as well.
#include<stdio.h>
#include<conio.h>
void author(void){
printf("\nAuthor : ABCD\n");
printf("Date: 26-Nov-2015\n");
printf("About: Lives in Islamabad Pakistan\n");
printf("email : [email protected]\n");
}
void printLine(void){
printf("\n*************************************************\n");
}
void main () {
int num;
author();
printLine();
printf("Enter a Number :");
scanf("%d",&num);
if(num%2==0)
printf("Even Number");
else
printf("Odd Number");
printLine();
getch();
}
Output
Author : ABCD
Date: 26-Nov-2015
About: Lives in Islamabad Pakistan
email : [email protected]
***********************************
Enter a Number :13
Odd Number
***********************************
CF‐Lab Exercise prepared by Nauman Shamim Page 7
Task‐03
1. Write a program that calls print line function 5 times using a loop.
2. Modify the example-5A and add a new function void evenOdd(int), the function
should print even or odd according to the number passed. Update the program to
use this function
3. Write a program that prints the status of 10 numbers as even or odd using your
evenOdd() function, the numbers can be as simple as 1-10 or can be between two
numbers A and B provided by the user.
Tasks‐04
1. Write a function pow() which takes two integer parameters a and n and returns nth
power of a, write a program to use this function.
2. Write a function that returns the greater of the two numbers i.e. make a function
that takes two integer arguments and returns the greater of the two. Write program
to use this function.
Task‐05
Try to write the following functions and programs
CF‐Lab Exercise prepared by Nauman Shamim Page 8
Use the function
Write a program that will ask user to enter length and width of a shape and will inform the
user weather the shape is a rectangle or a square.
Extension
Develop a program that will use the functions areaRect() and isSquare(), the program will
ask user to enter two integer values as length and width of a shape, the program will
display type of shape i.e. square or rectangle and will display the area of the shape as well.
Try implementing the following functions that are already available in header file
string.h
1. int strlen(char str[])
The function should return the length of the string passed. The character passed
should must be null terminated
CF‐Lab Exercise prepared by Nauman Shamim Page 9
Lab‐10
Topics covered in this lab
1. Calling Function Inside Other Functions
2. Returning Values From Function
3. Functions With Default Arguments
Calling Functions Inside Other Functions
When know that main is a function , also printf is a function, when we call printf inside main we actually
call a function inside another function. Same can be done with user defined functions. See example
below.
void main(){
printf(“The date today is :”);
printDate(29,12,2016);
Making functions work together makes the task easy to solve and provides flexibility to perform multiple
tasks from same functions. In above example the two functions printDay and printMonth can be used
saperately to print any day or month or can be used in printDate
CF‐Lab Exercise prepared by Nauman Shamim Page 1
Task‐01, Print Calendar
Modify the above program and add another function, printCalander(int month) the function should get
only one argument i.e. month as integer and should print all the dates of that month with day names
(year can be fixed or skipped)
Task‐02 , Reverse a Number
Try to understand the following program, and write a function to isPalindrome (int num) using these
functions , a palindrome is a number that reads the same from left to right or from right to left. For
example 121 , 222, 62226 are all palindrome numbers.
#include <stdio.h>
int trim(int a){
return a/10;
}
int digit(int a){
return a%10;
}
int reverse(int a){
int result=0;
while(a!=0){
result=result*10+digit(a);
a=trim(a);
}
return result;
}
void main () {
int num=234;
printf(“\n%d",reverse(num));
printf(“\n%d”,reverse(num));
getch();
}
Task‐03
Try to write the following functions using the trim and digit function given above
1‐printLength(int num) :Should print the length of the number provided
2‐printMiddleDigit(int num) : should print the digit which lies in the middle of the given number, in case
the length of the number is even you may choose to select length/2 or length/2+1 as middle digit
CF‐Lab Exercise prepared by Nauman Shamim Page 2
Returning Values from Functions
A function when called should must return to the caller , such as when printf is called inside
main after printing the printf function comes back to main and the line next to printf is
executed. A function may return in three ways as given below
1. When all lines of the functions are executed
2. Using a return keyword
3. Using a return keyword and a value
Example‐1
void printDay(int day){
char days[]={“mon”,”tue”,”wed”,”thu”,”fri”,”sat”,”sun”};
printf(“%s”,days[day%7]);
}
The function returns after printf(“%s”,days[day%7]);statement
Example‐2
CF‐Lab Exercise prepared by Nauman Shamim Page 3
Task‐04
A stack is a container of objects such that objects are placed on top of each other just like
dishes are placed on top of each other. If an object is added to the stack it is placed on top of
the already present objects, if an object is to be removed from the stack it will be removed
from the top, so to remove the last object in the stack one has to remove all top objects.
In this activity we have to demonstrate the working of stack by using a global array of integers
and the following functions. Follow the instruction and try to complete the task
1‐ 1‐Write a program that declares a global array of 10 integers, name this array as stack.
2‐ Write the following functions
a. void push(int a): this function should put the value of variable a in front of the array
i.e. at index 0 (always)
b. int pop(void) : this function should return the first element of the array i.e. element
at index 0 (always), the element will also be removed from the array
c. void shift_right(void) : this function should shift the elements of the array 1 place
toward right i.e. element at index 0 will move to index 1 , element at index 1 will
move to index 2 and so on till the last array element is processed
d. void shift_left(void) : this function should shift the elements of the array 1 place
towards left i.e. element at index 1 will be shifted to index 0, element at index 2 will
be shifted to index 1
e. void show(void): the function should display the contents of the array stack
3‐ Write a program that offers following choices to the user
1‐push
2‐pop
3‐show
4‐exit
4‐ In case user selects choice 1, the program should get a number from the user and place it in
the array stack using push()
CF‐Lab Exercise prepared by Nauman Shamim Page 4
5‐ In case user selects choice 2, the program should call the function pop and display the
number returned
6‐ In case user selects choice‐3 the program should display the contents of the stack as a
vertical list
7‐ To push a number you might need to shift the array towards right , use function push_right
8‐ To pop a number you might need to shift the array towards left, use function push_left
9‐ You should put suitable conditions such that no more than 10 elements are pushed in the
array stack , in such a case a suitable message such that “stack is full” be displayed
10‐ You should also put suitable conditions such that if there is no element in the array the pop
should display suitable message such as “empty stack”.
CF‐Lab Exercise prepared by Nauman Shamim Page 5
Lab‐11
Scope of a Variable
Scope of a variable defines in which part of the program the variable is accessible. Depending upon the
scope of variable C/C++ variables can be categorized into following classes
1. Local
2. Global
Life of a variable
Not all variables have same life during the execution of a program some variables are short lived while
others exists till the end of the program , life of a variable is also termed as longevity of a variable.
According to the longevity C/C++ variable can be categorized into following classes
1. Automatic or Auto
2. Static
Local Variables :
All variables declared inside a function are local to that function , i.e. can only be used inside that
function and cannot be used in any other function, see the example below
Example Local Variables
int sum(int a, int b){
int s=a+b;
a=0;
b=0;
printf("\nInside sum function");
printf("\n a = %d",a);
printf("\n b = %d",b);
return s;
}
void main(){
Output
int a=10;
Inside sum function
int b=20;
a = 0
int c;
b = 0
c=sum(a,b);
Inside main function
printf("\nInside main function");
a = 10
printf("\n a = %d",a);
b = 20
printf("\n b = %d",b);
Sum of a and b = 30
printf("\nSum of a and b = %d",c);
getch();
}
Integer variables a and b are declared in both the functions i.e. main and sum however these
are not same variables, any variable declared in sum is not visible inside main and vice versa.
Important Concept : In this example modifying a and b inside sum has not changed the values
of a and b in main .
CF‐Lab Exercise prepared by Nauman Shamim Page 1
Global Variables
1. Also called external variables, all variable declared outside any function are accessible to all
functions define after these variables , hence called global variables
For the following programs, you need to include the header files
Example Global Variables
int count;
void A(){
count++;
printf("\n A() is Called ");
printf("\nTotal function calls: %d",count);
}
void B(){
count++;
printf("\n B() is called");
printf("\nTotal function calls: %d",count);
}
void main(){
count=0;
A();
A();
B();
B();
printf("\n\n\nResetting the counter to zero i.e. count=0\n\n");
count=0;
A();
B(); Output
getch(); A() is Called
} Total function calls: 1
A() is Called
Total function calls: 2
Concept: The variable count is shared among all B() is called
Total function calls: 3
the functions, see it is modified in three functions B() is called
and the modified value is available to all the Total function calls: 4
functions
Resetting the counter to zero i.e.
count=0
Note: A global variable is accessible to functions
that are defined after its declaration A() is Called
Total function calls: 1
B() is called
Question: Total function calls: 2
Can there be a local and a global variable of same name?
Ans: Yes, if a function has a variable whose name is same as previously declared global variable, then
the local variable will take precedence inside such a function see example below
CF‐Lab Exercise prepared by Nauman Shamim Page 2
#include<stdio.h>
#include<conio.h>
int x=10;
int fun1() {
x=x+10; //The global variable x
return x;
}
int fun2(){
int x=5;
x=x+10; //Local variable x
return x;
}
int main(){
//Only global variable can be accessed in other functions Output
//The following line will print value of global variable x Value of x=10
printf(“Value of x=%d\n”,x); Value of x=20
Value of x=15
//fun1 modifies and returns value of global variable
printf(“Value of x=%d\n”,fun1());
//fun2 modifies and returns value of its local variable
printf(“Value of x=%d\n”,fun2());
getch();
}
Static Variables
A static variable is a variable whose life time is entire program, once the variable is created it is not
destroyed till the program is finished. A static variable can be global or local.
Example static Variables
void A(){
staticint count_a=0;
count_a++;
printf("\nNo of calls to A() =%d",count_a);
}
void B(){
staticint count_b=0;
count_b++;
printf("\nNo of calls to B() =%d",count_b);
}
CF‐Lab Exercise prepared by Nauman Shamim Page 3
Output
void main(){
int i; Multiple Calls to A()
No of calls to A() =1
printf("\n Multiple Calls to A()\n");
No of calls to A() =2
No of calls to A() =3
for(i=0;i<4;i++) No of calls to A() =4
A();
Multiple Calls to B()
printf("\n\nMultiple Calls to B()"); No of calls to B() =1
No of calls to B() =2
No of calls to B() =3
for(i=0;i<6;i++)
No of calls to B() =4
B(); No of calls to B() =5
No of calls to B() =6
getch();
}
Concept: The two static variables count_a and count_b are created only once, i.e. the
statement int count_a=0 ; and int count_b=0; is executed only once because the variables are
not destroyed when the function calls A() or B() are finished, the variables will be destroyed
only when the program is finished.
Auto Variables
Variables that are automatically created and automatically destroyed are called automatic or auto
variables. Non‐static variables that are declared inside a function are automatically created and
destroyed so non‐static local variables are auto variables.
Note: Not all local variables are auto or automatic variables, the concept will become clear after
understanding static variables
Task‐01
In the above examples static variables have been used to count the number of calls to
individual functions, use global variables to do the same, instead of printing the number of calls
inside the function print the total numbers of calls to each function at the end of your main
function. For example if A() is called 7 times, B() is called 3 times , the following should be
printed in main.
Total calls to A() = 7
Total calls to B() =3
Total number of function calls =10
CF‐Lab Exercise prepared by Nauman Shamim Page 4
Task‐02
Declare a global array of 10 integers name, declare a variable size that will store the size of the
array, now write the following functions.
1. void PrintArray(void) : This function should print the global array
2. void SumArray(void): This function should print the sum of all elements of the array
Recursive Function
A function that calls itself inside its body is called a recursive function
Example
void printSeries(int num){
if(num<=0)
return;
printf(“ %d “,num);
printSeries(num‐1);
}
The above functions prints all the number between zero and a given number that is greater
than zero.
Task‐03
1. Just to warm up , write a recursive function printEven(int num) that prints all the even
number between zero and a given number
2. Modify the printEven(int num) function and make it a recursive function that can print
all the even numbers between two given numbers A and B where A is smaller than B
3. Write a function divisor(int num), the number should print all the positive divisors of the
given number num first write a non‐recursive version later write a recursive function
4. Write a recursive function fact(int num), that should return the factorial of given
number num
5. Write a recursive function that can print first N terms of following Fibonacci series ,
define the number and type of parameters that should be passed to your function
0 1 1 2 3 5 8 13 . . .
CF‐Lab Exercise prepared by Nauman Shamim Page 5