0% found this document useful (0 votes)
15 views37 pages

Part Six - Sen 101 Pop 1

Uploaded by

kren4456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views37 pages

Part Six - Sen 101 Pop 1

Uploaded by

kren4456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

MIU-SEN 101 Mr.

Abdulhamid Idris
(PRINCIPLES OF PROGRAMMING 1)
-- 6 --
SECTION SIX: FUNCTION
A function is a block of code that performs a specific task.
Functions allow you to organize your code, break it into smaller reusable pieces, and improve
code readability and maintainability.
With functions, you only need to define the code once, and you can use it many times.
A function only gets executed when it is called.
Data (parameters) can be passed into a function for it to work with.

Types of functions in C++


1. built-in functions
2. user-defined functions
FUNCTION CONTD.
Defining/declaring or creating a function
A function definition contains the statements that make up the function.
When creating a function, you must write its definition. All function definitions have the
Following four parts:
Return Type: Specifies the type of value the function will return. If the function doesn't
return anything, the return type is void.
Function Name: A unique identifier that allows you to call the function.
Parameter List (optional): A set of input values (variables) that are passed into the
function. These are enclosed in parentheses and separated by commas.
Function Body: The block of code that defines what the function does. It is enclosed in
curly braces { }.
FUNCTION CONTD.
Function definition

return_type function_name (parameters)


{
// function body
// code to perform some task return value;
// if the return type is not void
}

The line in the definition that reads int main() is called the function header .
A void function doesn’t return any value to its caller.
FUNCTION CONTD.
Calling a Function

A function is executed when it is called.


Function main is called automatically when a program starts, but all other functions
must be executed by function call statements.
When a function is called, the program branches to that function and executes the
statements in its body.

Functions are invoked/called by referring to them by their names and passing any
arguments defined in the function’s header.
FUNCTION CONTD.
Function prototype

A function prototype (also known as a function declaration) is a declaration of a


function that provides information to the compiler about the function's name, return
type, and parameters without defining the actual body of the function.
It tells the compiler about the function's signature so that it can be used before its
definition in the code.
FUNCTION CONTD.
Function prototype contd.

Purpose of a Function Prototype:


Declares the function to the compiler, so the compiler knows how to check for
correct usage of the function in the code.
Allows you to use the function before its definition in the code. This is useful when
you want to call a function in a different part of the program or file.
FUNCTION CONTD.
Function prototype contd.

Syntax of function prototype


return_type function_name(parameter1_type, parameter2_type, ...);

returnType: The type of value the function will return.


functionName: The name of the function.
parameter1_type, parameter2_type, etc.: The types of the function's parameters.
FUNCTION CONTD.
Function prototype contd.
Example

#include <iostream>

// Function prototype

int sum(int a, int b);

// Declare the sum function

int main()

int result = sum(10, 20); // Function call

std::cout << "The sum is: " << result << std::endl;

return 0;

// Function definition

int sum(int a, int b) { // Define the sum function return a + b;}


FUNCTION CONTD.
Function parameter VS function argument
Function Parameter
Function parameter is a variable declared in the function definition or declaration that represents the
input to the function. It acts as a placeholder for the actual values that will be passed when the function
is called. Parameters are used within the function to operate on the data.
Example:
void printSum (int a, int b)
{
cout << “The sum of the two numbers is: " << a + b << endl;
}
In this example, a and b are function parameters. They are placeholders for the actual values that will
be passed to the function when it is called.
FUNCTION CONTD.
Function argument

Function argument is the actual value or reference that you pass to the function when you call it. The
argument corresponds to the function's parameter and is used to provide real data that the function will
process.
Example
int main()
{
printSum(3, 5);
return 0;
}
Here, 3 and 5 are function arguments. They are the actual values passed to the printSum function,
corresponding to the parameters a and b inside the function.
FUNCTION CONTD.
Default argument

A default argument allows you to provide default values for one or more parameters of a function.
This means that if a caller does not supply a value for that parameter when calling the function, the
function will use the default value instead.
Default arguments make your functions more flexible, as they allow them to be called with fewer
arguments.
Default arguments are specified in the function declaration (or prototype), not in the definition(body of
the function).
They must appear from right to left. This means that you cannot provide a default argument for a
parameter without providing default values for all the parameters that come after it.
A default argument can only be provided once, either in the function declaration or in the function
definition, but not both.
FUNCTION CONTD.
Default argument contd.

#include <iostream>
// Function with default arguments
void printMessage(std::string message = "Hello, World!", int times = 1)
{
for (int i = 0; i < times; i++)
{
std::cout << message << std::endl;
}
}
// program continues on next slide
FUNCTION CONTD.
Default argument contd.
int main()
{
// Using both default arguments
printMessage();
// Prints "Hello, World!" once

// Using the default value for 'times', but specifying 'message'


printMessage("Welcome to C++!", 3);
// Prints the message 3 times

// Using the default value for 'message', but specifying 'times' printMessage("Goodbye!", 2);
// Prints "Goodbye!" twice

return 0;
}
FUNCTION CONTD.
Default argument contd.
Explanation

The function printMessage() has two parameters:


message has a default value of "Hello, World!".
times has a default value of 1.
When printMessage() is called without arguments, it uses the default values:
"Hello, World!" for message and 1 for times.
When printMessage("Welcome to C++!", 3) is called, it overrides both default
values by passing "Welcome to C++!" for message and 3 for times.
Similarly, calling printMessage("Goodbye!", 2) uses "Goodbye!" and 2 for message
and times, respectively.
FUNCTION CONTD.
Local variable VS Global variable
Local variable
A local variable is a variable that is declared inside a function or block of code (such
as loops or conditionals). It is only accessible within that specific function or block.
Because variables defined in a function are hidden, other functions may have
separate, distinct variables with the same name.
FUNCTION CONTD.
Local variable contd.
Example
#include <iostream>

void myFunction()

int x = 5;

// 'x' is a local variable

std::cout << "Value of x: " << x << std::endl;

int main()

myFunction();

// 'x' is not accessible here

return 0;

}
FUNCTION CONTD.
Local variable contd.

Scope: A local variable is only visible within the function or block where it is
declared. Once the program execution leaves that scope, the variable is no longer
accessible.
Lifetime: The lifetime of a local variable is limited to the duration of the function or
block. It is created when the function is called and destroyed when the function
returns.
Default Initialization: Local variables are not automatically initialized. If you do not
assign a value to them, their value will be undefined.
FUNCTION CONTD.
Global variable
A global variable is declared outside of all functions, typically at the top of a file, and
it is accessible from any function within the same program (or file, if declared extern
in others).
FUNCTION CONTD.
Global variable contd.
#include <iostream>

int x = 10;

// 'x' is a global variable

void myFunction()

std::cout << "Global x: " << x << std::endl;

// Can access global variable 'x’

int main()

std::cout << "Global x in main: " << x << std::endl;

myFunction();

// Accesses the global variable 'x'

return 0;

}
FUNCTION CONTD.
Global variable contd.

Scope: A global variable has a program-wide scope. It is visible and accessible from
any function within the same program (or across multiple files if declared extern).
Lifetime: The lifetime of a global variable is the entire duration of the program’s
execution. It is created when the program starts and destroyed when the program
ends.
Default Initialization: Global variables are automatically initialized to zero (for
basic types like int, float, etc.) if no explicit initialization is provided.
FUNCTION CONTD.
Function overloading

Function overloading in C++ allows you to define multiple functions with the same
name but with different parameter lists.
The function signature (name + parameters) must be different, and it enables you to
call the same function with different numbers or types of arguments.
Function overloading works by distinguishing functions based on the number of
arguments or the types of arguments passed.
C++ will automatically pick the correct function based on the call, as long as there is
no ambiguity.
FUNCTION CONTD.
Function overloading contd.

Consider a simple sum function that calculates the sum of numbers. We can overload
this function in several ways by changing the number or types of arguments.
Examples
FUNCTION CONTD.
Function overloading contd.
Example 1: Overloading based on the number of arguments
Here, we define multiple versions of the sum function to add:
Two integers
Three integers
FUNCTION CONTD.
Function overloading contd.
#include <iostream>

// Sum of two integers

int sum(int a, int b) { return a + b;}

// Sum of three integers

int sum(int a, int b, int c) { return a + b + c;}

int main()

int result1 = sum(10, 20); // Calls sum(int, int)

int result2 = sum(10, 20, 30); // Calls sum(int, int, int)

std::cout << "Sum of two integers: " << result1 << std::endl; // Outputs 30

std::cout << "Sum of three integers: " << result2 << std::endl; // Outputs 60

return 0;

}
FUNCTION CONTD.
Function overloading contd.
Explanation
The sum function is overloaded: one version takes two integers and the other takes
three integers.

In the main() function:


sum(10, 20) calls the function sum(int, int), which returns the sum of two integers.
sum(10, 20, 30) calls the function sum(int, int, int), which returns the sum of three
integers.
FUNCTION CONTD.
Function overloading contd.
Example 2: Overloading based on parameter types
A function can also be overloaded based on different types of arguments (e.g.,
integers, floating-point numbers, etc.)
The following example overloads the sum function with different types of arguments
(integer and double)
FUNCTION CONTD.
Function overloading contd.
#include <iostream>

// Sum of two integers

int sum(int a, int b) { return a + b;}

// Sum of two floating-point numbers

double sum(double a, double b) { return a + b;}

int main()

int intResult = sum(10, 20);

// Calls sum(int, int)

double doubleResult = sum(10.5, 20.5);

// Calls sum(double, double)

std::cout << "Sum of integers: " << intResult << std::endl; // Outputs 30

std::cout << "Sum of doubles: " << doubleResult << std::endl; // Outputs 31.0

return 0;

}
FUNCTION CONTD.
Function overloading contd.
Explanation
The sum function is overloaded: one version takes integers and the other takes
numbers with decimal points.

In the main() function:


The function call sum(10, 20) uses the version that accepts integers.
The function call sum(10.5, 20.5) uses the version that accepts doubles.
FUNCTION CONTD.
Returning value from a function
A function may send a value back to the part of the program that called the function.
Just as data may be passed into a function by way of parameter variables, data may also be returned
from a function, back to the statement that called it.
Functions that return a value are appropriately known as value-returning functions.
Example
The built-in pow function, is an example of a value-returning function.
double x;
x = pow(4.0, 2.0);
The second line in this code calls the pow function, passing 4.0 and 2.0 as arguments.
The function calculates the value of 4.0 raised to the power of 2.0 and returns that value.
The value, which is 16.0, is assigned to the x variable by the = operator.
FUNCTION CONTD.
Returning value from a function contd.
A value-returning function will use int , double , bool , or any other valid data type in its header.
Every value-returning function must have a return statement that signals the end of the function and
returns the result of the operation performed by the function to the statement that called the function.

Consider the following sum function that returns an int value:


int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
FUNCTION CONTD.
Returning value from a function contd.

This code defines a function named sum that accepts two int arguments.
The arguments are passed into the parameter variables num1 and num2 . Inside the function, a
variable, result is defined.
After the variable definition, the parameter variables num1 and num2 are added, and their sum is
assigned to the result variable.
The last statement in the function is return result;
This statement causes the function to end, and it sends the value of the result variable back to the
statement that called the function.
EXERCISE
1. Write a function that displays the message “Welcome”
2. Write a function that accepts a user’s name and number of times the user wants to be greeted. The
function should then displays the message “Welcome, users-name” as many times as the number
entered by the user. (Hint: use default arguments to set the number of times to 1)
3. Write a function to compute the product of two integer numbers.
4. Overload the function in example three to allow the program to compute product of two integers
and a floating-point number
5. Write a function to calculate the average of three numbers.
6. Overload the average function in exercise 5
ASSIGNMENT
1. The formula for converting a temperature from Fahrenheit to Celsius is

where F is the Fahrenheit temperature and C is the Celsius temperature.


Write a function named celsius that accepts a Fahrenheit temperature as an argument. The
function should return the temperature, converted to Celsius.
Demonstrate the function by calling it in a loop that displays a table of the Fahrenheit
temperatures 0 through 20 and their Celsius equivalents.
ASSIGNMENT CONTD.
2. Overloaded Hospital
Write a program that computes and displays the charges for a patient’s hospital stay. First, the program
should ask if the patient was admitted as an in-patient or an outpatient.

If the patient was an in-patient, the following data should be entered:


 The number of days spent in the hospital
 The daily rate
 Hospital medication charges
 Charges for hospital services (lab tests, etc.)

The program should ask for the following data if the patient was an out-patient:
 Charges for hospital services (lab tests, etc.)
 Hospital medication charges

The program should use two overloaded functions to calculate the total charges. One of the functions should
accept arguments for the in-patient data, while the other function accepts arguments for out-patient
information.
Both functions should return the total charges.

Input Validation: Do not accept negative numbers for any data.

You might also like