0% found this document useful (0 votes)
65 views15 pages

Lecture 8-C++ Functions

Functions allow programmers to organize C++ code into reusable blocks of code called functions. Functions take in parameters, perform tasks, and return outputs. There are two types of functions: standard library functions which are predefined, and user-defined functions which are created by the programmer. Functions make code more modular and reusable, and reduce redundancy. Key parts of a function include its return type, name, parameters, body, and return statement.

Uploaded by

orodizodanielo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
65 views15 pages

Lecture 8-C++ Functions

Functions allow programmers to organize C++ code into reusable blocks of code called functions. Functions take in parameters, perform tasks, and return outputs. There are two types of functions: standard library functions which are predefined, and user-defined functions which are created by the programmer. Functions make code more modular and reusable, and reduce redundancy. Key parts of a function include its return type, name, parameters, body, and return statement.

Uploaded by

orodizodanielo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Lecture 8: C++ Functions

Introduction
We can break our C++ code into smaller chunks called functions. A function has a return type, a
name, a list of parameters in a declaration, and an additional function body in a definition. A simple
function definition is:

return_type function_name(arguments) {
statement;
statement;
return something;
}

Therefore; a function is a set of statements that take inputs, do some specific computation, and
produce output. The idea is to put some commonly or repeatedly done tasks together and make
a function so that instead of writing the same code again and again for different inputs, we can
call the function.

In simple terms, a function is a block of code that only runs (performs a specific task) when it is
called.

For example; suppose we need to create a program to create a circle and color it. We can create
two functions to solve this problem:

• a function to draw the circle


• a function to color the circle

Thus, dividing a complex problem into smaller chunks makes our program easy to understand
and reusable.

Why do we need Functions?


• Functions help us in reducing code redundancy. If functionality is performed at multiple
places in software, then rather than writing the same code, again and again, we create a
function and call it everywhere. This also helps in maintenance as we have to change at one
place if we make future changes to the functionality.
• Functions make code modular. Consider a big file having many lines of code. It becomes
really simple to read and use the code if the code is divided into functions.
• Functions provide abstraction. For example, we can use library functions without worrying
about their internal work.
Function Declaration
A function declaration tells the compiler about the number of parameters function takes, data-
types of parameters, and returns the type of function. Putting parameter names in the function
declaration is optional, but it is necessary to put them in the definition.

1|Page
@myco…TCBE 2202 Computing for Civil Engineering
Below are an example of function declarations and definition.
Syntax:

This function computes the sum of two numbers


Example 2:
// C++ Program to demonstrate working of a function
#include <iostream>
using namespace std;

// Following function that takes two parameters 'x' and 'y'


// as input and returns max of two input numbers
int max(int x, int y) Prototype or Function Signature
{
if (x > y)
return x;
else Function definition or Function body
return y;
}

// main function that doesn't receive any parameter and


// returns integer
int main()
{
int a = 10, b = 20;

// Calling above function to find max of 'a' and 'b'


int maximum = max(a, b); Function call
Note:
cout << "max btn a and b is " << maximum;
return 0; - x and y are formal
} parameters
Output - a and b are actual
parameters
max btn a and b is 20

2|Page
@myco…TCBE 2202 Computing for Civil Engineering
Program: Adding Two Numbers; this add function computes the sum of two numbers
#include <iostream>
using namespace std;
int add (int a, int b)
{
int c;
c = a + b;
return (c);
}
int main ()
{
int x, y;
x = 10;
y = 5;
int z = add (x, y);
cout<<"The sum is "<< z;
return 0;
As you can see in the above code, we created a function called add which takes two input
parameters a and b of type integer. This add function adds the two integer numbers it received as
input parameters and stores the result in variable c and returns that result.
Now see the main function. From the main function, we are calling the add function and while
calling the add function we are passing two parameters i.e. x and y (actually we are passing the
values stored in x and y) and these parameters’ values will go into a and b. The add function then
adds these two values and returns the result to the calling function (the function is called the add
method) i.e. the main method. The main method then store the result coming from the add method
into the variable z and then print the result on the output window.
As you can see in the above code, we are passing two values x and y to the add function which is
taking two parameters (a and b). The parameters (x and y) which are passing to the add function
are called Actual Parameters. The parameters (a and b) which are taken by the add method are
called Formal Parameters. When we call the add method the values of actual parameters are copied
to the formal parameters. So, x value i.e. 10 is copied to a, and y value i.e. 5 is copied to b.
Different Parts of a Function in C++ Language:
• Return Type: Function returning the value in which data type. It can be void if the function
returns nothing
• Name of the function: It is the identifier for the function name.
• Parameters/Arguments: Argument is the variables that the function will use. (can be
void)
• Body: this is the main logic of the function.
• Return Statement: if the return type is not null then the function will return a variable
according to the return type.

3|Page
@myco…TCBE 2202 Computing for Civil Engineering
Types of Functions
There are two types of function:
1. Standard Library Functions: Predefined in C++
2. User-defined Function: Created by users

Library Function
Library functions are also called “builtin Functions“. These functions are a part of a compiler
package that is already defined and consists of a special function with special and different
meanings. Builtin Function gives us an edge as we can directly use them without defining them
whereas in the user-defined function we have to declare and define a function before using them.
For Example: sqrt(), setw(), strcat(), etc.

User Defined Function


User Defined functions are user/customer-defined blocks of code specially customized to reduce
the complexity of big programs. They are also commonly known as “tailor-made functions”
which are built only to satisfy the condition in which the user is facing issues meanwhile
reducing the complexity of the whole program.

Main Function
The main() function is a special function. Every C++ program must contain a function named
main. It serves as the entry point for the program. The computer will start running the code from
the beginning of the main function.
Types of Main Functions
1. Without parameters:

// Without Parameters
int main() { ... return 0; }
2. With parameters:

// With Parameters
int main(int argc, char* const argv[]) { ... return 0; }
The reason for having the parameter option for the main function is to allow input from the
command line. When you use the main function with parameters, it saves every group of
characters (separated by a space) after the program name as elements in an array named argv.
Since the main function has the return type of int, the programmer must always have a return
statement in the code. The number that is returned is used to inform the calling program what
the result of the program’s execution was. Returning 0 signals that there were no problems.

4|Page
@myco…TCBE 2202 Computing for Civil Engineering
1. C++ Library Functions
Library functions are the built-in functions in C++ programming. Programmers can use library
functions by invoking the functions directly; they don't need to write the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc. In order to use library
functions, we usually need to include the header file in which these library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we need to include
the header file cmath.
Example: C++ Program to Find the Square Root of a Number

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double number, squareRoot;

number = 25.0;

// sqrt() is a library function to calculate the square root


squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;
}
Run Code

Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a number. The
function declaration of sqrt() is defined in the cmath header file. That's why we need to use the
code #include <cmath> to use the sqrt() function.
To learn more, visit C++ Standard Library functions; at https://www.programiz.com/cpp-
programming/library-function

5|Page
@myco…TCBE 2202 Computing for Civil Engineering
Categories of the Standard Function Library
The standard function library is divided into the following categories;
• I/O,
• String and character handling,
• Mathematical,
• Time, date, and localization,
• Dynamic allocation,
• Miscellaneous,
• Wide-character functions,
The table below shows some examples of standard Library functions in the first four categories.
No. Function name Purpose
C++ Mathematical Functions Header file: #include<cmath>
cos() returns Cosine of the Argument
sin() returns Sine of the Argument
tan() returns Tangent of the Argument
sinh() returns hyperbolic sine of an angle
exp() returns exponential (e) raised to a number
log() returns Natural Logarithm of a Number
trunc() truncates the demical part of a number
etc.
String and character handling Header file: #include<cstring>
strtol() converts a string to number
atol() converts String to Integer
strtod() returns string float to double
atof() converts String to Double
wctomb() converts wide character to a multibyte character
mbtowc() converts multibyte character to a wide character
etc.
I/O Header file: #include<iostream>
cin accepts input from the user
cout displays output to output device i.e monitor
wcin accepts input in wide character type
wcout displays wide characters (Unicode) to screen
etc.
Time, date, and localization Header file: #include<ctime>
time() returns current calendar time
clock() returns processor time consumed by program
difftime() computes difference between two times in seconds
asctime() converts calendar time to character representation
etc.
Etc.

6|Page
@myco…TCBE 2202 Computing for Civil Engineering
2. C++ User-defined Function
C++ allows the programmer to define their own function. A user-defined function groups code to
perform a specific task and that group of code is given a name (identifier). When the function is
invoked from any part of the program, it all executes the codes defined in the body of the function.

C++ Function Declaration


The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) {


// function body
}

Here's an example of a function declaration.

// function declaration
void greet() {
cout << "Hello World";
}

Here,
• the name of the function is greet()
• the return type of the function is void
• the empty parentheses mean it doesn't have any parameters
• the function body is written inside {}

Note: We will learn about returnType and parameters later in this tutorial.

Calling a Function
In the above program, we have declared a function named greet(). To use the greet() function, we
need to call it.
Here's how we can call the above greet() function.

int main() {

// calling a function
greet();

7|Page
@myco…TCBE 2202 Computing for Civil Engineering
How Function works in C++

Example 1: Display a Text


#include <iostream>
using namespace std;

// declaring a function
void greet() {
cout << "Hello there!";
}

int main() {

// calling the function


greet();

return 0;
}
Run Code
Output

Hello there!

Function Parameters
As mentioned above, a function can be declared with parameters (arguments). A parameter is a
value that is passed when declaring a function. For example, let us consider the function below:

void printNum(int num) {


cout << num;
}

8|Page
@myco…TCBE 2202 Computing for Civil Engineering
Here, the int variable num is the function parameter. We pass a value to the function parameter
while calling the function.

int main() {
int n = 7;

// calling the function


// n is passed to the function as argument
printNum(n);

return 0;
}

Example 2: Function with Parameters


// program to print a text

#include <iostream>
using namespace std;

// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}

int main() {

int num1 = 5;
double num2 = 5.5;

// calling the function


displayNum(num1, num2);

return 0;
}
Run Code

Output

The int number is 5


The double number is 5.5

9|Page
@myco…TCBE 2202 Computing for Civil Engineering
In the above program, we have used a function that has one int parameter and
one double parameter. We then pass num1 and num2 as arguments. These values are stored by
the function parameters n1 and n2 respectively.

C++ function with parameters

Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.

Return Statement
In the above programs, we have used void in the function declaration. For example,

void displayNumber() {
// code
}

This means the function is not returning any value. It's also possible to return a value from a
function. For this, we need to specify the returnType of the function during function declaration.

Then, the return statement can be used to return a value from a function.
For example,

int add (int a, int b) {


return (a + b);
}

10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Here, we have the data type int instead of void. This means that the function returns an int value.
The code return (a + b); returns the sum of the two parameters as the function value.
The return statement denotes that the function has ended. Any code after return inside the function
is not executed.
Example 3: Add Two Numbers

// program to add two numbers using a function

#include <iostream>

using namespace std;

// declaring a function
int add(int a, int b) {
return (a + b);
}

int main() {

int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;
}
Run Code

Output

100 + 78 = 178

In the above program, the add() function is used to find the sum of two numbers.

• We pass two int literals 100 and 78 while calling the function.
• We store the returned value of the function in the variable sum, and then we print it.

11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Working of C++ Function with return statement;

Notice that sum is a variable of int type. This is because the return value of add() is of int type.

Function Prototype

In C++, the code of function declaration should be before the function call. However, if we want
to define a function after the function call, we need to use the function prototype. For example,

// function prototype
void add(int, int);

int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}

// function definition
void add(int a, int b) {
cout << (a + b);
}

In the above code, the function prototype is:

void add(int, int);

12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
This provides the compiler with information about the function name and its parameters. That's
why we can use the code to call a function before the function has been defined.

The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);

Example 4: C++ Function Prototype

// using function definition after main() function


// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype
int add(int, int);

int main() {
int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;
}

// function definition
int add(int a, int b) {
return (a + b);
}
Run Code

Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is that here, the function
is defined after the function call. That's why we have used a function prototype in this example.

13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Benefits of Using User-Defined Functions
• Functions make the code reusable. We can declare them once and use them multiple times.
Reusable codes can also be used in other programs.
• Functions make the program easier as each small task is divided into a function. A large
program can be divided into smaller modules. Hence, a large project can be divided among
many programmers.
• Functions increase readability. The program will be easier to understand, maintain, and
debug.
Understanding the main() function in C/C++.

The main () function is an identifier in the program which indicates the starting point of program
execution. The main () function is a user-defined function with the pre-implemented signature of
the linker. Always linker will be searching to start the program from main() only that’s why main()
function should be required.

Without using the main() function we can design the program but we can’t execute it because
compilation can be a success but the execution is a failure (linker error will occur).

In any application only one main() function should be required, if we are placing more than one
main() function then the compiler will give an error i.e. multiple declarations for main().

Generally, the main function does not return any value that’s why the return type of the main
function can also be void. In implementation when we need to return the exit status of an
application then the main function return type should be an int.

The void main() function does not provide any existing status back to the OS. int main function
will provide existing status back to the operating system i.e. success or failure.

When we need to inform the existing status as success then need to return “0” i.e. return 0; exit
success. When we need to inform the exit status as a failure then the return value should be 1 i.e.
return 1; exit failure

When the main function return type is mentioned as an integer type then it is possible to return the
values from -32768 to 32767 but those are all meaningless exit statuses except 1 and 0. When the
user is terminated the program explicitly then the exit code is -1.

14 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Points to Remember About Functions in C++
1. Most C++ program has a function called main() that is called by the operating system when
a user runs the program.

2. Every function has a return type. If a function doesn’t return any value, then void is used as a
return type. Moreover, if the return type of the function is void, we still can use the return
statement in the body of the function definition by not specifying any constant, variable, etc.
with it, by only mentioning the ‘return;’ statement which would symbolize the termination of
the function as shown below:

void function name(int a)


{
....... // Function Body
return; // Function execution would get terminated
}
3. To declare a function that can only be called without any parameter, we should use “void
fun(void)“. As a side note, in C++, an empty list means a function can only be called without any
parameter. In C++, both void fun() and void fun(void) are same.
Below are an example of function declarations; (parameter names are not there in the below
declarations)

Function Declaration

15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering

You might also like