Uploaded by يونس الناعبي

05 Modularity sp2020

advertisement
ENGR2217: Programming for Engineers
Lecture 5: Modularity (Functions)
Sl i d es a re a d a pted f rom t h os e p rovi d ed w i t h t h e Tex t b ook :
C + + p rog ra mming: f rom p rob l em a n a lys is to p rog ra m
d es i gn, s i x t h ed i t ion
Introduction
• Functions are often called modules
• They are like miniature programs that can be
combined to form larger programs
• They allow complicated programs to be divided
into manageable pieces
• There are two types of functions: predefined and
user-defined
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
2
Program without functions
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double length,width,m,n,area;
cout<<"Please enter the length and width of the rectangle"<<endl;
cin>>length>>width;
area= length*width;
cout<<"The area of the rectangle ="<<area<<endl;
m=sqrt(length+width);
n=length-width;
area= m*n;
cout<<"The area of the rectangle ="<<area<<endl;
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
3
Predefined Functions
• In C++, a function is similar to that of a
function in algebra
– It has a name
– It does some computation
• Some of the predefined mathematical
functions are:
sqrt(x)
pow(x, y)
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
floor(x)
4
Predefined Functions [cont.]
• Predefined functions are organized into
separate libraries. For example:
– I/O functions are in iostream header
– Math functions are in cmath header
• To use predefined functions, you must include
the header file using an include statement
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
5
User-Defined Functions
• These functions are developed by you!
• Two Types:
– Value-returning functions: have a return type. They return
a value of a specific data type using the return statement
– Void functions: do not have a return type. They do not
require a return statement. However, a return can be
added optionally.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
6
Value-Returning Functions
• To use these functions, you must:
– Include the appropriate header file in your program using
the include statement
Example
– Know the following items:
•
•
•
•
Name of the function
Number of parameters, if any
Data type of each parameter
Data type of the value returned:
called the type of the function
int abs(int number)
{
if (number < 0)
number = -number;
return number;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
7
Value-Returning Functions [cont.]
• Can use the value returned by this type of
function to:
– Save it for further calculation
– Use it in some calculation
– Print it
• A value-returning function is used in an
assignment or in an output statement
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
8
Value-Returning Functions [cont.]
• Heading (or function header): first line of the function
– Example: int abs(int number)
• Formal parameter: variable declared in the heading
– Example: number
• Actual parameter: variable or expression listed in a call
to a function
– Example: x = abs(value)
NOT: The word argument is sometimes used instead of parameter
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
9
Syntax: Value-Returning Function
• Syntax:
•
functionType is also
called the data type or
return type
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
10
Syntax: Formal Parameter List
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
11
Function Call
• Syntax to call a value-returning function:
• Examples:
X = function1(param1, param2, param3);
Y = function2(param1, param2);
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
12
Syntax: Actual Parameter List
• Syntax of the actual parameter list:
• Formal parameter list can be empty:
• A call to a value-returning function with an
empty formal parameter list is:
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
13
Syntax: return Statement
• Syntax:
• In C++, return is a reserved word
• When a return statement executes
– Function immediately terminates
– Control goes back to the caller
• When a return statement executes in the
function main, the program terminates
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
14
Syntax: return Statement [cont.]
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
15
Value-Returning Functions:
Some Peculiarities
What happened if
x ≤ 5?
Always return a value with
the same function datatype!
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
16
Void Functions:
Even Odd
Check whether a number is even
or odd
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
17
#include <iostream>
using namespace std;
void printEvenOdd(int number) {
if (number % 2 == 0) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
printEvenOdd(number);
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
18
Non Void function
#include <iostream>
using namespace std;
bool isEven(int number) {
if (number % 2 == 0) {
return true; // number is even
} else {
return false; // number is odd
}
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
19
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isEven(number)) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
20
Value-Returning Functions:
Factorial
Compute and display factorial of
any number n using functions
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
21
Value-Returning Functions:
Factorial
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a positive integer: ";
cin >> num;
unsigned long long result = factorial(num);
cout << "Factorial of " << num << " = " << result << endl;
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
22
Value-Returning Functions:
Factorial
unsigned long long factorial(int n) {
unsigned long long result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
23
Factorial using return
#include <iostream>
using namespace std;
unsigned long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
unsigned long long result = factorial(6);
cout << "Factorial is = " << result << endl;
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
return 0;
24
Print Numbers
User is prompted to enter start and
end numbers:
Print Numbers from start to end
using function
e.g. Enter start: 8
Enter end: 12
Program outputs: 8 9 10 11 12
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
25
Print Numbers
#include <iostream>
using namespace std;
void printNumbers(int start, int end) {
for (int i = start; i <= end; ++i) {
cout << i << " ";
}
cout << endl;
}
int main() {
int startNum, endNum;
cout << "Enter the start number: ";
cin >> startNum;
cout << "Enter the end number: ";
cin >> endNum;
printNumbers(startNum, endNum);
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
26
Flow of Execution
• Execution always begins at the first statement
in the function main
• Other functions are executed only when called
• Function prototypes appear before any
function definition
– Compiler translates these first
• Compiler can then correctly translate a
function call
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
27
Flow of Execution [cont.]
• Function call transfers control to the first
statement in the body of the called function
• When the end of a called function is executed,
control is passed back to the point immediately
following the function call
– Function’s returned value replaces the function
call statement
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
28
Flow of Execution [cont.]
int main()
{
int x = 5;
int y;
int abs(int number)
{
if (number < 0)
number = -number;
3
1
// ....
2
y = abs(x);
4
// ....
5
return number;
}
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
29
Void Functions
• User-defined void functions can be placed
either before or after the function main
• If user-defined void functions are placed after
the function main
– The function prototype must be placed before the
function main
• Void function does not have a return type
– return statement without any value is typically
used to exit the function early
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
30
Void Functions [cont.]
int main()
{
int x = 5;
void display (int number)
{
cout << number;
1
// ....
2
3
display(x);
return;
4
// ....
}
5
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
31
Scope of an Identifier
• Scope of an identifier: where in the program
the identifier is accessible
• Local identifier: identifiers declared within a
function (or block)
• Global identifier: identifiers declared outside
of every function definition
• C++ does not allow nested functions
– Definition of one function cannot be included in
the body of another function
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
32
Scope of an Identifier [cont.]
• Local vs. Global Identifier
int main()
{
int x = 5;
// ....
cout << x;
// ....
int x
int main()
{
// ....
x = 5;
cout << x;
// ....
return 0;
}
x is local, only visible within
the function main
return 0;
}
x is global, it is visible in all functions
within the same program
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
33
//Scope Example - What is the output
#include <iostream>
using namespace std;
void a();//Function prototypes
void b();
int x=1;
//Global (file scope)
int main()
{ int x=5; //Local to main
cout << "before call to a, x= " << x << endl;
cout << "global x is " << ::x << endl;
a();
cout << "after call to a, x= " << x << endl;
cout << "global x is " << ::x << endl;
b();
cout << "after call to b, x= " << x << endl;
cout << "global x is " << ::x << endl;
b();
cout << "after 2nd call to b, x= " << x << endl;
cout << "global x is " << ::x << endl;
return(0);
}
void a()
{ int x=25;
//Local to a
x++;
}
void b()
{
x++;
}
• In the main() function, we declare a local variable x with an
initial value of 5, which shadows the global variable x. We
then print the values of x and ::x (the global x) using cout.
• We then call the function a(), which declares a local variable x
with an initial value of 25 and adds 1 to it. However, this x is a
different variable than the x in main(), so the changes to x in
a() have no effect on x in main().
• We then print the values of x and ::x again, followed by two
calls to the function b(). The b() function simply adds 1 to the
global variable x, which is then printed out.
• As you can see, the local variable x in main() is not affected by
the changes made to the local variable x in a(). However, the
global variable x is modified by the calls to b().
35
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
Scope Example - Output
before call to a, x= 5
global x is 1
after call to a, x= 5
global x is 1
after call to b, x= 5
global x is 2
after 2nd call to b, x= 5
global x is 3
Static Storage Class
• static - key word static
– Requests that memory for a local variable be reserved throughout the
execution life of the program. The static storage class does not affect
the scope of the variable.
– When a variable is declared as static inside a function, it retains its
value between function calls, i.e., its value is preserved across function
calls.
Static Class
• x=0
• x=1
• x=2
#include <iostream>
using namespace std;
void function() {
static int x = 0;
cout << "x = " << x << endl;
x++;
}
int main() {
function();
function();
function();
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
38
• In the main() function, we call the function() function three
times.
• When function() is called the first time, the value of x is 0,
which is printed to the console. We then increment the value
of x by 1.
• When function() is called the second time, the value of x is 1,
which is printed to the console. We then increment the value
of x by 1 again.
• When function() is called the third time, the value of x is 2,
which is printed to the console. We then increment the value
of x by 1 again.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
39
//Storage Class Example - What is the output
#include <iostream>
using namespace std;
void donothing();
int main()
{
donothing();
donothing();
donothing();
return(0);
}//endmain
x is 1, y is 1
x is 1, y is 2
x is 1, y is 3
void donothing()
{
int x=0;
static int y=0;
x++;
y++;
cout <<“x is ”<< x << “, y is ” << y << endl;
return;
}//end donothing
Parameter Passing
• C++ supports two forms of parameter passing:
– Pass by value.
– Pass by reference.
Pass by Value
– Pass by value is the default in C++
(except when passing arrays as arguments to functions).
– The formal parameter is a distinct variable initialized with the
value of the argument.
• The argument is an expression that is evaluated when the function is
called to determine the value of the formal parameter.
– Changes to the formal parameter do not affect the argument.
Example
int fact(int);
int main()
{
int n, factorial; //1
cin >> n; //2
if(n>=0)
{
factorial = fact(n); //3
cout << n <<"! is "
<< factorial << endl;//7
} //end if
return 0;
} //end main
//Function Definition
int fact(int num) //4
{
int nfact = 1; //5
while(num>1)
{
nfact = nfact*num;
num--;
}
return(nfact); //6
} //end fact
int fact(int);
int main()
{
int n, factorial; //1
cin >> n; //2
if(n>=0)
{
factorial = fact(n); //3
cout << n <<"! is "
<< factorial << endl;//7
} //end if
return 0;
} //end main
int fact(int num) //4
{
int nfact = 1; //5
while(num>1)
{
nfact = nfact*num;
num--;
}
return(nfact); //6
} //end fact
call fact()
Memory
Snapshot:
main()
fact()
4-> int num 3
int factorial ?
2 ->
3
?
3
6
1
6->
return nfact
1-> int n
?
3 ->
7 ->
//Function Definition
5-> int nfact
1
6
Note: value of n in
main has not
changed.
Pass by Reference
• Pass by reference allows modification of a function
argument.
• Must append an & to the parameter data type in
both the function prototype and function header
void getDate(int& day, int& mo, int& year)
• Formal parameter becomes an alias for the
argument.
– The argument must be a variable of a compatible type.
• Any changes to the formal parameter directly change
the value of the argument.
• In C++, passing a variable by reference
allows a function to modify the original
variable that was passed as an argument.
• In contrast, passing a variable by value
creates a copy of the variable that the
function can modify without affecting the
original variable.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
46
Parameter passing
• By value
• By reference
void foo(int x) {
x++;
cout << "x inside
foo: " << x << endl;
}
void bar(int &x) {
x++;
cout << "x inside bar: "
<< x << endl;
}
int main() {
int x = 5;
foo(x);
cout << "x after
foo: " << x << endl;
return 0;
}
x inside foo: 6
x after foo: 5
int main() {
int x = 5;
bar(x);
cout << "x after bar: "
<< x << endl;
return 0;
}
x inside bar: 6
x after bar: 6
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
47
Parameter passing
• By value
void addOne(int x) {
x += 1;
}
int main() {
int a = 5;
addOne(a);
cout << "a after
addOne: " << a << endl;
return 0;
}
a after addOne: 5
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
• By reference
void addOne(int &x) {
x += 1;
}
int main() {
int a = 5;
addOne(a);
cout << "a after addOne:
" << a << endl;
return 0;
}
a after addOne: 6
48
Parameter passing
• By value
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
cout << "x: " << x <<
", y: " << y << endl;
return 0;
}
x: 5, y: 10
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
• By reference
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
cout << "x: " << x << ",
y: " << y << endl;
return 0;
}
x: 10, y:5
49
#include <iostream>
using namespace std;
void modify(int& a, int b) {
a += 1;
// modify the reference parameter
b += 1;
// modify the value parameter
}
int main() {
int x = 5;
int y = 7;
modify(x, y);
cout << "x = " << x << endl;
// outputs "x = 6"
cout << "y = " << y << endl;
// outputs "y = 7"
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
50
• In the modify function, the first parameter a is
passed by reference, which means that any
changes made to it will affect the original x
variable outside the function.
• The second parameter b is passed by value,
which means that any changes made to it will
not affect the original y variable outside the
function.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
51
• These two lines modify the values of a and b
inside the modify function.
• Because a is passed by reference, any changes
made to it inside the function will also affect
the value of the variable that was passed in as
an argument.
• However, because b is passed by value, any
changes made to it inside the function will not
affect the original variable outside the
function.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
52
• In the main function, the modify function is
called with x and y as arguments.
• After the function call, x has been
incremented by 1 because a was modified
inside the function, but y remains unchanged
because b was only modified inside the
function and did not affect the original y
variable.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
53
#include <iostream>
using namespace std;
void increment(int x) {
x++;
}
x after increment: 5
x after increment_by_reference:
6
void increment_by_reference(int &x) {
x++;
}
int main() {
int x = 5;
increment(x);
cout << "x after increment: " << x <<
endl;
increment_by_reference(x);
cout << "x after
increment_by_reference: " << x << endl;
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
54
• The increment() function takes an integer parameter x by
value and increments it.
• The increment_by_reference() function takes an integer
parameter x by reference and increments it.
• In the main() function, we declare an integer variable x and
initialize it to 5.
• We then call the increment() function, passing x as an
argument. However, because x is passed by value, the
increment() function creates a copy of x, increments the copy,
and then discards the copy when the function returns.
• Therefore, the value of x in main() remains unchanged.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
55
• Next, we call the increment_by_reference()
function, passing x as a reference. Because x is
passed by reference, the
increment_by_reference() function modifies
the original variable x by incrementing it.
Therefore, the value of x in main() is
incremented by 1.
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
56
#include <iostream>
void swapNumbers(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swapNumbers(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
C++ Programming: From Problem Analysis to Program Design, Sixth Edition
57
Example
#include <iostream>
using namespace std;
void swap(double&, double&);
//function prototype
int main(){
double x=5, y=10;
swap(x,y);
//function call; x y are
arguments
cout >> “x = “ << x << ‘,’ << “ y= “ << y << endl;
return 0;
} //end main
Output is:
x = 10, y = 5
Example
//Function swap interchanges the values of
//two variables
void swap(double& x, double& y)
{
double temp; //local variable temp
temp = x;
x=y;
y=temp;
return;
//optional return statement
} //end swap
Program Trace: pass by reference
#include <iostream>
using namespace std;
//Function Definition
void swap(double&, double&); //prototype
int main()
{
double x=5, y=10;
swap(x,y);
//x y are arguments
cout << "x = " << x << ','
<< " y= " << y << endl;
return 0;
} //end main
Memory
Snapshot:
main()
void swap(double& x, double& y)
{
double temp;
temp = x;
x=y;
y=temp;
return;
}//end swap
swap()
double x
double y
double
temp
?
5
double x
5
double y
10
call
swap()
Program Trace: pass by reference
#include <iostream>
using namespace std;
//Function Definition
void swap(double&, double&); //prototype
int main()
{
double x=5, y=10;
swap(x,y);
//x y are arguments
cout << "x = " << x << ','
<< " y= " << y << endl;
return 0;
} //end main
Memory
Snapshot:
main()
void swap(double& x, double& y)
{
double temp;//
temp = x;
x=y;
y=temp;
return;
//optional
}//end swap
swap()
double x
double y
double
temp
?
5
double x
10
double y
10
Program Trace: pass by reference
#include <iostream>
using namespace std;
void swap(double&, double&); //prototype
int main()
{
double x=5, y=10;
swap(x,y);
//x y are arguments
cout << "x = " << x << ','
<< " y= " << y << endl;
return 0;
} //end main
Memory
Snapshot:
main()
//Function Definition
void swap(double& x, double& y)
{
double temp;//
temp = x;
x=y;
y=temp;
return;
//optional
}//end swap
swap()
double x
double y
double
temp
?
5
double x
10
double y
5
return;
Program Trace: pass by reference
#include <iostream>
using namespace std;
void swap(double&, double&); //prototype
int main()
{
double x=5, y=10;
swap(x,y);
//x y are arguments
cout << "x = " << x << ','
<< " y= " << y << endl;
return 0;
} //end main
//Function Definition
void swap(double& x, double& y)
{
double temp;//
temp = x;
x=y;
y=temp;
return;
//optional
}//end swap
Memory
Snapshot:
main()
double x 10
double y
5
Arguments have been
modified
// Comparing pass-by-value and pass-by-reference
with references.
#include <iostream>
using namespace std;
int squareByValue( int );
// function prototype
void squareByReference( int & );
// function prototype
int main() {
int x = 2;
int z = 4;
// demonstrate squareByValue
cout << "x = " << x << " before squareByValue\n";
cout << "Value returned by squareByValue: "
<< squareByValue( x ) << endl;
cout << "x = " << x << " after squareByValue\n" << endl;
// demonstrate squareByReference
cout << "z = " << z << " before squareByReference" << endl;
cout << "Value returned by squareByReference: "
<< squareByReference( z ) << endl;
cout << "z = " << z << " after squareByReference" << endl;
return 0;
} // end main
// indicates successful termination
// squareByValue multiplies number by itself, stores the
Changes number, but original
// result in number and returns the new value of
number(x) is not modified.
parameter
int squareByValue( int number )
{
return number *= number;
// caller's argument not modified
} // end function squareByValue
Changes numberRef,
alias for the original
// squareByReference multiplies numberRef by itself an
and
parameter. Thus, z is
changed.
// stores the result in the variable to which numberRef
refers in
function main
void squareByReference( int &numberRef )
{
numberRef *= numberRef;
x = 2 before squareByValue
Value returned by squareByValue: 4
// caller's argument modified
x = 2 after squareByValue
} // end function squareByReference
z = 4 before squareByReference
Value returned by squareByValue: 16
z = 16 after squareByReference
Practice! - What is the output?
#include <iostream>
using namespace std;
void fun(int&, int&, int);
int main()
{ int c1=1, c2=2, c3=3;
cout << c1 << ‘,’ << c2 << ‘,’ << c3 << endl;
fun(c1,c2,c3);
cout << c1 << ‘,’ << c2 << ‘,’ << c3 << endl;
fun(c3, c2, c1);
cout << c1 << ‘,’ << c2 << ‘,’ << c3 << endl;
return 0;
}
void fun(int& a1, int& a2, int a3)
{ a1++;
1,2,3
a2++;
2,3,3
a3--;
2,4,4
}
Functions with default parameters
#include <iostream>
// Function that calculates the volume of a box
double calculateBoxVolume(double length, double width, double
height, double density = 1.0) {
double volume = length * width * height;
return volume * density;
}
67
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Functions with default parameters
int main() {
double length = 5.0, width = 3.0, height = 2.0;
double density = 0.7; // Density of the material
double volume1 = calculateBoxVolume(length, width,
height);
double volume2 = calculateBoxVolume(length, width, height,
density);
cout << "Volume without density: " << volume1 << endl;
cout << "Volume with density: " << volume2 << endl;
return 0;
}
68
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Function Overloading
Using function overloading, we can call the same function
based on the number and types of arguments passed to it.
The compiler will determine the correct function to execute
at compile time.
69
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Function Overloading
#include <iostream>
// Function to calculate the area of a rectangle
double calculateArea(double length, double width) {
return length * width;
}
// Function to calculate the area of a circle
double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
70
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Function Overloading
int main() {
double rectangleLength = 5.0, rectangleWidth = 3.0;
double circleRadius = 2.5;
cout << "Area of the rectangle: " <<
calculateArea(rectangleLength, rectangleWidth) << endl;
cout << "Area of the circle: " <<
calculateArea(circleRadius) << endl;
return 0;
}
71
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
An arithmetic series with fractions is a sequence of
numbers where each term after the first is found by
adding a fixed, constant fraction to the previous term.
The general form of an arithmetic series with fractions
is:
Sum = a + (a + d) + (a + 2d) + (a + 3d) + ... + (a + (n1)d)
where 'a' is the first term, 'd' is the common difference
(which can be a fraction), and 'n' is the number of
terms in the series.
72
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
Consider the arithmetic series with the first term 'a' as 1/2 and the
common difference 'd' as 1/3. We will calculate the sum of the first
5 terms in the series.
The general form of the series is:
Sum = a + (a + d) + (a + 2d) + (a + 3d) + (a + 4d)
Given: a = ½; d = 1/3
Calculating the series:
Sum = 1/2 + (1/2 + 1/3) + (1/2 + 2/3) + (1/2 + 3/3) + (1/2 + 4/3)
Sum = 1/2 + 5/6 + 7/6 + 3/2 + 11/6
Sum = (1 + 5 + 7 + 9 + 11) / 6
Sum = 33/6
Sum = 11/2
73
So, the sum of the first 5 terms in the arithmetic series with
FROM PROBLEM ANALYSIS TO PROGRAM
fractions is 11/2. C++ PROGRAMMING:
DESIGN, SIXTH EDITION
Arithmetic Series
#include <iostream>
using namespace std;
// Function to calculate the sum of an arithmetic series with
fractions
double arithmeticSumWithFractions(double firstTerm, double
commonDifference, int numTerms) {
double sum = 0.0;
for (int i = 0; i < numTerms; i++) {
sum += firstTerm + i * commonDifference;
}
return sum;
}
74
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
int main() {
double firstTerm, commonDifference;
int numTerms;
cout << "Enter the first term of the arithmetic series with
fractions: ";
cin >> firstTerm;
cout << "Enter the common difference (as a fraction): ";
cin >> commonDifference;
cout << "Enter the number of terms: ";
cin >> numTerms;
double sum = arithmeticSumWithFractions(firstTerm,
commonDifference, numTerms);
cout << "Sum of the arithmetic series with fractions: " << sum
<< endl;
75 return 0;
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
An arithmetic series of even numbers is a sequence of
numbers where each term after the first is the next even
number. The general form of the series is:
Sum = 2 + 4 + 6 + 8 + ... + (2n)
76
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
#include <iostream>
using namespace std;
int sumOfEvenNumbersInRange(int start, int end) {
int sum = 0;
cout << "Even Numbers: ";
for (int i = start; i <= end; i++) {
if (i % 2 == 0) {
sum += i;
cout<<i<<" ";
}
}
cout << endl;
return sum;
}
77
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
int main() {
int start, end;
cout << "Enter the starting number: ";
cin >> start;
cout << "Enter the ending number: ";
cin >> end;
int sum = sumOfEvenNumbersInRange(start, end);
cout << "Sum of even numbers in the range: " << sum <<
endl;
return 0;
}
78
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
#include <iostream>
using namespace std;
// Function to calculate the sum of even numbers in an
arithmetic series
int sumOfEvenNumbers(int numTerms) {
int sum = 0;
for (int i = 1; i <= numTerms; i++) {
sum += 2 * i;
}
return sum;
}
79
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Arithmetic Series
int main() {
int numTerms;
cout << "Enter the number of terms in the arithmetic series
of even numbers: ";
cin >> numTerms;
int sum = sumOfEvenNumbers(numTerms);
cout << "Sum of the arithmetic series of even numbers: " <<
sum << endl;
return 0;
}
80
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Geometric Series
A geometric series is a series of numbers in which
each term after the first is found by multiplying the
previous one by a fixed, non-zero number called the
common ratio.
The general form of a geometric series is:
Sum = a + ar + ar^2 + ar^3 + ... + ar^n-1
Where 'a' is the first term, 'r' is the common ratio, and
'n' is the number of terms in the series.
To calculate the sum of a geometric series in C++,
◦ We can use a loop to iterate through the terms
◦ and calculate the sum.
81
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Geometric Series
Write a C++ code using functions:
◦ Ask the user to input the first term ('a') of the geometric
series.
◦ Ask the user to input the common ratio ('r') of the
geometric series.
◦ Ask the user to input the number of terms ('n') in the
geometric series.
◦ Use a function with loop to calculate the sum of the series
by adding each term to the previous term.
◦ The function returns sum
◦ Display the sum of the geometric series.
82
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Geometric Series
#include <iostream>
#include <cmath> // Include this header to use pow() function
for exponentiation
using namespace std;
// Function to calculate the sum of a geometric series
double geometricSum(double firstTerm, double commonRatio, int
numTerms) {
double sum = 0.0;
for (int i = 0; i < numTerms; i++) {
sum += firstTerm * pow(commonRatio, i);
}
return sum;
}
83
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Geometric Series
int main() {
double firstTerm, commonRatio;
int numTerms;
cout << "Enter the first term of the geometric series: ";
cin >> firstTerm;
cout << "Enter the common ratio: ";
cin >> commonRatio;
cout << "Enter the number of terms: ";
cin >> numTerms;
double sum = geometricSum(firstTerm, commonRatio,
numTerms);
cout << "Sum of the geometric series: " << sum << endl;
84
return 0;
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Geometric Series – Output Series/ Sum
#include <iostream>
#include <cmath>
using namespace std;
// Function to calculate the sum of a geometric series
double geometricSum(double firstTerm, double commonRatio, int
numTerms) {
double sum = 0.0;
cout << "Geometric Series: ";
for (int i = 0; i < numTerms; i++) {
double term = firstTerm * pow(commonRatio, i);
sum += term;
cout << term;
if (i != numTerms - 1) {
cout << " , ";
}
}
cout << endl;
return sum;
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
85 }
DESIGN, SIXTH EDITION
Fabbonaci Series
The Fibonacci series is a sequence of numbers in
which each number is the sum of the two preceding
ones, usually starting with 0 and 1. The general form of
the Fibonacci series is:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
86
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Fibonacci Series
#include <iostream>
using namespace std;
// Function to generate the Fibonacci series
void fibonacciSeries(int numTerms) {
int prev = 0, current = 1, nextTerm;
cout << "Fibonacci Series: ";
for (int i = 0; i < numTerms; i++) {
cout << prev << " ";
nextTerm = prev + current;
prev = current;
current = nextTerm;
}
}
87
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Fibonacci Series
int main() {
int numTerms;
cout << "Enter the number of
terms in the Fibonacci series:
";
cin >> numTerms;
fibonacciSeries(numTerms);
return 0;
}
88
C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM
DESIGN, SIXTH EDITION
Download