Lab 8
Lab 8
Lab 8
PROCEDURE
1. In the lab students should complete both the “Examples” and “Lab Tasks”.
Before starting this lab, students should read/revise the lectures presented on given topics in the class.
Background Knowledge
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the code
once, and use it many times.
1. Create a Function
C++ provides some pre-defined functions, such as main (), which is used to execute code. But you can
also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():
Syntax
void myFunction ( ){
// code to be executed
}
Explanation
myFunction() is the name of the function
void means that the function does not have a return value. You will learn more about return
values later in the next chapter
inside the function (the body), add code that defines what the function should do.
Calling a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed
later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
Example
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction();
myFunction(); // call the function
myFunction();
return 0;
}
// Outputs "I just got executed!"
// Outputs "I just got executed!"
// Outputs "I just got executed!"
Example
Sum function
#include <iostream>
using namespace std;
/* This function adds two integer values
* and returns the result
*/
int sum(int num1, int num2)
{
int num3 = num1+num2;
return num3;
}
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)
Note: If a user-defined function, such as myFunction() is declared after the main() function, an error
will occur. It is because C++ works from top to bottom; which means that if the function is not declared
above main (), the program is unaware of it:
Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
Output
However, it is possible to separate the declaration and the definition of the function - for code
optimization. You will often see C++ programs that have function declaration above main(),
and function definition below main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Types of function
1) Built-in functions
Built-in functions are also known as library functions. We need not to declare and define these functions
as they are already written in the C++ libraries such as iostream, cmath etc. We can directly call them
when we need.
Example: C++ built-in function example
Here we are using built-in function pow(x,y) which is x to the power y. This function is declared in
cmath header file so we have included the file in our program using #include directive.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}
Output:
2) User-defined functions
We have already seen user-defined functions, the example we have given at the beginning of this tutorial
is an example of user-defined function. The functions that we declare and write in our programs are
user-defined functions. Let’s see another example of user-defined functions.
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);
int main(){
int x, y;
cout<<"enter first number: ";
cin>> x;
cout<<"enter second number: ";
cin>>y;
cout<<"Sum of these two :"<<sum(x,y);
return 0;
}
//Defining the function sum
int sum(int a, int b) {
int c = a+b;
return c;
}
Output
Example
// 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;
}
Note: Parameter names are not important in function declaration only their type is required,
so following is also valid declaration:
A global variable is a variable declared in the main body of the source code, outside all functions, while
a local variable is one declared within the body of a function or a block.
int rand(void):
returns a pseudo-random number in the range of 0 to RAND_MAX.
RAND_MAX: is a constant whose default value may vary
between implementations but it is granted to be at least 32767.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
int random = rand();
cout << "Seed = " << time(0) << endl;
cout << "Random number = " << random << endl;
return 0;
}
Lab Task
Task 1
1. Given the following function:
int square (int a)
{
a = a*a;
return a;
}
Write a C++ program that gets an integer n and invokes the function to compute its
square and displays this result
Task 2
Write a function that can find the average of four numbers in a double precision
floating point passed to the function as parameters. Write a C++ program
that inputs a double precision floating point numbers and invokes the above function to
find the average of all the numbers and displays it out.
Task 3
Using random function to generate any number between 1 and 6 randomly in C++.
Task 4
Write a function that swaps the values of two numbers passed to it as parameters. Get the values of
numbers from the user.
Conclusion