Functions C+++
Functions C+++
Fundamental
s
By Engr. Sher Mohammad
Contents of Lecture
• Functions
• Why functions?
• Types of Functions
• Standard Library/Built-in Functions
• User defined Functions
• Declaration/Prototyping and Definition of functions
• Function Parameters and Arguments
• Function Overloading
Functions
• A group of statements that takes input, processes it, and returns an
output.
• The idea behind a function is to combine common tasks that are done
repeatedly.
• If you have different inputs, you will not write the same code again. You
will simply call the function with a different set of data called
parameters.
• Each C++ program has at least one function, the main() function.
• You can divide your code into different functions.
• This division should be such that every function does a specific task.
Functions
• A function has:
– A name
– Zero or more input parameters
– 0 or 1 return (output) values
• We only specify the type
}
Example 1
Example 2
C++ Standard Library Functions
(In-built Functions)
• There are a number of built-in functions included in the standard library of C++.
• These functions are present in the corresponding header files and offer a variety of
functionality.
• <cmath>
• <ctime>
• <cstdio>
• <cstring>
• <cctype>
• <iostream>
• <cstdlib>
Example 1:
#include <iostream>
#include <cmath>
int main() {
double number = 16.0;
double squareRoot = sqrt(number);
cout << "The square root of " << number << " is: " << squareRoot
<< endl;
return 0;
}
Example 2:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = 7.5, y = 2.1;
double result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
x = -17.50, y=2.0;
result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
y=0;
result = remainder(x, y);
cout << "Remainder of " << x << "/" << y << " = " << result << endl;
return 0;
}
Function Overloading
• The C++ language's function overloading feature enables the coexistence of
many functions with the same name but various arguments or argument types.
• A person is eligible to vote if his/her age is greater than or equal to 18. Define a
function to find out if he/she is eligible to vote.
• Define two functions to print the maximum and the minimum number respectively
among three numbers entered by user.
• Define a function that returns the product of two numbers entered by user.
• Write a program that calculates 6^5. Declare your own function to do this.
• Write a C++ program that take a number from user then output the square of this
number.