0% found this document useful (0 votes)
4 views

Lab Manual Functions

The document is a lab manual for Programming Fundamentals at the University of Management and Technology, focusing on functions and recursion. It outlines objectives, concepts, and various programming exercises to help students understand user-defined functions, their declarations, definitions, and the concept of recursion. The manual includes coding examples and explanations for different types of functions and their applications.

Uploaded by

usmanqasim845
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab Manual Functions

The document is a lab manual for Programming Fundamentals at the University of Management and Technology, focusing on functions and recursion. It outlines objectives, concepts, and various programming exercises to help students understand user-defined functions, their declarations, definitions, and the concept of recursion. The manual includes coding examples and explanations for different types of functions and their applications.

Uploaded by

usmanqasim845
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Lab Manual: Programming Fundamentals

University of Management and


Technology, Lahore Campus

Lab- 09 Manual
Lab Instructor: Syed Wajid Ali
Department of AI
Email: [email protected]
Lab 09: Functions and Recursion
Lab Rubrics

Identify key programming


Areas Problem Understanding structures such as Design/ Development of Solutions
Assessed variables, loops, and
functions.
(CLO 1) (CLO 2) (CLO 3)
No able to identify key
Not able to understand Not able to Model a solution for a
Poor programming structures such
Problem given problem
as variables, loops, and
functions.

Partially able identify Modeled an average solution


Able to partially understand
Average key programming for a given problem using
the problem
structures such as programming principles
variables, loops, and
functions.

Thoroughly identify key


Modeled a proper solution for a
Very Good Fully Understand the problem programming structures
given problem using programming
such as variables, loops,
principles
and functions.

Functions
1. Objective:

Learn how to write user defined functions which do not return value OR can return
single value.

2. Scope:

The student should know the following:


Lab Manual: Programming Fundamentals
 Functions which neither accept any argument nor return any value
 Functions which accept arguments but do not return any value
 Functions which accept arguments and return a single result.

3. Useful Concepts:

4. Basic Concepts about Function :


A function is a block of code that performs a task. The statements written in a function
are executed when
it is called by its name. The functions provide a structured programming approach. It is a
modular way of writing programs. The whole program logic is divided into a number of
smaller modules or functions. The main function calls these function when they are
needed to execute.

NOTE: The program should always have a main function whether it has other function
or not. Without the main function the program will not do anything as the program
always starts from the main function.

Why functions are important?

The program may need to repeat the same piece of code at various places or it may
require repeating same task again and again. The program may become very large and
messy if we do not divide it into sub programs (functions). The piece of code that is
executed repeatedly is stored in a separate function, and is called when and where it is
required.

Functions can be divided in to:

1. Built- in Functions:

A type of function that is available as a part of language is known as built-in


function or library function. These functions are stored in different header files
e.g. sqrt() is a built-in function to compute the square root and it is part of header
file called “cmath”.

Function can further be distinguished as:


 Functions returning no value and accepting no arguments.
 Function returning no value but accepting one or more arguments.
 Function returning one value and accepting one or more arguments.
Lab Manual: Programming Fundamentals
2. User Defined Functions:
Functions written by programmers are called user-defined functions. A user-
defined function consists of the following:
 Function declaration or function prototype
 Function definition

Functions Declaration or Function Prototype:


Function declaration provides information to compiler about the structure of the function
to be used in program. It ends with a semi colon. Function prototypes are usually placed
at the beginning of the source file before the main function. Function prototype consists
of the following:
 Function return type
 Function name
 Number and types of parameters (Optional)
Syntax:
Return-type Function-name (Parameter list (optional));

Examples:
1. The function show neither accepts any argument nor returns any
value.
Function name No parameters
void indicates no return
type void show ( );

2. The function alpha accepts a character type argument and returns no


value.

Function name char indicates character parameter


void indicates no return
type void
alpha(char);
Lab Manual: Programming Fundamentals

3. The function beta accepts a character type argument and returns a


character value.
Function name char indicates character
char indicates character return parameter
type char beta (char);

4. The function fact has no argument but returns an integer value.


Function name No
int indicates integer parameter
return type int fact ( );

5. The function sum accepts two integer type arguments and returns an
integer value.
Function name int indicates integer
int indicates integer parameters
return type int sum (int,int);

Functions Definition:
A set of statements that explains what a function does is called function
definition. The function definition can be written at the following places.
 Before main function
 After main function
Function declaration is not required if the function definition is written before main
function. Function declaration is compulsory if function definition is written after main
function. The function definition consists of two parts:

Functions Header:

The first line of function definition is called function header. It is similar to


function prototype except that it is not terminated with semicolon. The number and
sequence of parameter in function header must be same as that of function prototype.
Lab Manual: Programming Fundamentals

Functions Body:
The set of statements written inside the function are called function body. The
body of the function appears after function header and the statements are enclosed in
curly braces { }.

Syntax:

Return-type Function-Name
Function header
(Parameters)
{
Statement 1;
Statement 2;
Function body

Statement n;
return statement (optional);
}

Functions Call:

The statement that activates a function is called function call. A function is called with its
name followed by required parameters in parenthesis “( ) “. If there are many
parameters, these are separated by comas. If there are no parameter, empty parenthesis
are used. Following steps show the process of function call.

 The control moves to the function that is called.


 All the statements in that function body are executed.
 The control returns back to the calling function.
 The rest of the body of calling function is executed.

Passing Parameters to Functions:


The values passed to the function at the time of function call are called parameters.
Parameters are written in the parenthesis. If there are more than one parameter, these are
separated by commas. Both variables and constants can be passed to function as
Lab Manual: Programming Fundamentals
parameters. The sequence and type of parameters in function call must be similar to the
sequence and type of parameters in function declaration.

 Parameters in function declaration or function header are called formal


parameters.
 Parameters in function call are called actual parameters.

Passing Parameters by Value:

In pass by value the value of actual parameter is copied to formal parameters. If the function
makes any changes in formal parameters, it does not affect the values of actual parameter.

Passing Parameters by Reference:

In pass by reference method, the memory address of actual parameter is passed to the
function. The formal parameter becomes second name for actual parameter. Formal parameter
does not occupy separate memory, it means both actual and formal parameters refer to the same
memory location. If the function makes any changes in formal parameters, the change is also
reflected in actual parameter.

Returning Value from Functions:

A function can return a single value. The return type in function declaration indicates the type of
value returned by a function. The keyword return is used to return the value back to the calling
function. When the return statement is executed in a function, the control moves back to the
calling function along with the returned value.

Program #1: Display a simple message using the function.


coding:
#include <iostream>
using namespace std;
void displayMessage()
{
cout<<"Hello from the function diplayMessage. \n";
}
int main()
{
cout<<"Hello from main.\n";
displayMessage();
cout<<"Back in function main again.\n";
return 0;
}
Lab Manual: Programming Fundamentals

Program # 2: Display a simple message using the function and call a function
using for loop.
Coding by using for loop:
#include <iostream>
using namespace std;
void displayMessage()
{
cout<<"Hello from the function diplayMessage. \n";
}
int main()
{
cout<<"Hello from main.\n";
for(int i=1;i<=10;i++)
{
displayMessage();
}
cout<<"Back in function main again.\n";
return 0;
}

Program # 3: Display a simple message using the function and call a function
using while loop.
Coding by using while loop:
#include <iostream>
using namespace std;
void displayMessage()
{
cout<<"Hello from the function diplayMessage. \n";
}
int main()
{
cout<<"Hello from main.\n";
int i=1;
while (i<=10)
{
displayMessage ();
i++;
}
Lab Manual: Programming Fundamentals
cout<<"Back in function main again.\n";
return 0;
}

Program # 4: Write program to show the one number by using function.


Coding:
#include <iostream>
using namespace std;
void displayValue(int num)
{
cout<<"The number is " <<num <<endl;
}
int main()
{
cout<<"I am passing 5 to displyValue. \n";
displayValue(5);
cout<<"Now back in main function.\n";
return 0;
}

Program # 5: Write program to show the one number by using function.


Coding:
#include <iostream>
using namespace std;
void displayValue(int firstNum,int secondNum)
{
cout<<"The First Number is "<<firstNum <<endl <<"The Second Number is
"<<secondNum <<endl;
}

int main()
{
cout<<"I am passing 5 and 6 to displyValue. \n";
displayValue(5,6);
cout<<"Now back in main function.\n";
return 0;
}
Lab Manual: Programming Fundamentals

Function Prototype
Program #6:
Coding:
#include <iostream>
using namespace std;
void first();
void second();
int main()
{
cout<<"I am starting in function main. \n";
first();
second();
cout<<"Back in function main again.\n";
return 0;
}
void first()
{
cout<<"Hello from first.\n";
}
void second()
{
cout<<"Hello from second.\n"; }
Program #7:Write a program to show one number by using
the function Prototype.
coding:
#include <iostream>
using namespace std;
void displayValue(int);
int main()
{
cout<<"I am passing 5 to displyValue. \n";
displayValue(5);
cout<<"Now back in main function.\n";
return 0;
}
void displayValue(int num)
Lab Manual: Programming Fundamentals
{
cout<<"The number is " <<num <<endl;
}

Program #8: Write a program to execute the sum of three numbers


by using a Function prototype.
Coding:
#include <iostream>
using namespace std;
void showSum(int ,int,int);
int main()
{
int value1,value2,value3;
cout<<"Enter three integers and i will display their sum ";
cin>>value1>>value2>>value3;
showSum(value1,value2,value3);
return 0;
}
void showSum(int value1,int value2,int value3)
{
int sum;
sum=value1+value2+value3;
cout<<"The sum is "<<sum;
}
Program #9: Write a program to divide the two numbers by using Functions
and check that if second number is zero then the program is terminated.
#include <iostream>
using namespace std;
void divide(double,double);
int main()
{
double num1,num2;
cout<<"Enter the first number: \n";
cin>>num1;
cout<<"number the second number: ";
cin>>num2;
divide(num1,num2);
return 0;
}
Lab Manual: Programming Fundamentals
void divide(double num1,double num2)
{
if(num2==0)
{
cout<<"I cannot divide by zero";
return;
}
cout<<"The number is "<<(num1/num2);
}

Program #10:
Write a program that contains a function that takes two arguments of
integer types and displays their quotient.
#include <iostream>
using namespace std;
int quotient(int, int); // Function Prototype
int main()
{
int one,two, quot;
cout<<"Enter two integers: ";
cin>>one>>two;
quot = quotient(one, two); // Function Call
cout<<"Quotient = "<<quot<<endl; return 0;
}
int quotient(int one, int two) // Function Definition
{
int q = one/two;
return q;}
Program #11:
C++ Program to Calculate Square of a Number using Functions
#include<iostream>
using namespace std;
int calculateSquare(int number)
{
return number * number;
}

int main()
{
int number, square;
Lab Manual: Programming Fundamentals
cout << "\nPlease Enter Number to find Square of it = ";
cin >> number;

square = calculateSquare(number);

cout << "\nThe Square of the Given " << number << " = " << square;

return 0;
}

Program #12:
C++ Program to Calculate Square of ten numbers using Functions.
#include<iostream>
using namespace std;

int calculateSquare(int number)


{
return number * number;
}
int main()
{
int number, square;

for (number=1;number<=10;number++)
{
square = calculateSquare(number);
cout << "\nThe Square of the Given " << number << " = " << square;
}
return 0;
}
Program #13:
Write a program that inputs two integers in main ( ) and passes the integers
to swap( ) by value. The swap( ) exchanges the values. The main( ) should
display the values before and after swapping.

#include <iostream>
using namespace std;
void swap_value(int, int);
Lab Manual: Programming Fundamentals
int main()
{
int one,two;
cout<<"Enter two integers: ";
cin>>one>>two;
cout<<"Before Swap: "<<one<<" and "<<two<<endl;
swap_value(one, two);
cout<<"After Swap: "<<one<<" and "<<two<<endl;
return 0;
}

void swap_value(int one, int two)


{
cout<<"Entering Swap: "<<one<<" and "<<two<<endl;
int temp;
temp = one;
one = two;
two = temp;
cout<<"Exiting Swap: "<<one<<" and "<<two<<endl;
}

Pass by Reference
Program #14:

#include <iostream>
using namespace std;
void f(int & x)
{
x = x+2;
cout << x << endl;
Lab Manual: Programming Fundamentals
}

// Driver code
int main()
{
int a = 5;
cout << a << endl;
f(a);
cout << a << endl;
}

Program #15: Write a program that inputs two integers in main ( ) and
passes the integers to swap( ) by reference. The swap( ) exchanges the
values. The main( ) should display the values before and after swapping.

#include <iostream>
using namespace std;
void swap_ref(int&, int&);

int main()
{
int one,two;
cout<<"Enter two integers: ";
cin>>one>>two;
cout<<"Before Swap: "<<one<<" and "<<two<<endl;
swap_ref(one, two);
cout<<"After Swap: "<<one<<" and "<<two<<endl;
return 0;
}
Lab Manual: Programming Fundamentals
void swap_ref(int& one, int& two)
{
cout<<"Entering Swap: "<<one<<" and "<<two<<endl;
int temp;
temp = one;
one = two;
two = temp;
cout<<"Exiting Swap: "<<one<<" and "<<two<<endl;
}

Recursion
Recursion is a programming and mathematical concept where a function or algorithm calls
itself as part of its execution. In simpler terms, it's a process where a problem is solved by
breaking it down into smaller, similar sub-problems, and the solution to each sub-problem is
found by calling the same function recursively.
Lab Manual: Programming Fundamentals

Program #16:
Fibonacci Series Using Recursion in C++
Fibonacci number series is the sequence of numbers such that each number
is the sum of the two preceding ones starting from zero(0) and one(1).
#include <iostream>
using namespace std;
int fibonnaci(int x)
{
if((x==1)||(x==0))
{
return(x);
}
else
{
return(fibonnaci(x-1)+fibonnaci(x-2));
}
}
int main()
{
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x)
{
cout << " " << fibonnaci(i);
i++;
}
return 0;
Lab Manual: Programming Fundamentals
}

Program #17:
Factorial Program Using Recursion In C++
Factorial is the product of an integer and all other integers below it. For
example, the factorial of 5 (5!) is equal to 5x4x3x2x1 i.e. 120.
#include <iostream>
using namespace std;

int fact(int n);

int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factorial of " << n << " = " << fact(n);
return 0;
}

int fact(int n)
{
if(n > 1)
return n * fact(n - 1);
else
return 1;
}

Program #18:
Program To Calculate Number Power Using Recursion In C++
Lab Manual: Programming Fundamentals
In this program, we will calculate the power of the number using the
recursion approach where the base and exponent is taken as input by the
user.
#include <iostream>
using namespace std;

int calculate(int, int);

int main()
{
int base, power, result;

cout << "Enter base number: ";


cin >> base;

cout << "Enter power number(positive integer): ";


cin >> power;

result = calculate(base, power);


cout << base << "^" << power << " = " << result;

return 0;
}

int calculate(int base, int power)


{
if (power != 0)
return (base*calculate(base, power-1));
else
return 1;
}
Lab Manual: Programming Fundamentals

Tasks
Task 1: Write a Program in c++ in which you need to implement a function Factorial() by
using Recursion.
For Example: Factorial of 5 is 1*2*3*4*5=120
Task 2: Write a Program in c++ in which you need to implement a function () by using
Recursion.
Task 3: Basic Pass by Value Calculation
Write a function calculateArea that takes two parameters, length and width, and returns the
area of a rectangle. The function should not modify the original values of length and width.
Task:
 Implement a calculateArea function that demonstrates pass by value.
 Call the function and print the calculated area without affecting the original
variables.
Example:

Task 4: Complex Calculation with Pass by Value


Create a program where you simulate a simple tax calculation system. Write a function
calculateSalary that accepts the baseSalary, taxRate, and deductions. The function should
return the final salary after applying the tax and deductions, but should not modify any of
the original arguments.
Task:
 Write a function that takes the base salary, tax rate, and deductions by value, and
computes the final salary.
 Ensure that the original values of baseSalary, taxRate, and deductions remain
unchanged after calling the function.
Example:

Task 5: Swapping Two Variables


Write a function swapNumbers that swaps two numbers using pass by reference. After calling
the function, the values of the two variables should be exchanged.
Task:
 Implement a swapNumbers function that takes two integers by reference and swaps
their values.
 Ensure that the values are modified in the calling function.
Lab Manual: Programming Fundamentals
Example:

Task 6: Sorting Array in Ascending Order


Write a function sortArray that takes an array of integers and its size by reference. Use pass
by reference to modify the original array so that it is sorted in ascending order.
Task:
 Write a sortArray function that uses a sorting algorithm (e.g., Bubble Sort or Selection
Sort) to modify the original array.
 Use pass by reference so that the array in the main function is updated after sorting.
Example:

Task 7: Prime Number Checker


Write a simple function isPrime that takes an integer and returns true if the number is prime
and false otherwise.
Task:
 Implement a simple isPrime function.
 Call the function to check if a number is prime and output the result.
Example:

Task 8: Fibonacci Series Generator


Write a function generateFibonacci that takes an integer n and returns the first n numbers of
the Fibonacci sequence in an array. The function should generate the Fibonacci series without
recursion.
Task:
Lab Manual: Programming Fundamentals
 Implement the generateFibonacci function that returns the Fibonacci series up to the
nth term.
 Output the series in the main function.
Example:

You might also like