0% found this document useful (0 votes)
12 views9 pages

Labreport 551

The document outlines a computer programming lab focused on understanding functions, including their definitions, prototypes, and the differences between pass by value and pass by reference. It also covers function overloading and provides several lab tasks for students to implement various functions, such as calculating grades, counting function calls, and simulating a food ordering system. The document serves as a guide for students in the Department of Mechanical Engineering to enhance their programming skills.

Uploaded by

Hashir Khan
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)
12 views9 pages

Labreport 551

The document outlines a computer programming lab focused on understanding functions, including their definitions, prototypes, and the differences between pass by value and pass by reference. It also covers function overloading and provides several lab tasks for students to implement various functions, such as calculating grades, counting function calls, and simulating a food ordering system. The document serves as a guide for students in the Department of Mechanical Engineering to enhance their programming skills.

Uploaded by

Hashir Khan
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/ 9

Computer programming Department of mechanical Purwa Tariq

Name of Student:______________________________ Section:___________________________________

Class: BEME-I Date:__________________________________


Lab no#6 Name of Instructor:______________________

Lab#6
Computer Programming
Objectives:
 To understand the concept of function.
 To understand what the function prototype is and how that is different from the
function definition.
 Convert the code processing in the main function to a function called from the main
function.
 Create functions with multiple parameters.
 The mechanisms for passing information between functions and returning results.
 Understand the difference between pass by value and reference.
 To know about function overloading.

Description
A function is a collection of statements that performs a specific task. So far you have
experienced functions as you have created a function named “main” in every program
you have written. Functionsare commonly used to break a problem down into small
manageable pieces. This approach is sometimes called divide and conquer because a
large problem is divided into several smaller problemsthat are easily solved.

Defining and Calling Functions

A function call is a statement that causes a function to execute. 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 parts:

1. Name: You should give each function a descriptive name. In general, the same
Computer programming Department of mechanical Purwa Tariq

Rule that apply to variable names also apply to function names.

1. Parameter list: The program can send data into a function. The parameter
list is a list ofvariables that hold the values being passed to the function.
2. Body: The body of a function is the set of statements that perform the
function’s operation.They are enclosed in a set of braces.
3. Return type: A function can send a value to the part of the program that
executed it. Thereturn type is the data type of the value that is sent from the
function.

Void Functions
It is not necessary for all functions to return a value, however. Some functions simply
perform one or more statements, which follows terminate. These are called void
functions. An example is shown below.

Calling a Function
A function is executed when it is called. The “main” function 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.

In the above example, void displayMessage() represent the Function Header


(Definition) while the 2nd line in the “main” function i.e. displayMessage(); represent
the function call. When this line executes the program move towards the function
definition and execute the whole body, then it comesback to the main function.
Computer programming Department of mechanical Purwa Tariq

In the above example, void displayMessage() represent the Function Header


(Definition) while the 2nd line in the “main” function i.e. displayMessage(); represent
the function call. When this line executes the program move towards the function
definition and execute the whole body, then it comesback to the main function.
Functions may also be called in a hierarchical, or layered, fashion. It means a function can
call anotherfunction too, example is shown below:

Function prototype
A function prototype eliminates the need to place a function definition before all calls to
the function.You must place either the function definition or / the function prototype
ahead of all calls to the function. Otherwise, the program will not compile.

Sending Data into a Function


When a function is called, the program may send values into the function. Values that
are sent into a function are called arguments. In the following statement the function pow
is being called and two arguments, 2.0 and 4.0, are passed to it:
Computer programming Department of mechanical Purwa Tariq

result = pow (2.0, 4.0);

By using parameters, you can design your own functions that accept data this way. A
parameter is a special variable that holds a value being passed into a function. The values
can be passed to the functionas “value” or as “reference”.

Pass by Value
void displayValue (int);

//function prototypeint main ()

// main function

int x = 2;

displayValue(x); //function is called and the parameter x is passed to the function definition

void displayValue (int x) //function definition


{
cout<< "The value is " <<x<<endl; }

Here the value “x” passed by main function is stored in another “x”. Keep in mind this
“x” is differentfrom the one in the main function. Any change we make to this “x” will
not change the value of “x” present in the “main” function. Suppose we update the “x”
value here as, “x” = 3, then “x” has value 3 in this function only but in the main function
“x” will not get updated, it will still stay as “x” = 2, because both are different. We can
give different name to the “x” in the function definition to avoid confusion. In the same
program we can also write the function definition line as,

void displayValue (int num) //function definition

Now the variable sent by the main function is “x” whose value is copied in the variable
“num”.

Pass by Reference
void displayValue (int&);

//function prototypeint main ()

// main function
Computer programming Department of mechanical Purwa Tariq

int x = 2;

displayValue(x); //function is called and the parameter “x” is passed to the function
definition

void displayValue (int& x) //function definition

cout<< "The value is " <<x<<endl;

Notice this “&” with the data type in function definition. Here the value “x” passed by
main function is stored in another “x” but by writing “&” gives an address to the “x” in
the main function. So, if I change this “x” value within the function it will also change
the value of “x” in the main function. Even if we had stored it in another variable, it still
has the address of the main function variable “x”, so any change we make into this
variable will update the variable in the main function also.

void displayValue (int& num) //function definition

Now the variable sent by the main function is “x” whose value is copied in the variable
“num”. If wechange the value of “num” here the value of “x” in the main function will
also change as “num” has the address of “x”.
This “&” should be written in both function definition as well as prototype.

The Return Statement and Returning a Value from a Function


The return statement causes a function to end immediately. A function may send a value
back to the part of the program that called the function this is known as returning a value.
Here is an example of afunction that returns an int value:
Computer programming Department of mechanical Purwa Tariq

A function can also return a Boolean value instead of integer or double or character. Then
we must use“bool” in the function definition instead of “int”

Function Overloading
Overloaded functions have the same name but different parameter lists. They can be used
to create functions that perform the same task but take different parameter types or
different number of parameters. The compiler will determine which version of function
to call by argument and parameterlists.

Example

In the above example, all the functions being called are different. Although their names
are same but the parameters or their data types are change, that makes them a different
function.

SLOVED EXAMPLE OF FUNCTION:


Computer programming Department of mechanical Purwa Tariq
Computer programming Department of mechanical Purwa Tariq

LAB TASKS
1. Write a function courseGrade. This function takes as a parameter an int value
specifying the score for a course and returns the grade, a value of type char, for
the course.
2. Write a main function that call a function named countCall. Every time this
function is called you should display a message “I have been called 1 time” etc.
If the function is called 3 timesthe output should be: (Use pass by Reference)

I have been called 1 time.


I have been called 2 time.
I have been called 3 time
Note: (If your Roll Number is 201795, call the function 5 times etc.)

3. Write a function accepts an integer argument and tests it to be even or odd. The
function returns true if the argument is even or false if the argument is odd. The return
value should be bool. In main take a integer input from user and pass it to the function.
4. The program simulates a simple food ordering system. The user can select a food item from
the menu, specify how many of that item they want to order, and then calculate the total bill.
The program also applies a discount if the total bill exceeds a certain amount.

showMenu():
 It uses cout (console output) to print the menu.
 Each food item is listed with a corresponding number (1 for Burger, 2 for Pizza, etc.).
 This helps the user choose an option by entering the corresponding number.
getPrice(int choice):
 The function takes an argument choice (an integer).
 Depending on the value of choice, the function returns the price of the selected item.
 If the user chooses "1" (Burger), the function returns the price $5.99. If the user chooses "2"
(Pizza), it returns $8.99, and so on.
 If the user provides an invalid choice (e.g., a number outside the menu options), the function
returns 0, indicating no valid price.
calculateBill(int choice, int quantity):
 The function takes two arguments:
1. choice: The number representing the selected food item (e.g., 1 for Burger, 2 for Pizza).
2. quantity: The number of items the user wants to order.

 The function first calls getPrice() to get the price of the food item based on the user's
choice.
Computer programming Department of mechanical Purwa Tariq

 Then, it multiplies the price by the quantity to get the total cost for that food item and quantity.
 The result is returned as the total cost.
applyDiscount(double totalBill):
 The function takes totalBill as an argument (the total amount the user needs to pay before
the discount).
 It checks if the total bill is greater than $30.
 If the total bill is greater than $30, it applies a 10% discount by reducing the total bill by 10%.
 If the bill is not above $30, no discount is applied, and the function simply returns the original
total bill.
For Example :

Let's say a user selects "Pizza" (Choice 2) and orders 4 pizzas.

1. The price of Pizza is retrieved using getPrice(2), which returns $8.99.


2. The total cost for 4 pizzas is calculated as 8.99 * 4 = 35.96.
3. The total bill of $35.96 is passed to the applyDiscount() function, and since the bill is
above $30, the program applies a 10% discount:
o New total after discount = $35.96 - (35.96 * 0.10) = $32.36.
4. The program displays the final bill after the discount is applied.

You might also like