CP 23-24 - Lab 2
CP 23-24 - Lab 2
Laboratory 2
Functions in C++
2.1 Introduction
This laboratory session is designed to give you an understanding of the workings of C++ Functions.
Here you are going to focus on the following:
Function’s Idea and Definition
Function’s structure and syntax
Function’s Interface
Function’s Types
o Predefined o User-defined
Sharing data among functions through parameters
o Calling by Value o Calling by Reference
2.2 Function’s Idea and Definition
Idea: it is to divide the main problem into smaller tasks which may be divided into simpler
tasks, then implement each simple task by a function.
Function is a group of statements that is given a name and called from some point of the program.
2.3 Function’s Structure and Syntax
Structure: the function consists of two parts 1- header 2- body
Syntax: < Type > <name> (<parameter list>)
{
Statement(s)
}
2.4 Function’s Interface
It is actually similar to the function header except in two aspects:
Has unnamed parameters
Must be ended by a semicolon
Example double computeTaxes (double);
2.5 Function’s Types
2.6.1 Predefined Functions
Functions that are grouped in different libraries which can be included in the
C++ program.
Example:
Compute the ceiling and the floor of the real number
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
void main()
{
// Getting a double value
double x;
cout << "Please enter a real number: ";
cin >> x;
// calling ceiling & floor function from cmath library
cout<<"The ceil of "<<x<< " = "<<ceil(x)<<endl;
cout<<"The floor of "<<x<<" = "<<floor(x)<<endl;
}
2.6.2 User-defined Functions
Functions that are set by the user.
Example:
Take 2 integer values from user as parameters to a function, then apply the
following equation (5*a)-(3/b) , Which code is better?
#include "stdafx.h" #include "stdafx.h"
#include <iostream> #include <iostream>
using namespace std; using namespace std;
Bonus
Write a C++ program that gets three values x, y, and z as parameters
to a function then print the average of those three numbers.
2.7 Exercise
2.7.1 Write a C++ program that computes the smallest and the largest of three
integer numbers using predefined functions.
2.7.2 Write a C++ program that allows the user to input an integer value as a
parameter then use predefined functions to compute its square root, log, and
power of 5.
2.7.3 Write a C++ program that allows the user to input string as a parameter then use
a predefined function to print this string again in uppercase.
2.7.4 Write a C++ program that allows the user to input the radius of a circle as a
parameter to two functions: the first, it computes the area, and the second, it
computes the circumference.
2.7.5 Write a C++ program function that uses a call by reference to convert from
inches to centimeters knowing that 1 inch = 2.54 centimeters.
Note:
Don’t Forget to Send Your Assignment to
Microsoft Teams
Account Name: seifaldin.yasser
Email: [email protected]