Lab 8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Lab 8

USE OF FUNCTIONS IN C++

PROCEDURE

1. In the lab students should complete both the “Examples” and “Lab Tasks”.

PRE-LAB READING ASSIGNMENTS

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

Inside main, call myFunction():

// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"

A function can be called multiple times as shown below:

Example

Inside main, call myFunction():

// 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;
}

Function Declaration and Definition

A C++ function consist of two parts:

 Declaration: the function's name, return type, and parameters (if any)
 Definition: the body of the function (code to be executed)

void myFunction() { // declaration


// the body of the function (definition)
}

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

We have two types of function in C++:


1) Built-in functions
2) User-defined functions

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:

int max (int, int);


Local and Global variables

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.

Example for local and global variables


// C++ program to show that we can access a global
// variable using scope resolution operator :: when
// there is a local variable with same name
#include<iostream>
using namespace std;
// Global x
int x = 0;
int main()
{
// Local x
int x = 10;
cout << "Value of global x is " << ::x;
cout<< "\nValue of local x is " << x;
return 0;
}
Output:

rand() and srand() in C++


rand() function is used in C++ to generate random numbers. If we generate a sequence of
random number with rand() function, it will create the same sequence again and again
every time program runs. Say if we are generating 5 random numbers in C++ with the help
of rand() in a loop, then every time we compile and run the program our output must be
the same sequence of numbers.
Syntax:

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.

// C++ program to generate random numbers


#include <stdio>
#include <stdlib>
// Driver program
int main(void)
{
// This program will create same sequence of
// random numbers on every program run
for(int i = 0; i<5; i++)
cout<< rand();
return 0;
}
srand() prototype
void srand(unsigned int seed);
The srand() function takes an unsigned integer as its parameter which is used as seed
by the rand() function.
It is defined in <cstdlib> header file.

Example : How srand() function works?


#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int random = rand();
/* No srand() calls before rand(), so seed = 1*/
cout << "Seed = 1, Random number = " << random << endl;
srand(5);
/* Seed = 5 */
random = rand();
cout << "Seed = 5, Random number = " << random << endl;
return 0;
}

Example : srand() function with time()

#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

You might also like