Ch2p1 Sequential
Ch2p1 Sequential
Input : miles
(I) PROBLEM Output: kilo
DEFINITION Formula : kilo = miles * 1.609
1. Get input
Read miles
2. Calculate kilo (II) ALGORITHM
kilo = miles * 1.609 DESIGN
3. Display output
Print “Miles in kilometer is ” kilo
LINE EXPLANATION
Lines 1-6 ▪ These are introductory comments.
▪ The comments are not executed by the compiler
and they are used only to allow the readability of
the program.
LINE EXPLANATION
Lines 8 (cont.)
▪ In the C++, the iostream file contains the instruction
(source code) needed to handle input and output
operation, such as inputting data form keyboard and
outputting information on the computer screen.
▪ C++ programs typically include at least one directive,
and most include many directives.
Line 12,16,20,23 ▪ These are the comments that tell the purpose of the
program’s section.
Line 13,14 ▪ These instructions declare or reserve two variables, which
are simply memory locations that the program uses while
it is running. The keyword float tells the compiler that the
variable or the memory location can store a number with a
decimal place.
▪ The instruction to declare a variable is considered a
statement in C++, therefore it ends with a semicolon(;).
Line 18 ▪ The cin object and the extraction operator (>>) will accepts a
value from the keyboard and store the value into the
memory location miles.
Line 24-25 ▪ Display the message “Miles in kilometers is ” and the value
stored in the variable kilo to the screen. This statement end
with ‘;’ can be written in two lines.
LINE EXPLANATION
Lines 26 ▪ return 0 – this keyword indicate that program terminate in
normal condition. return 0 must be written if the main()
function has data type integer (int).
3
CSC126 FUNDAMENTALS OF ALGORITHMS & COMPUTER PROBLEM SOLVING 12
Rules for naming variables are:
▪ SINGLE declaration:
▪ Example: int num1;
int num2;
int sum;
▪ MULTIPLE declarations – variables having the same data type can be
grouped and declared using the single declaration statement.
▪ For example, single declaration as shown above can
be declared as a single statement.
✓ Example: int num1, num2, sum;
✓ Example of initialization: int num1 = 10, num2 = 20, sum = 0;
▪ The following example gives all the variable the value 0,
✓ Example: score1 = score2 = score3 = 0;