POS/370
Programming
Concepts Using C++
Week 3
Newsletter (E. Nikjeh)
Hello Class,
Most
computer programs that solve real-world problems are much larger than the
programs presented in the class and your textbook.
Experience has shown that the best way to develop and maintain a large program
is to construct it from smaller pieces or components each, of which is more
manageable than the original program. This technique is called divide
and conquer.
A
function is a block of code that performs a task. Functions can greatly reduce
the amount of code you need to write by creating reusable modules. Functions
can create more self-documenting code, obtain more efficient code, and they can
reduce maintenance costs. You can recognize a function in a program by the parentheses
immediately following the function’s name. Each item of information within a
function’s parentheses is called an actual
argument. There are several motivations to use functions in a program. The
divide-and-conquer approach makes program development more manageable. Another
motivation is software reusability (using existing functions as building blocks
to create new programs). A third motivation is to avoid repeating code in a
program. Packaging code as a function allows the code to be executed from
several locations in a program simply by calling the function.
Built-in Function:
A built-in function is a function whose
task is predefined, and whose function definition (the
code that guides the function in completing its task) is prewritten and appears
outside of the program in which the function is used. The function definitions
are contained in files, called libraries,
that come with the language compiler and are available when we include a system
header file (e.g. #include <math.h> and #include<string>). Examples
(in class):
1- // To
calculate the side of the land which is in square shape
#include<iostream.h>
#include<math.h> // We need
this compiler directive to use Math. Functions
void main()
{
float
side = 0.0;
float
area = 0.0;
cout<<”Enter
the area of your land: “<<endl;
cin>>area; //In class we entered 283024 sqft
side
= sqrt(area); // sqrt is a
built-in-function which is in <math.h>
cout<<”The
side of the square shape of our land is “<<side<<endl;
// It prints
as a result 532
}
2-
// To calculate the length of a string and copy a
string to a string variable
#include<iostream.h>
#include<string> // We
need this to use built-in-functions for string manipulations
void main()
{
int counter = 0; //The
string length
char companyName [20] = “”;// The company name with max. 20
characters
char message[] = “”;
cout<<”Enter company name: “<<endl;
cin.getline(companyName,20); //We can read space also in company name
// We entered
Pacific Bell
counter =
strlen(companyName);
/* the strlen is a built-in-function, which can
calculate the number of characters in a string */
cout<<”The string length
is “<<counter<<endl;
strcpy(message,”This is a good
company”);
/* The strcpy is another
built-in-function, which can copy the second argument to its first argument */
cout<<”The message
is: “<<message<<endl;
// It prints The message is: This is a good company
}
3-
The pow built-in-function: pow(2,5) = 32
Programmer-defined function:
The
programmer can write functions to define specific tasks that could be used at
many points in a program. The actual statements defining the function are
written only once, and these statements are hidden from other functions. A
function is invoked (i.e., made to perform its designated task) by a function
call. The function call specifies the function name and provides information
(as arguments) that the called function needs to do its job. A real world
example is, a boss (the calling function or caller) asks a worker (the called
function) to perform a task and return (i.e., report back) the results when the
task is done. All variables declared in function definitions are local
variables. They are known only in the function in which they are defined.
Functions may or may not return information back to the calling program or
function. When they don’t return information, they are known as void functions. A void function is one that returns no data to its calling function
(caller). It is void (absent) of a return value. For example:
void
printMenu( )
{
cout<<”*** The Data-Base Program Ver1.0***”<<endl;
cout<<”1-
To add a name”<<endl;
cout<<”2-
To edit a name”<<endl;
cout<<”3-
To delete a name”<<endl;
cout<<”4-
Quit”<<endl;
}
//This function only prints
a menu and it doesn’t return a value to its caller
A
function that returns a value can be used anywhere an expression can be used.
For example:
monthlyPayment
= calcLoan(principal,rate,term);
or
If(calcLoan(principal,rate,term)
< = 1000.0)
monthlyPayment = monthlyPayment + 120.0;
else
monthlyPayment = monthlyPayment + 65.0;
or
cout<<”The monthly payment is:
“<<calcLoan(principal,rate,term)<<endl;
It
is a good idea to prototype our
functions above the main but below the
#include lines ending with a semicolon. So we inform the compiler that we will
define the function later. The function header is the first line of a function
that defines the return data-type, the function name, and the parameters (if
there is any) without semicolon at the end. For example:
Function prototype: float calcLoan(float
principal,float rate,int term);
or
float calcLoan(float ,float ,int
);
Function header: float calcLoan(float
principal,float rate,int term)
We
can call the function as follows:
monthlyPayment
= calcLoan(principal,rate,term);
In
the function header we can have different variable names like:
float calcLoan(float loanAmount, float interestRate, int
years)
{
-----
-----
}
We
call the variable loanAmount, interestRate, and years dummy variables.
Here
we pass the variables to the function by value (the value of principal to
loanAmount, the value of rate to interestRate, and the value of term to years).
This way of passing variables is called call
by value. The computer passes only the contents of the variable to the
receiving function. The receiving function is not given access to the variable
in memory, so it cannot change the value stored inside the variable. Passing a
variable’s address instead its value is called call by reference. It gives the receiving function access to the
variable being passed. So the receiving function can change the contents of the
variable (like the program example in the class). To pass a variable by
reference to a function, we include an ampersand (&) before the name of the
corresponding formal parameter in the function header. We also must include the
& in the function prototype after the data type. For example:
In function prototype: float calcLoan(float
&principal,float rate,int term);
or
float calcLoan(float &, float , int );
In function header: float calcLoan(float
&principal,float rate,int term)
The
variable principal is called by
reference and variables rate and term are called by value.
Global Variable:
If
we declare a variable with its data type above the main, we can use it in entire of our program even in any function
without declaring it again and we can change its value anywhere.
Selection (decision)
Structure:
When we want a program to make a decision or
comparison and then, based on the result of that decision or comparison, select
one of two paths. Most programming languages offer three forms of the selection
structure: if, if/else, and switch
(also called case). We have
different types of if statements as follows:
1- if (condition) one
statement; /* if condition is true, it
executes the statement and goes to the statement below if otherwise it goes to
the statement below if */
2- if (condition) { multiple
statements require braces}/* if condition is true it will execute the
statements inside the braces and then goes to the statement below the if */
3- if (condition) one statement;
else
one statement;
4- if (condition) {one or more statements}
else
{one or more
statements}
5- Nested if:
if (condition1) {one or more statements}
else
if (condition2) {one or more statements}
else
if(condition3) {one or more
statements}
else
. . .
if (condition N)
{one or more statements}
else {one
or more statements}
The
condition portion of the if statement can contain a
single statement or several compound expressions connected with logical
operators, but it can only yield a true or false answer. Try to avoid nesting
more than five levels.
Comparison (relational) operators:
operator operation Precedence
number
< <= less than, less than or equal to 1
> >= greater than, greater than or equal to 1
= = equal
to 2
!= not
equal to 2
Switch Statement: The switch statement allows
for multiple paths with default, but it can only compare the value of an int, short, long, or char data-type. Each path is specified
using the case keyword followed by
one or more statements ending with break
statement. The break would cause the switch to exit. For example:
Switch (gradeLetter)
{
case(‘A’):
cout<<”Excellent”<<endl;
break;
case(‘B’):
cout<<”very good”<<endl;
break;
case(‘C’):
cout<<”Good”<<endl;
break;
case(‘D’):
cout<<”Pass”<<endl;
break;
case(‘F’):
cout<<”Please take the course again”<<endl;
break;
default: cout<<”Wrong letter
grade entered”<<endl;
break;
} //The
switch multiple-selection structure with breaks
Four
program examples in the class: Example 1-
/* This program reads a string with a space and prints it. It
also uses the string built in functions to calculate the string length and to
copy a string to a string variable. It also calculates the side of a square
land that we have its area by using math built in function */
#include<iostream.h>
#include<string>
#include<math.h>
void main( )
{
float area
= 0.0;
float side
= 0.0;
char
message[] = ""; // This is array of characters (string) with any
number of characters
char
coName[] = "";
int counter
= 0;
cout<<"Enter
the company name"<<endl;
cin.getline(coName,20 );//We
can read the company name(max 20 characters) with space
cout<<"The
company name is "<<coName<<endl;
counter = strlen(coName);//
strlen(built in function) calculates string length of a string
cout<<"The number of
the string is "<<counter<<endl;
strcpy(message,"This
is a good company");// strcpy copies the second string to the first
cout<<message<<endl;
cout<<"Enter
the area of your land: "<<endl;
cin>>area;
side =
sqrt(area);// sqrt is built in function to calculate square root of a number
cout<<"the
side is "<<side<<endl;
}
2-
// This program calculates the monthly payment of your loan
#include<iostream.h>
#include<math.h>
void main( )
{
double
payment = 0.0;// monthly payment
double
principal = 0.0;// loan amount
double rate
= 0.0;// interest rate
int term =
30;// the loan term which is 30 years
cout<<"Enter
your loan principal: \n";
cin>>principal;
cout<<"Enter
the loan interest rate: "<<endl;
cin>>rate;
rate =
rate/(double)12.0;// to find the rate for one month
term = term*12;//
to find the term in months
payment =
principal*rate / (1.0 - pow(rate + 1.0,
-(double)term));// formula to calculate
cout<<"Your
monthly payment is $"<<payment<<endl;
}
3-
// This program calculates monthly payment for your loan using
function (call by value)
#include
<iostream.h>
#include
<math.h>
#include<iomanip.h>
// This is a function prototype
double loanCalc(double principal,double
rate);
int term = 30; // term is a
global variable
void main()
{
double
principal = 0.0;
double
payment = 0.0;
double rate
= 0.0;
double totalPayments = 0.0;
cout<<"Enter the principal: "<<endl;
cin>>principal;
cout<<"Enter the annual interest rate:
"<<endl;
cin>>rate;
payment = loanCalc(principal,rate);// It
calls the function loanCalc
cout<<"The payment is
$"<<payment<<endl;
totalPayments = 360.0 * payment;
cout<<setiosflags(ios::fixed);// displys in fixed
point notation
cout<<"your total payments after 30 years
is $"<<totalPayments<<endl;
}
// This function calculates the monthly payment
//
program-defined function
double loanCalc(double principal,double
rate)
{
double mpayment =0.0;// local variable
rate =
rate/(double)12.0;
term =
term*12;
mpayment = principal*rate/(1.0 - pow(rate+1.0,-(double)term));
cout<<"Your monthly payment is
$"<<setprecision(5)<<mpayment<<endl;
cout<<"Your
term is "<<setw(10)<<term/12<<" years
fixed."<<endl;
return mpayment;
}
4-
// This program calculates the monthly payment of your loan using function (call by reference)
#include<iostream.h>
#include<math.h>
#include<iomanip.h>
// The user-defined function to calculate the payment
double calcLoan(double &,double );// Function prototype to calculate the
monthly payment
void title( ); /* Function
prototype-It prints the title of the program. It is void because it doesn’t return any value */
//
term is global variable and we can use it without declaration in the entire
program
int
term = 0;
void main( )
{
double
payment = 0.0;//monthly payment
double
principal = 0.0;// loan amount
double rate
= 0.0;// interest rate
title( );//
it calls the function to print the title
cout<<"Enter
your loan principal: \n";
cin>>principal;
cout<<"Enter
the loan interest rate: "<<endl;
cin>>rate;
cout<<"Enter
the term of your loan: "<<endl;
cin>>term;
payment =
calcLoan(principal,rate);
cout<<"Your
monthly payment is $"<<payment<<endl;
cout<<setiosflags(ios::fixed);
//We can have fixed point instead floating point
// setprecision(2)
is a built in function. It shows two digits after decimal point
cout<<"The
pricipal is $"<<setprecision(2)<<principal<<endl;
}
// This function calculates the monthly payment and returns a
value
double
calcLoan(double &loanAmount,double intRate) // call by reference loanAmount
{
double mPayment = 0.0;
rate =
rate/(double)12.0;
term =
term*12;
mPayment = loanAmount*intRate / (1.0 - pow(intRate + 1.0,
-(double)term));
loanAmount = loanAmount*2;
return
mPayment;
}
// This function prints the title and it doesn’t return any
value so it is void
void title( )
{
cout<<" *** The calculation for loan
process ***"<<endl;
}
5-
// To read a grade and to print the grade letter
#include
<iostream.h>
void main()
{
float grade
= 0.0;
char gletter = ' ';
cout<<"Enter your grade: "<<endl;
cin>>grade;
if(grade
> 100.0) cout<<"Wrong
grade entry"<<endl;
else
if(grade
>= 90.0)
{
cout<<"Your grade letter is
A"<<endl;
gletter = 'A';
}
else
if(grade
>= 80.0)
{
cout<<"Your grade
letter is B"<<endl;
gletter = 'B';
}
else
if(grade >= 70.0)
{
cout<<"Your grade
letter is C"<<endl;
gletter = 'C';
}
else
if(grade >= 60.0)
{
cout<<"Your grade
letter is D"<<endl;
gletter = 'D';
}
else
{
cout<<"Your grade
letter is F \n You are failed\n";
gletter = 'F';
}
switch (gletter)
{
case('A'): cout<<"Excellent"<<endl;
break;
case('B'): cout<<"Very good"<<endl;
break;
case('C'): cout<<"Good"<<endl;
break;
case('D'): cout<<"Bad"<<endl;
break;
case('F'): cout<<"Please take the course
again"<<endl;
break;
default: cout<<"Wrong letter grade
entered"<<endl;
cout<<"Please
enter grade letter again"<<endl;
break;
}
}
It
is a good programming practice if you run these programs again.
Have
a nice day.
See
you in class
Esmaail M Nikjeh