Module 02
Module 02
ELEMENTARY
PROGRAMMING
LEARNING OBJECTIVES
1. Develop C++ programs that conduct basic calculations.
2. Develop C++ programs to read input from the keyboard.
3. Select appropriate names for variables and functions using identifiers.
4. Store data using variables.
5. Employ assignment statements and expressions to construct C++ programs.
6. Name constants using the const keyword.
7. Utilize numeric data types when defining variables.
8. Represent integers and floating-point values using scientific notation.
9. Perform operations with the operators +, -, *, /, and %.
10. Perform exponentiation using the pow(a, b) function.
11. Write expressions and evaluate their results.
12. Obtain the current system time using time(0).
13. Utilize added assignment operators (+=, -=, *=, /=, %=).
14. Distinguish between postincrement and preincrement, and postdecrement
and predecrement operations.
15. Perform type conversion (casting) to change the data type of a number.
16. Follow the software development process to address challenges.
17. Avoid common errors in fundamental programming.
LOADING YOUR KNOWLEDGE
Developing critical programming skills for problem-solving is the main goal
of this course. You gained knowledge of how to design straightforward programs,
comprehend how to compile and run them, and do so in Module 1. You will now
look into how problem-solving computer programs are made. You will be able to
understand the fundamental ideas of programming, such as simple data types,
variables, constants, operators, expressions, and input and output operations,
by working through a number of problem scenarios.
Consider that you want to apply for a student loan. How can a program
that determines your monthly payment and total payment be developed using the
loan amount, loan duration, and annual interest rate? You will be shown how to
make such programs in this lesson. You'll learn the fundamental techniques for
problem analysis, solution design, and program development along the way.
LESSON 01
WRITING A SIMPLE PROGRAM
LET’S PROCESS
The primary goal of the lesson is to teach students fundamental
programming problem-solving techniques.
Consider the simple task of determining a circle's area. How may this task be
accomplished by a tool? Designing algorithms and converting them into programming
instructions, or code, are steps in the process of creating a program. An algorithm specifies
the actions that must be performed in a particular sequence in order to solve a problem.
Algorithms can be used by programmers to design their projects before they are actually
implemented in a particular programming language. Both ordinary English and pseudocode,
which combines plain language with some programming code, can be used to describe
algorithms. The design and development of a program employing IPO (Input-Process-Output)
concepts and pseudocode are covered in module one.
INPUT
1. Read in the circle’s radius.
PROCESS
1. Apply the following formula to get the area:
area = radius * radius * p
OUTPUT
1. Display the result.
When you code, that is, when you create a program, you turn an algorithm into a
program. You are already aware that a C++ program begins execution in the main function.
Here, the fundamental role would be described as follows:
The user's entered radius from the keyboard must be read by the application. This
brings up two crucial issues:
Let's start with the second problem. The program must declare a variable in order to
store the radius as a symbol. A value that is kept in the computer's memory is represented by
a variable.
It is recommended to use descriptive names that clearly explain the function of the
variables rather than generic variable names like x and y. In this instance, the variables are
suitably named radius and area to record the radius value and calculated area, respectively.
In order to educate the compiler about the nature of these variables, their data types
must be provided. A variable may hold an integer, a floating-point number, a character, or a
Boolean value depending on the data type. The procedure for achieving this involves declaring
variables. In C++, the basic data types such as integers, floating-point numbers with decimal
places, characters, and Boolean values are available as simple data types. These data types
are also referred to as basic or primitive data types.
Create double-precision floating-point definitions for radius and area. The following can
be added to the program:
The variables radius and area are declared by the application. The word "double"
denotes the high precision double-precision floating-point type of variable that is used to hold
decimal values.
The first stage is asking the user to enter the circle's radius. You can set a fixed value
to the radius variable within the program's code to demonstrate how variables function, even
though the procedure of prompting the user will be addressed later. You'll eventually change
the application so that it asks the user for this value.
In the subsequent step, the area is calculated by dividing the result of the expression
radius * radius * 3.14159 by the area variable. This sentence uses the radius variable to
calculate the area of the circle according to the mathematical formula for doing so.
In the final stage, the program will use cout area to display the value of area on the
console. The complete program is shown in its entirety in Listing 2.1.
The phrase "The area is" is printed to the console on line 16. It also prints the value kept
in the area variable. It is important to note that the variable name area is not enclosed by
quotation marks. If quotation marks were used, the actual value kept in the area variable
would be displayed on the console instead of the string "area".
LESSON 02
READING INPUT FROM THE KEYBOARD
LET’S PROCESS
The program can take input from the user by reading it from the keyboard. In the
source code for the example displayed in Listing 2.1, the radius is hardcoded. It can be time-
consuming to write new source code and compile it from scratch every time you want to change
the radius. However, a more useful approach is accessible.
In order to get around this restriction, the "cin" object, which is pronounced "see-in," can be
utilized, as shown in Listing 2.2. The application can now take user input for the radius
dynamically without needing to alter the source code each time a different radius is requested.
On line 11, the application prints the string "Enter a radius:" to the terminal. This string
serves as a prompt to let the user know what input is required. Your program must provide
the user with clear instructions while requesting keyboard input.
Line 12 employs the cin object to read a value from the keyboard. The application's cin
object is in charge of capturing user input so that the supplied value can be saved in a variable
for further processing.
It's important to keep in mind that cin in C++ stands for console input. The sample
program uses the stream extraction operator, often known as the >> symbol, to assign an input
to a variable.
At the start of the sample execution, the software displays the prompt message "Enter
a radius:". The cin object then takes the user's entry of 2 to set the variable radius to that
value. The cin object makes the application wait for keyboard input until the user enters data
and presses the Enter key. It's critical to remember that C++ automatically performs data type
conversion, ensuring that the data entered into the keyboard is correctly assigned to the
variable.
A single statement may also be used to read several inputs. For instance, the sentence
that follows inserts three values into the variables x1, x2, and x3:
INPUT
1. Ask the user to input three numbers
PROCESS
1. Compute average by adding all the three numbers then divide by 3
OUTPUT
1. Display the result.
The user is prompted to input three numbers on line 11. In line 12, the numbers are
read. Three digits can be entered, separated by spaces, and then you can press Enter.
Alternatively, you can enter each number, then press Enter, like in the sample run of this
program.
LESSON 03
IDENTIFIERS
LET’S PROCESS
In a program, identifiers are used as names for various components, such
as variables and functions.
Listing 2.3 demonstrates how various program elements are represented by identifiers
like main, number1, number2, number3, and others. These names are referred to as identifiers
in programming language. Identifiers must adhere to the following criteria:
For instance, 2A and d+4 are not valid identifiers since they don't follow the
requirements, even though area and radius are. Users are alerted by the compiler about syntax
errors and improper identifiers.
Due to the case-sensitivity of C++, identifiers like area, area, and AREA are seen as
distinct and independent.
For identifying variables, functions, and other kinds of program objects, identifiers are
necessary. The readability of programs is improved by the use of descriptive identifiers. Full
words should be used instead of abbreviations because they are more descriptive. It is advised
to use numberOfStudents rather than numStuds, numOfStuds, or numOfStuds. In the text,
we provide thorough programs with pertinent titles. We occasionally replace variable names
like i, j, k, x, and y in code samples to save space. These names give the code snippets a general
appearance.
C++ Keywords
LESSON 04
VARIABLES
LET’S PROCESS
The aim of variables is to represent values that could potentially change
within a program.
As is evident from the programs provided in the aforementioned sections, variables are
used to store values for potential use in a program. They are referred regarded as variables
because their values can be altered.
Radius and area are variables of the double-precision floating-point type in the program
shown in Listing 2.2. Radius and area can be given any numerical number, and their values
can be changed in the future. For instance, area is originally allocated as 3.14159 (line 3) and
afterwards adjusted to 12.56636 (line 8), whereas radius is initially set to 1.0 (line 2) and then
modified to 2.0 (line 7).
Variables are used to represent a certain type of data. A variable must be declared before
it can be used by stating its name and the kind of data it may store. Declaring a variable gives
the compiler the go-ahead to allocate the variable the proper amount of memory based on its
data type. The following is the syntax for declaring a variable:
datatype variableName;
The data types int and double are used in these instances. Additional data types
including short, long, float, char, and bool will be covered later.
Variables of the same type may be specified together like in the following example:
datatype variable1, variable2,..., variablen;
To draw a distinction, we say "declare a variable" rather than "define a variable." While
a declaration often entails allocating memory to store data for the declared item, a definition
explains what the defined item is.
Initial values are a common feature of variables. A variable can be initialized and
declared at the same time. Consider the following code as an illustration:
Likewise, you can use shorthand to jointly declare and initialize variables of the same
type. For instance,
The area of the program where a variable can be accessed is referred to as its scope, and
it is present in every variable. The following lessons of the module will gradually cover the
guidelines governing variable scope. It suffices to know for the time being that variables need
to be defined and initialized before they may be utilized.
LESSON 05
ASSIGNMENT STATEMENTS AND ASSIGNMENT EXPRESSIONS
LET’S PROCESS
To give a variable a value, use an assignment statement. C++ uses the
assignment operator (=) to denote a variable's value. An assignment statement may serve as
an expression in C++.
The assignment statement syntax is as follows, and it can be used to assign a value to
a variable after it has been declared:
variable = expression;
In an expression, a variable may be used. The = operator can also be used with a variable
on both sides. For instance,
'x + 1' is the value that is given to the variable 'x' in this assignment statement. Before
the statement is executed, the value of 'x' will be 1, and after the statement has been run, it
will become 2. It's crucial to keep in mind that the variable name must always be on the left
side of the assignment operator when providing a value to a variable. As a result, the statement
that follows is untrue:
LET’S PROCESS
An identifier that stands in for a permanent value is a named constant.
The value of a variable could vary while a program is being executed. However, a named
constant or simply a constant refers to data that stays the same over the duration of the
program. In our ComputeArea program, the value of (pi) is a constant. Instead of repeatedly
typing 3.14159, you can create a constant called for. The syntax for defining a constant is as
follows:
In C++, the keyword "const" must be used along with the data type and variable name
to declare a constant. The declaration and initialization of the constant must occur in the same
statement. As seen in Listing 2.4, here is an example of declaring a constant called "p" and
rewriting Listing 2.2 using this constant.
1. It does away with the need to constantly type the same value throughout the code,
making it easier to understand and lowering the possibility of typos.
2. If a constant value needs to be updated, such as changing the value of PI from 3.14
to 3.14159, only one place in the source code needs to be modified. As a result, there is a time
savings and a lower chance of making mistakes by failing to update all instances of the value.
3. Having descriptive constant names makes the program easier to read. Programmers
find it simpler to comprehend the importance of the values used in the code when constants
have names that make sense.
LESSON 07
NUMERIC DATA TYPES AND OPERATIONS
LET’S PROCESS
With operators +, -, *, /, and%, C++ offers nine different numeric types for integers
and floating-point values.
1. NUMERIC TYPES
There are several potential values for each data type. The compiler allots a particular
amount of RAM for each variable or constant based on the data type. C++ provides primitive
data types for values of the character, boolean, and numeric kinds. This section introduces
the operations and varieties of numerical data. In Table 2.1, the different types of numeric
data are given together with their normal storage sizes and ranges.
Short int and short can be used interchangeably in C++, as can unsigned short int
and unsigned short, long int and long, and unsigned long int and unsigned long. For
instance,
is the same as
The three types of floating-point numbers in C++ are float, double, and long double.
Double precision refers to the double type, whereas single precision refers to the float type,
which is usually twice as large. Even bigger than double is the extended double kind. The
double type is typically chosen and useful for many purposes.
It's essential to remember that older compilers might not define these constants, and
that the size of data types can change based on the compiler and computer being used.
Although on some systems long may need 8 bytes, int and long often have the same
sizes.
The sizeof function can be used to determine the size of a type or variable on your
particular computer. An illustration of how to display the sizes of int, long, and double as
well as variables like age and area on your machine is shown in Listing 2.6.
2. NUMERIC LITERALS
A literal is a constant value that occurs directly in a program. The numbers 34 and
0.305, for instance, are literals in the following sentences:
By default, an integer literal is a decimal integer number. For octal integer literals,
use a leading 0 (zero), while for hexadecimal integer literals, use a leading 0x (zero x). In
the example code below, the decimal value 8 is displayed for the octal number 10 and the
decimal value 65535 is displayed for the hexadecimal number FFFF.
Numbers with a decimal point are represented using the float and double types.
What does the term "floating-point numbers" mean? Internally, these quantities are kept in
scientific notation. The decimal point is floated to a new location when a number, such as
34.534, is written in scientific notation, such as 3.4534E+1.
3. NUMERIC OPERATORS
As illustrated in Table 2.2, the operators for numeric data types include addition (+),
subtraction (-), multiplication (*), division (/), and remainder (%). The values that an
operator operates on are known as operands.
When a division operation yields a result with two integer operands, any fractional
parts are clipped and the result is the quotient. For example, multiplying 5 by 2 gives you
2, not 2.5, and multiplying -5 by 2 gives you 2, not -2.5. At least one of the operands must
be a floating-point number to execute ordinary division with a fractional portion. For
instance, 5.0 divided by 2 results in 2.5.
The remainder (%) operator, also referred to as the modulo or remainder operator,
returns the remaining value after division when used with integer operands. The dividend
is represented by the left operand, and the divisor is represented by the right operand. 10%
3 yields 1, 2%7 yields 2, 8%2 yields 0, 29%4 yields 1, and 20%17 yields 3, for instance.
In programming, the modulus operator (%) is a useful tool. For instance, it can
establish if a number is even or odd when applied to positive integers. An odd number
divided by an even number will always produce 1, and vice versa. The similarity of a number
can be determined using this attribute.
Future days of the week can also be calculated using the modulus operator. For
instance, if it's Saturday today and you want to know what day of the week it will be in 10
days, you can apply the following formula to find that it will be Tuesday:
From a time in seconds, the program in Listing 2.7 calculates minutes and remaining
seconds. For instance, 8 minutes and 20 seconds are contained in 500 seconds.
The program in Listing 2.7 calculates the number of minutes and remaining seconds
from a time in seconds. 8 minutes and 20 seconds, for instance, are contained in 500
seconds.
INPUT
1. Prompt the user to enter time in seconds
PROCESS
1. Convert seconds to minutes and seconds.
a. Compute minute by dividing seconds by 60
Minutes = seconds / 60
b. Compute remaining seconds by using modulus operator
remainingSeconds = seconds % 60
OUTPUT
1. Display the result.
Binary and unary are both possible for the + and - operators. A binary operator has
two operands, whereas a unary operator has just one. As an illustration, the - operator in
-3 is a unary operator to negate the number 3, but the - operator in 3 - 7 is a binary operator
or subtraction of the number 7 from the number 3.
4. Exponent Operations
The pow(a, b) function, where 'a' stands for the base and 'b' for the exponent, can be
used to determine an amount's exponential power. The C++ cmath library contains the pow
function. The result of 2 raised to the power of 3 (23) is returned when it is called using the
syntax pow(a, b), as in pow(2.0, 3).
In the example provided, the pow function's parameters 'a' and 'b' serve as inputs,
whereas 2.0 and 3 are actually utilized to call the function.
It's essential to keep in mind that some C++ compilers could demand that one of the
values in pow(a, b) be a decimal value. In this instance, 2.0 is used in place of 2. In Lesson
06, more information and specifics on functions will be covered. It is sufficient to know how
to use the pow function to exponentiate for the time being.
LESSON 08
EVALUATING EXPRESSIONS AND OPERATOR PRECEDENCE
LET’S PROCESS
The same guidelines apply when evaluating C++ expressions as when
evaluating arithmetic expressions.
You can directly translate an arithmetic expression using C++ operators when
writing numerical expressions. Consider the arithmetic expression, for instance:
➢ Next, the operators for multiplication, division, and remainder are used. When
one of these operators appears numerous times in an expression, they are all
evaluated left to right.
➢ Operators for addition and subtraction are applied last. Multiple addition and
subtraction operators are evaluated from left to right if an expression contains
them.
INPUT
1. Prompt the user to enter degree in Fahrenheit
PROCESS
1. Convert degree Fahrenheit to Celsius by usng the formula:
celsius = (5.0 / 9) * (fahrenheit - 32)
OUTPUT
1. Display the result.
When applying division operation, use caution. In C++, dividing two integers
𝟓
results in an integer. In line 12, is translated to 5.0 / 9 rather than 5/9 since in C++
𝟗
5/9 produces 0.
Problem: The task is to develop a software that displays the current time in GMT (Greenwich
Mean Time) in the format hour:minute:second, for example, 15:17:3.
Solution:
As seen in Figure 2.1, the time(0) function in the ctime header file delivers the current
time in seconds since 00:00:00 on January 1, 1970 GMT. The UNIX epoch is the period in
question. The epoch marks the beginning of time. The UNIX operating system was first formally
released in 1970.
Source: Liang, Y. Daniel; Introduction to Programming with C++; 3rd Edition; 2014
Figure 2.1. The number of seconds since the Unix epoch is returned by calling time(0).
You can use this method to find the current time and the subsequent second, minute,
and hour using pseudocode in IPO style as seen below:
INPUT
1. Use the time(0) function to get the duration in total seconds since midnight on January
1, 1970.
PROCESS
2. By dividing the total seconds by 60, you may get the total minutes.
4. By dividing the total minutes by 60, you can get the total hours.
OUTPUT
POTENTIAL VARIABLES
(List all the variables and constants identified in the IPO and determine its the appropriate
data type associated with these variables and constants.)
Note: All variables are of the integer data type because we only need to take into account
the complete number and not its fractional component.
When the time(0) function is used (line 16), it returns the amount of time, in seconds,
that has passed between the current GMT time and midnight on January 1, 1970 GMT.
LESSON 09
AUGMENTED ASSIGNMENT OPERATORS
LET’S PROCESS
The assignment operator can be coupled with the operators +, -, *, /, and%
to create augmented operators.
A variable's present value is frequently utilized, changed, and then assigned back to the
same variable. The declaration that follows, for instance, raises the number of variables by 1:
Using an augmented assignment operator, C++ enables you to combine the assignment
and addition operators. The preceding sentence, for instance, might be expressed as follows:
The addition assignment operator is also known as +=. In Table 2.3, more augmented
operators are listed.
is the same as
The operators (+=, -=, *=, /=, and %=) can be used to create assignment statements and
expressions just like the assignment operator (=). For instance, in the code below, the
statement x += 4 is on the first line and the expression is on the second.
LESSON 10
INCREMENT AND DECREMENT OPERATORS
LET’S PROCESS
To add or subtract 1 from the value of a variable, use the increment (++)
and decrement (--) operators.
The ++ and -- operators make it simple to increase or decrease a variable by one. This
comes in handy when a value needs to be changed by a specific amount in a variety of
programming circumstances. For instance, the code that follows shows how to increase the
value of the variable a by 1 and decrease the value of the variable b by 1.
It is pronouced "i plus plus" for the operator i++ and "i minus minus" for the operator i-
. Because the operators ++ and -- appear after the variable, these operations are referred to as
postfix increment (postincrement) and postfix decrement (postdecrement), respectively.
However, as demonstrated in the example below, these operators can also be used before the
variable.
You may have observed that the results of i++ and ++i, or i-- and --i, in the preceding
cases were identical. However, when included into expressions, their results vary. Table 2.4
lists the distinctions between these operators and offers instances of each to show how they
behave.
Example
Operator Name Description
(assume i = 1)
Use the new value of var in
int j = ++i;
++var Preincrement the statement after
// j is 2, i is 2
increasing it by 1
Increase var by 1, but keep
int j = i++;
var++ postincrement the statement's original var
// j is 1, i is 2
value.
Use the new value of var in
int j = --i;
--var predecrement the statement after
// j is 0, i is 0
decrementing var by 1.
Use the initial value of var in
int j = i--;
var-- postdecrement the statement after
// j is 1, i is 0
decrementing var by 1.
Here are some more examples to show how the prefix form of ++ (or --) and the postfix
form differ from one another. Take into account this code:
In this instance, i is increased by 1 before being multiplied using its previous value.
newNum then changes to 100. If ++i is used in place of i++ as shown below,
x becomes 0.1, y becomes 6.4, and z becomes 7.5 once the three lines have been
completed.
LESSON 11
NUMERIC TYPE CONVERSIONS
LET’S PROCESS
Is it possible to give a floating-point variable an integer value? Yes. Can an integer
variable have a floating-point value set to it? Yes. The fractional portion of a floating-point value
is truncated, not rounded, when it is assigned to an integer variable. For illustration:
Can binary operations be carried out with two different sorts of operands? It is, indeed.
In binary operations involving an integer and a floating-point number, the integer in C++ is
automatically transformed to a floating-point value. In other words, 3.0 * 4.5 is equivalent to
the statement 3 * 4.5.
Using a casting operator, C++ additionally offers a method for directly converting a value
from one type to another. The casting syntax is as follows:
where type is the type you want to convert value from, and value is a variable, a literal, or an
expression. For instance, the following assertion
displays 1. The fractional component is trimmed when a double value is converted to an int
value.
displays 0.5 since 1 is converted to 1.0 before being split by 2. However, since 1 and 2 are
both integers and the outcome should also be an integer, the expression
displays 0.
The (type) syntax, which places the target type in parentheses before a variable, literal,
or expression, can also be used for static casting. The C-style cast is what is used for this. For
instance,
Widening a type is the process of changing a variable of a smaller range type into a
variable of a greater range type. On the other hand, narrowing a type refers to changing a
variable of a type with a bigger range to a variable of a type with a smaller range. It's crucial to
keep in mind that when a type is narrowed, such as by giving an int variable a double value,
precision may suffer. Results that are erroneous because of the lost data could result.
When performing a narrowing type conversion in C++, the compiler will normally
produce a warning to let you know that precision may be lost. The warning can be disabled,
though, if the conversion is made directly using the static_cast operator.
It is important to note that casting has no effect on the original variable. For example,
in the program code below:
A program that shows the sales tax with two digits following the decimal point is
provided in Listing 2.10.
INPUT
1. Prompt the user to enter the purchase amount
PROCESS
1. Compute for the tax by multiplying purchaseAmount by TAXRATE
OUTPUT
1. Display the result
In line 12 of the statement, the tax is therefore shown as 11.85 with two digits following
the decimal point.
LESSON 12
SOFTWARE DEVELOPMENT PROCESS
LET’S PROCESS
The software development life cycle describes the systematic approach used to
create a software product. The stages of this life cycle include requirements formulation,
analysis, design, implementation, testing, deployment, and maintenance. These stages are vital
and necessary for successful software development, regardless of the size of the software
product. Figure 2.2 depicts the various stages of the software development life cycle.
Source: https://www.educba.com/waterfall-model/
Figure 2.2. Waterfall Model - Classical Software Engineering Cycle
The SDLC (software development life cycle) is a methodical technique to producing
software applications. It is composed of multiple well-defined stages that drive the development
process from early requirements collecting to final software deployment and maintenance. This
lecture provides an overview of each SDLC stage/phase, emphasizing its purpose and critical
activities.
1. Requirements Specification:
Definition: The requirements for the software system are gathered and recorded at this
phase.
Key Activities:
o Interacting with stakeholders to learn about their wants and requirements.
o Analyzing and prioritizing needs.
o Creating a list of functional and non-functional needs.
2. System Analysis:
Definition: In this phase, the requirements are analyzed to determine the behavior,
capabilities, and limits of the system.
Key Activities:
o Completing a feasibility study to ascertain the viability of the proposal.
o Examining the requirements to find any holes or contradictions.
o To explain system behavior, create use cases, user stories, and system models.
3. System Design:
Definition: The main goal of system design is to convert the requirements into a detailed
design specification.
Key Activities:
o Architectural design: Defining the framework and parts of the system.
o Detailed design: Establishing thorough specifications for every component.
o User interface design: Designing the components and interactions of the user interface.
4. Implementation:
Definition: The software is created at this phase in accordance with the design requirements.
Key Activities:
o Writing code and putting the functionality into practice.
o Carrying out routine unit tests and code reviews.
o Combining various parts and modules to build an effective system.
5. Testing:
Definition: To make sure that the software satisfies the requirements and operates as
intended, testing is an essential step.
Key Activities:
o Creating test cases and plans based on the specifications.
o Carrying out numerous testing techniques, including acceptability, system, integration,
and unit testing.
o Finding and repairing faults or problems that were discovered during testing.
6. Deployment:
Definition: The program must be made accessible to end users during the deployment
phase.
Key Activities:
o Getting the software ready for distribution or installation.
o Performing deployment-related tasks, such as data migration, installation, and
configuration.
o Carrying out user training and delivering required paperwork.
7. Maintenance:
Definition: Following deployment, the program moves into the maintenance phase, where it
is tracked, improved, and updated.
Key Activities:
o Addressing user-reported bugs and problems.
o Putting new features, upgrades, and updates into practice.
o Doing routine maintenance chores, such as security upgrades and performance
optimization.
We will move forward with the design of a program that computes loan payments in order
to witness the real application of the software development process. This tool will be able to
manage numerous loan kinds, including auto, student, and mortgage loans. Since this is an
introductory programming course, the phases of the software development process that deal
with requirements specification, analysis, design, implementation, and testing will receive the
majority of our attention.
• Give the user the ability to input the annual interest rate, loan amount, and number
of years for payments.
The monthly payment and total payment are the outputs, which may be calculated
using the following formulas:
As a result, the monthly interest rate, the number of years the loan will be outstanding,
and the loan amount will all need to be entered into the program.
The user must enter the annual interest rate, loan amount, and number of years for
payments, according to the requirements specification. However, it's likely that you'll find out
through analysis that some numbers are not necessary for the output or that the input is
insufficient. You can change the requirements specification if this occurs.
In the real world, you will interact with clients from different walks of life. Software for
chemists, physicists, engineers, economists, and psychologists is something you could create. Of
course, you won't have (or need) to be an expert in every one of these subjects. As a result, you
don't need to understand how formulae are created to use this application to calculate the
monthly payment given the annual interest rate, the loan amount, and the duration of the
installments. However, you'll need to interact with clients and comprehend how the system's
mathematical model functions.
Stage 3: System Design
You use IPO to determine the program steps during system design.
INPUT
1. Request the annual interest rate from the user
(The software needs to transform the input for the yearly interest rate, which is a
figure in percent format, into a decimal by dividing it by 100.)
2. Request the loan amount from the user
3. Request that the user input the number of years
(The annual interest rate is the typical way to express the interest rate as a
percentage of the principal over a year.)
PROCESS
1. Obtain the monthly interest rate.
a. Divide the annual interest rate by 12 since a year has 12 months.
(To obtain the monthly interest rate in decimal format, you must divide the
annual interest rate in percentage by 1200. For example, if the annual interest
rate is 4.5%, then the monthly interest rate is 4.5/1200 = 0.00375.)
2. Compute the monthly payment using the formula:
pow(1 + monthlyInterestRate, numberOfYears * 12)
3. Compute the total payment, which is the monthly payment multiplied by 12 and
multiplied by the number of years.
OUTPUT
1. Display the monthly payment and total payment
POTENTIAL VARIABLES
Stage 4: Implementation
Code writing, or implementation, is another name for this process. You must calculate
(1 + monthlyInterestRate)numberOfYears * 12 in the calculation, which may be done by using the
formula pow(1 + monthlyInterestRate, numberOfYears * 12). The entire program is provided in
Listing 2.11.
Listing 2.11 Compute Loan
The cmath library must be included in the program (line 2) in the same way that the
iostream library was included (line 1) in order to utilize the pow(a, b) function.
Lines 16–25 of the program ask the user to enter the annual interest rate, the number
of years, and the loan amount. A runtime error would occur if any other type of input were
used instead of a numeric value.
Select the data type that best fits the variable. For instance, although it may be
expressed as a long, float, or double, numberOfYears is best declared as an int (line 11). For
numberOfYears, it should be noted that unsigned short might be the best choice. However, for
the sake of convenience, the examples in this module will utilize double for floating-point
numbers and int for integer values..
Lines 31 and 32 transfer the monthly payment calculation algorithm into C++ code. To
get the total payment, go to line 37.
To get a new monthlyPayment and totalPayment with two digits after the decimal points,
casting is used in lines 34 and 39.
Stage 5: Testing
Once the program has been put into place, test it with some sample input data to see if
the output is accurate. You'll see in later chapters that some of the issues could encompass
numerous cases. You must create test data for these kinds of issues that account for every
scenario.
In this example, the system design phase identified a number of stages. Coding and
testing these stages sequentially by include them one at a time is a solid strategy. With this
strategy, it is considerably simpler to identify issues and debug the application.
Problem: Let's assume you want to create a program that divides a certain sum of money into
smaller amounts. The program allows the user to enter an amount as a double value that
represents a total in dollars and cents. It then generates a report that lists the monetary
equivalent in the most dollars, quarters, dimes, nickels, and pennies possible, in that order, to
produce the fewest possible coins, as demonstrated in the sample run.
Materials: Desktop/Laptop Computer or Android Phone/Tablet, and Dev-C++ for Windows or
CPPDroid - C/C++ IDE for Android
Solution:
Here are the steps for creating the program in IPO format, or pseudocode:
INPUT
PROCESS
2. Divide the cents by 100 to find the number of dollars. Obtain the remaining cents using
the cents remainder 100.
3. Divide the remaining cents by 25 to find the number of quarters. Obtain the remaining
cents using the remaining cents remainder 25.
4. Divide the remaining cents by 10 to find the number of dimes. Obtain the remaining
cents using the remaining cents remainder 10.
5. Divide the remaining cents by 5 to find the number of nickels. Obtain the remaining
cents using the remaining cents remainder 5.
OUTPUT
POTENTIAL VARIABLES
Note: All variables used in the program can also be declared before the input codes.
A double decimal denoting dollars and cents represents the variable amount. All of the
cents are represented by the int variable remainingAmount after conversion. For instance, the
initial remainingAmount is 1156 if the amount is 11.56. The integer portion of the division is
produced by the division operator. So, 1156 / 100 is 11. The remainder of the division is
obtained via the remainder operator. As a result, 56 is 1156% of 100.
The maximum number of dollars are taken out of the total amount by the program, and
the remaining amount is obtained and stored in the variable remainingAmount (lines 22–23).
The next step is to take the greatest possible number of quarters out of remainingAmount to
create a new remainingAmount (lines 26–27). The computer then repeats the process to identify
as many dimes, nickels, and pennies as possible within the remaining sum.
The potential loss of precision when casting a die in this case is one significant issue.
to an int remainingAmount, multiply by two. This can produce unreliable results. If you try to
enter 10.03, 10.03 * 100 will result in the number 1002.9999999999999. The program shows
10 dollars and 2 pennies, as you will see. Enter the sum as an integer value that represents
cents to solve the issue.
LESSON 13
COMMON ERRORS
LET’S PROCESS
Undeclared variables, uninitialized variables, integer overflow, accidental integer
division, and round-off mistakes are all common fundamental programming problems.
Before utilizing a variable, it must be declared with a type and assigned a value.
A typical mistake is failing to declare or initialize a variable. Take a look at the following
code:
This code is incorrect because the value 0.05 is assigned to interestRate, but
interestRate has not been declared or initialized. Because C++ is case-sensitive, it treats
interestRate and interestrate as two distinct variables.
If a variable is declared but not used in the program, this could indicate a
programming problem. As a result, you should delete the unused variable from your
program. In the following code, for example, taxRate is never utilized. As a result, it
should be deleted from the code.
Numbers can only be kept with a certain amount of digits. Overflow occurs when
a variable is assigned a value that is too large (in size) to be stored. For example, the
following statement generates overflow since the maximum value that may be stored in
a short type variable is 32767. 32768 is an excessively large number.
Similarly, executing the following statement results in overflow since the smallest
number that may be stored in a short type variable is -32768. The number -32769 is too
big to fit within a short variable.
C++ does not show overflow errors. When working with numbers near the
maximum or minimum range of a specific type, exercise caution.
Underflow occurs when a floating-point number is too small (i.e., too close to zero)
to be stored. It is approximated to zero by C++. Normally, you should not be concerned
about underflow.
0.429993 is shown rather of 0.43. Integers are exactly stored. Integer calculations
therefore produce an exact integer result.
The integer and floating-point division operations in C++ are performed using the
same divide operator, /. The / operator divides two integer operands when they are two
integers. The quotient is the outcome of the procedure. The fractional portion has been
cut off. Make one of the two integers a floating-point number to force two integers to
divide in floating points. As an illustration, the code in (a) shows that the average is 1,
while the code in (b) shows that the average is 1.5.