0% found this document useful (0 votes)
114 views8 pages

Lab 07: Functions: National University of Technology

The document discusses functions in C++ programming. It explains that functions group statements together to perform tasks and can be called from different parts of a program. The key components of a function are: [1] A declaration that specifies the function name and parameters; [2] Calling the function; and [3] The function definition that contains the code. Functions can take arguments using call by value or call by reference, and recursive functions call themselves repeatedly until a condition is met. The lab tasks practice writing functions to compare numbers, convert units, perform calculations, swap values, and calculate sums recursively.

Uploaded by

R k
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)
114 views8 pages

Lab 07: Functions: National University of Technology

The document discusses functions in C++ programming. It explains that functions group statements together to perform tasks and can be called from different parts of a program. The key components of a function are: [1] A declaration that specifies the function name and parameters; [2] Calling the function; and [3] The function definition that contains the code. Functions can take arguments using call by value or call by reference, and recursive functions call themselves repeatedly until a condition is met. The lab tasks practice writing functions to compare numbers, convert units, perform calculations, swap values, and calculate sums recursively.

Uploaded by

R k
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/ 8

National University of Technology

Electrical Engineering Department

EE-1004: Introduction to Computer Programing Semester: IV

Lab 07: FUNCTIONS

Learning objectives

 Brief understanding Functions, built in and user defined functions.


 Understanding how to declare and call a function.
 Familiarization different methods to pass value as an argument to function.
 Understanding the flow of recursive functions.

Group:

Date of Experiment:

Instructor’s Signature:
Description

A function groups a number of program statements into a unit and gives it a name. This unit can then
be invoked from other parts of the program. A function is a complete and independent program. It is
executed by main function or any other function of the program to perform its task.

Functions in C++ (and C) are similar to subroutines and procedures in various other languages.

Any sequence of instructions that appears in a program more than once is a candidate for being
made into a function. The function’s code is stored in only one place in memory, even though the
function is executed many times in the course of the program.

Figure: Flow of control to function

Simple Functions

Our first example demonstrates a simple function whose purpose is to print a line of 45 asterisks. The
example program generates a table, and lines of asterisks are used to make the table more readable.
Here’s the listing for TABLE:

// demonstrates simple function

#include<iostream>
using namespace std;

void starline(); // function declaration // declaration also called prototype


int main()
{
starline(); //call to function
cout<< “Data type Range” << endl;
starline(); //call to function

cout<< “char -128 to 127” << endl;


cout<< “short -32,768 to 32,767” << endl;
cout<< “int System dependent” << endl;
cout<< “long -2,147,483,648 to 2,147,483,647” << endl;
starline(); //call to function
return 0;
}

//--------------------------------------------------------------
// starline()
// function definition

voidstarline()
{
for(int j=0; j&lt45; j++) //function body
cout<< ‘*’;
cout<< endl;
}

Program consists of two functions: main() and starline(). You’ve already seen main() alone. What
other components are necessary to add a function to the program? functiondeclaration, the calls to
the function, and the function definition.

The Function Declaration

Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a
function without telling the compiler about it. There are two ways to do this. The approach we show
here is to declare the function before it is called.

(The other approach is to define it before it’s called; we’ll examine that next.). In the TABLE program,
the function starline() is declared in the line

voidstarline();

The declaration tells the compiler that at some later point we plan to present a function called starline.
The keyword void specifies that the function has no return value, and the empty parentheses indicate
that it takes no arguments.
(You can also use the keyword void in parentheses to indicate that the functiontakes no arguments,
as is often done in C, but leaving them empty is the more common practice in C++.)

We’ll have more to say about arguments and return values soon. Notice that the function declaration
is terminated with a semicolon. It is a complete statement in itself. Function declarations are also
called prototypes, since they provide a model or blueprint for the function.

They tell the compiler, “a function that looks like this is coming up later in the program, so it’s all right
if you see references to it before you see the function itself.”

Calling the Function


The function is called (or invoked, or executed) three times from main(). Each of the three calls looks
like this:

starline();

This is all we need to call the function: the function name, followed by parentheses. The syntax of the
call is very similar to that of the declaration, except that the return type is not used. The call is
terminated by a semicolon.

Executing the call statement causes the function to execute; that is, control is transferred to the
function, the statements in the function definition (which we’ll examine in a moment) are executed,
and hence control returns to the statement following the function call.

The Function Definition

Finally, we come to the function itself, which is referred to as the function definition. The definition
contains the actual code for the function. Here’s the definition for starline ():

void starline() //declarator


{
for(int j=0; j&lt45; j++) //function body
cout<< ‘*’;
cout<< endl;
}

The definition consists of a line called the declarator, followed by the function body. The function body
is composed of the statements that make up the function, delimited by braces.

The declarator must agree with the declaration:

It must use the same function name, have the same argument types in the same order (if there are
arguments), and have the same return type.

Notice that a semicolon does not terminate the declarator. Figure shows the syntax of the function
declaration, function call, and function definition.

When the function is called, control is transferred to the first statement in the function body. The other
statements in the function body are then executed, and when the closing brace is encountered,
control returns to the calling program.

Passing Arguments to Functions

An argument is a piece of data (an int value, for example) passed from a program to the function.
Arguments allow a function to operate with different values, or even to do different things, depending
on the requirements of the program calling it.

C++ allows programmers to divide their code up into chunks known as functions. A function with
simple description and a well-defined interface to outside world can be written and debugged without
worrying about the code that surrounds it. Using function we can structure our program in a more
modular way, accessing all the potential that structured programming can offer to us in C++.
Call by Value

This method of parsing value to a function is very simple. The values from the main function is
passed as arguments to the function as demonstrated below

main()
{
Int a;
Int b;

sum(5,6);

Return 0;
}

Int sum(int x, int y)


{
Int summation= x+y;
Print<<summation<<endl;

Call by Reference

Address of variables are passed as an argument to a function, which in turn are stored by pointers.
Here is how above example is modified to get the same result by using call by reference method.

main()
{
Int a;
Int b;

sum(&a,&b);

Return 0;
}

Int sum(int *x, int *y)


{
Int summation= *x+ *y;
Print<<summation<<endl;
Recursive function

A function calling it self is called a recursive function. This means that the function will continue to call
itself and repeat its behavior until some condition is met to return a result. An example given below
would give a clearer understanding of the phenomena.

#include<iostream>
using namespace std;
int fact(int a)
{
int n=0, answer;
if (a!=0)
{
answer=a*fact(a-1);
return answer;

}
else
return 1;
}

int main()
{
int x;
cout<<"enter number to find factorial of"<<endl;
cin>>x;
int facto=fact(x);
cout<<facto;
return 0;
}

Here a demonstration provides a clearer picture to what is happening inside a recursive function
LAB TASK 1

Write a program to pass two integer type numbers as arguments to the function body, compare the
numbers in the function body and print the greater number on the screen. The output of the program
should be like:

LAB TASK 2
Write a program that converts the kilograms into grams by using a function. The output of the
program should be like: Hint: 1 kilogram = 1000 grams.

LAB TASK 3

Write a program that creates four-function calculator, so that it uses functions for each of the four
arithmetic operations. They can be fadd, fsub, fmul, and fdiv. Each of these functions should take
three arguments two of float type and one is of character type for the operator. The output of the
program should be like:

LAB TASK 4

Write a program, which swap the two input values using


 Call by value
 Call by reference

LAB TASK 5

Find the sum of first n natural numbers using recursive function.


OBSERVATIONS & DISCUSSION

You might also like