Function I (Reusability and Divide and Conquer)
Learn why we need to implement functions in C++ and how we can pass the parameters by value.
Functions
Functions are a fundamental concept in programming. In essence, a function is a block of code that can be reused throughout a program. Functions allow us to break down a larger program into smaller, more manageable chunks, making it easier to write, debug, and maintain.
Let’s learn how to classify quadrilaterals and incorporate the reusability concept by utilizing functions.
Problem: Identify the quadrilateral's type
We’re given four coordinates points ,
We have to calculate the sides of a quadrilateral. We’ll use the distance square formula to calculate the sides, reducing the computation to calculating the square root.
Computing the distance between two points:
We can use the distance formula to calculate the distance between two points.
We can also simplify the above formula.
It can also be written like this:
Note: If two distances are the same length, then their distance squared will also be the same length. Also, note that computing a squared distance is less costly than calculating the distance (taking the square root of the squared distance). So, in this example, we can avoid taking the square root.
The following illustration describes the distance between all four coordinate points:
So, while checking the quadrilateral, first, we must check whether the sides
In another case, if only opposite sides are of the same length, then it is potentially a rectangle or parallelogram. For further evaluation, we’ll check whether the diagonals
#include <iostream>#include<math.h>using namespace std;int main(){double Ax = 3, Ay = 0,Bx = 0, By = 2,Cx = -3, Cy = 0,Dx = 0, Dy = -2;//calculating Euclidean distance between A and Bdouble distAB = 0.0;distAB = (Ax - Bx)*(Ax - Bx) + (Ay - By)*(Ay - By);//calculating Euclidean distance between D and Cdouble distDC = 0.0;distDC = (Dx - Cx)*(Dx - Cx) + (Dy - Cy)*(Dy - Cy);//calculating Euclidean distance between A and Ddouble distAD = 0.0;distAD = (Ax - Dx)*(Ax - Dx) + (Ay - Dy)*(Ay - Dy);//calculating Euclidean distance between B and Cdouble distBC = 0.0;distBC = (Bx - Cx)*(Bx - Cx) + (By - Cy)*(By - Cy);//calculating Euclidean distance between the diagonal A and Cdouble distAC = 0.0;distAC = (Ax - Cx)*(Ax - Cx) + (Ay - Cy)*(Ay - Cy);//calculating Euclidean distance between the diagonal B and Ddouble distBD = 0.0;distBD = (Bx - Dx)*(Bx - Dx) + (By - Dy)*(By - Dy);if(distAB == distBC && distBC == distDC && distDC == distAD){if(distAC == distBD)cout << "A quadrilateral ABCD is a Square \n";elsecout << "A quadrilateral ABCD is a Rhombus \n";}else if(distAB == distDC && distAD == distBC){if(distAC == distBD)cout << "A quadrilateral ABCD is a Rectangle \n";elsecout << "A quadrilateral ABCD is a Parallelogram \n";}else{cout << "It is an irregular quadrilateral \n";}return 0;}
Lines 7–10: We initialize the coordinate points for A(
Ax
,Ay
), B(Bx
,By
), C(Cx
,Cy
), and D(Dx
,Dy
) with valid values and types.Lines 12–23: We compute each side’s squared distance.
Lines 25–30: We compute each diagonal’s squared distance.
Lines 31–37: We check whether the quadrilateral with given points is a square or a rhombus.
Lines 38–44: We check whether the quadrilateral with given points is a rectangle or a parallelogram.
Lines 45-48: We will simply declare it as an irregular quadrilateral.
What if we have more than one quadrilateral to check?
The first solution that comes to mind is to replicate this code for another quadrilateral. Let’s look into the given code that can classify the types of two quadrilaterals.
#include <iostream>#include<math.h>using namespace std;int main(){double Ax = 3, Ay = 0,Bx = 0, By = 2,Cx = -3, Cy = 0,Dx = 0, Dy = -2;// coordinate points for 2nd quadrilateraldouble Ex = -4, Ey = -3,Fx = -2, Fy = -6,Gx = 4, Gy = -6,Hx = 2, Hy = -3;//calculating Euclidean distance between A and Bdouble distAB = 0;distAB = (Ax - Bx)*(Ax - Bx) + (Ay - By)*(Ay - By);//calculating Euclidean distance between D and Cdouble distDC = 0;distDC = (Dx - Cx)*(Dx - Cx) + (Dy - Cy)*(Dy - Cy); //calculating Euclidean distance//calculating Euclidean distance between A and Ddouble distAD = 0;distAD = (Ax - Dx)*(Ax - Dx) + (Ay - Dy)*(Ay - Dy); //calculating Euclidean distance//calculating Euclidean distance between B and Cdouble distBC = 0;distBC = (Bx - Cx)*(Bx - Cx) + (By - Cy)*(By - Cy); //calculating Euclidean distance//calculating Euclidean distance between the diagonal A and Cdouble distAC = 0;distAC = (Ax - Cx)*(Ax - Cx) + (Ay - Cy)*(Ay - Cy); //calculating Euclidean distance//calculating Euclidean distance between the diagonal B and Ddouble distBD = 0;distBD = (Bx - Dx)*(Bx - Dx) + (By - Dy)*(By - Dy); //calculating Euclidean distanceif(distAB == distBC && distBC == distDC && distDC == distAD){if(distAC == distBD)cout << "A quadrilateral ABCD is a Square \n";elsecout << "A quadrilateral ABCD is a Rhombus \n";}else if(distAB == distDC && distAD == distBC){if(distAC == distBD)cout << "A quadrilateral ABCD is a Rectangle \n";elsecout << "A quadrilateral ABCD is a Parallelogram \n";}else{cout << "It is an irregular quadrilateral \n";}// replicate the code for quadrilateral A1, B1, C1, and D1double distEF = 0;distEF = (Ex - Fx)* (Ex - Fx) + (Ey - Fy)*(Ey - Fy);//calculating Euclidean distance between D and Cdouble distHG = 0;distHG = (Hx - Gx)*(Hx - Gx) + (Hy - Gy)*(Hy - Gy); //calculating Euclidean distance//calculating Euclidean distance between A and Ddouble distEH = 0;distEH = (Ex - Hx)*(Ex - Hx) + (Ey - Hy)*(Ey - Hy); //calculating Euclidean distance//calculating Euclidean distance between B and Cdouble distFG = 0;distFG = (Fx - Gx)*(Fx - Gx) + (Fy - Gy)*(Fy - Gy); //calculating Euclidean distance//calculating Euclidean distance between the diagonal A and Cdouble distEG = 0;distEG = (Ex - Gx)*(Ex - Gx) + (Ey - Gy)*(Ey - Gy); //calculating Euclidean distance//calculating Euclidean distance between the diagonal B and Ddouble distFH = 0;distFH = (Fx - Hx)*(Fx - Hx) + (Fy - Hy)*(Fy - Hy); //calculating Euclidean distanceif(distEF == distFG && distFG == distHG && distHG == distEH){if(distEG == distFH)cout << "A quadrilateral EFGH is a Square \n";elsecout << "A quadrilateral EFGH is a Rhombus \n";}else if(distEF == distHG && distEH == distFG){if(distEG == distFH)cout << "A quadrilateral EFGH is a Rectangle \n";elsecout << "A quadrilateral EFGH is a Parallelogram \n";}else{cout << "It is an irregular quadrilateral \n";}return 0;}
Lines 7–10: We initialize the coordinate points of the first quadrilateral,
. Lines 12–15: We initialize the coordinate points of the second quadrilateral,
. Lines 17–52: We check the type of the first quadrilateral.
Lines 54–89: We check the type of the second quadrilateral.
To improve our code’s organization and efficiency, we can create a separate module, referred to as a function, that takes specific parameters as inputs and performs the designated task. By defining a function named someFunction(arguments_list)
, we can conveniently call it whenever we need to execute the same operations. This approach greatly reduces code duplication and enhances the overall conciseness and manageability of our program, making it easier to maintain and understand.
Reusability using functions
Let’s take a careful look at the above implementation. First, let’s identify the repeated statements and then convert them into functions to eliminate redundancy.
Repeated statements
This is the calculation of the square power in a Euclidean square with different points in consideration.
(Ax - Bx) * (Ax - Bx)(Ay - Cy) * (Ay - Cy)(Dx - Cx) * (Dx - Cx)(Dy - Cy) * (Dy - Cy)...
This is the calculation of the distance between any two points using the Euclidean distance function.
distAC = (Ax - Cx)*(Ax - Cx) + (Ay - Cy)*(Ay - Cy);distAB = (Ax - Bx)*(Ax - Bx) + (Ay - By)*(Ay - By);distAD = (Ax - Dx)*(Ax - Dx) + (Ay - Dy)*(Ay - Dy);distBC = (Bx - Cx)*(Bx - Cx) + (By - Cy)*(By - Cy);...
This is the calculation of the Euclidean distance for a quadrilateral.
//calculating Euclidean distance between A and Bdouble distAB = 0;distAB = (Ax - Bx)*(Ax - Bx) + (Ay - By)*(Ay - By);//calculating Euclidean distance between D and Cdouble distDC = 0;distDC = (Dx - Cx)*(Dx - Cx) + (Dy - Cy)*(Dy - Cy);//calculating Euclidean distance between A and Ddouble distAD = 0;distAD = (Ax - Dx)*(Ax - Dx) + (Ay - Dy)*(Ay - Dy);//calculating Euclidean distance between B and Cdouble distBC = 0;distBC = (Bx - Cx)*(Bx - Cx) + (By - Cy)*(By - Cy);//calculating Euclidean distance between the diagonal A and Cdouble distAC = 0;distAC = (Ax - Cx)*(Ax - Cx) + (Ay - Cy)*(Ay - Cy);//calculating Euclidean distance between the diagonal B and Ddouble distBD = 0;distBD = (Bx - Dx)*(Bx - Dx) + (By - Dy)*(By - Dy);
This is how we identify the type of quadrilateral based on the computed four sides and two diagonals.
if(distAB == distBC && distBC == distDC && distDC == distAD){if(distAC == distBD)cout << "A quadrilateral WXYZ is a Square \n";elsecout << "A quadrilateral WXYZ is a Rhombus \n";}else if(distAB == distDC && distAD == distBC){if(distAC == distBD)cout << "A quadrilateral WXYZ is a rectangle \n";elsecout << "A quadrilateral WXYZ is a parallelogram \n";}else{cout << "It is an irregular quadrilateral \n";}}// The same above code is written again for quadrilateral EFGH with different sides
Declaring functions and their syntax
Now, how can we get rid of this repetition issue?
In C++, a function is defined using a specific syntax that includes its signature and body. The signature of a function is composed of the return type, followed by the function name and a pair of parentheses (()
), which may contain {}
) and consists of a set of statements that are executed when the function is called. The basic syntax for a function is as follows:
// Function declarationreturnType functionName(type parm1, type parm2, ..., type paramN){// Function body}
Here, returnType
is the data type of the value the function returns. returnType
should be void
if the function doesn’t return a value. functionName
is what we name the function.
So, the next question is, “How can we call the specific function?” We can call it by just writing the function’s name followed by the
{..// wherever we need that function to perform a specific taskfunctionName(agrv1, argv2, ..., agrvN);}
Code implementation for identifying the quadrilateral type using functions
Let’s simplify the code of the above problem by replacing the repeated statements with functions to perform the desired behavior. For this purpose, we’ll create four functions:
The
power()
function that calculates the power of a number based on the base valuen
and the power valuek
. The function should have a return typeint
since the result is an integer that accumulates over multiplicationk
times.
Let’s look at the code and test it inmain()
.
#include <iostream>using namespace std;int power(int n, int k){int result = 1;if(k == 0)return n;while(k >= 1){result*=n;k--;}return result;}int main(){int n = 2;int k = 3;cout<< power(n, k);return 0;}
Lines 3–14: We implement the
power(int n, int k)
function, which can return the power of the provided values.
Let’s look at the following animation that provides us with the behavior of the memory for thepower
function:
The
euclideanDistanceSquare()
function calculates the distance square between two points,and , based on their coordinate values. So, we pass four values: p1x
,p1y
(which represents thepoint), p2x
, andp2y
(which represents thepoint) of type double
as input. The function should have a return typedouble
as the distance square would be a real value.
Let’s look at the following code:
#include <iostream>using namespace std;int power(int n, int k){int result = 1;if(k == 0)return n;while(k >= 1){result*=n;k--;}return result;}double euclideanDistanceSquare(double p1x, double p1y, double p2x, double p2y){double dist = 0;dist = power((p1x - p2x), 2) + power((p1y - p2y), 2);return dist;}int main(){double p1x = 2, p1y = 2,p2x = 6, p2y = 2;cout << euclideanDistanceSquare(p1x, p1y, p2x, p2y);return 0;}
For a quadrilateral, there are eight coordinate values:
Ax
,Ay
,Bx
,By
,Cx
,Cy
,Dx
, andDy
, which are passed as input to the functioncheckQuad()
. After calculating the sides and diagonals, this function evaluates the type of quadrilateral and returns astring
value containing the type of quadrilateral.To evaluate the type of quadrilateral, we need its sides and diagonals. Thus, we have implemented the function
evaluateQuad()
, which takes six parameters: the four sides of the square (distAB
,distBC
,distAD
, anddistDC
) and the two diagonals (distAC
anddistBD
), all of which are of the typedouble
. This function returns astring
value that represents the type of quadrilateral.
Let’s look at the following code:
#include <iostream>using namespace std;int power(int n, int k){int result = 1;if(k == 0)return n;while(k >= 1){result*=n;k--;}return result;}double euclideanDistanceSquare(double p1x, double p1y, double p2x, double p2y){double dist = 0;dist = power((p1x - p2x), 2) + power((p1y - p2y), 2);return dist;}string evaluateQuad(double distAB, double distDC, double distAD, double distBC, double distAC, double distBD){if(distAB == distBC && distBC == distDC && distDC == distAD){if(distAC == distBD)return "Square";elsereturn "Rhombus";}else if(distAB == distDC || distAD == distBC){if(distAC == distBD)return "Rectangle";elsereturn "Parallelogram";}else{return "Irregular quadrilateral";}}string checkQuad(int Ax, int Ay, int Bx, int By, int Cx, int Cy, int Dx, int Dy){//calculating Euclidean distance square between ABdouble distAB = euclideanDistanceSquare(Ax, Ay, Bx, By);//calculating Euclidean distance square between DCdouble distDC = euclideanDistanceSquare(Dx, Dy, Cx, Cy);//calculating Euclidean distance square between ADdouble distAD = euclideanDistanceSquare(Ax, Ay, Dx, Dy);//calculating Euclidean distance square between BCdouble distBC = euclideanDistanceSquare(Bx, By, Cx, Cy);//calculating Euclidean distance square between ACdouble distAC = euclideanDistanceSquare(Ax, Ay, Cx, Cy);//calculating Euclidean distance square between BDdouble distBD = euclideanDistanceSquare(Bx, By, Dx, Dy);string result = evaluateQuad(distAB, distDC, distAD, distBC, distAC, distBD);return result;}int main(){double Ax = 2, Ay = 2,Bx = 6, By = 2,Cx = 8, Cy = 5,Dx = 4, Dy = 5;// coordinate points for 2nd quadrilateraldouble Ex = 4, Ey = 5,Fx = 4, Fy = 10,Gx = 9, Gy = 10,Hx = 9, Hy = 5;cout <<"The type of quadrilateral ABCD is: " << checkQuad(Ax, Ay, Bx, By, Cx, Cy, Dx, Dy)<<endl;cout <<"The type of quadrilateral EFGH is: " << checkQuad(Ex, Ey, Fx, Fy, Gx, Gy, Hx, Hy)<<endl;return 0;}
Lines 4–15: We implement the
power()
function.Lines 16–21: We implement the
euclideanDistanceSquare()
function for calculating the sides and diagonals of the quadrilateral.Lines 36–57: We define the
checkQuad()
function to classify the type of quadrilateral by calling theevaluateQuad()
function with the calculated distances.
Summary
After adding some functions to remove the repetitive code, our program has become more interactive and reusable, thanks to the divide-and-conquer approach. For example, we made a separate function called evaluateQuad()
instead of putting its code inside the checkQuad()
function. This helps keep our code tidy and easy to understand as we break down the problem into smaller, more manageable parts. By using these smaller parts, we can perform different tasks without writing the same code again and again. This divide-and-conquer strategy makes our program more organized and clearer, just like following a step-by-step guide for solving a problem. As novice programmers, this technique simplifies complex challenges and empowers us to tackle programming tasks with greater ease and confidence!