Big Picture in Focus: to review basic computer programming using C++.
Metalanguage
For you to demonstrate ULOb, you will need to have an operational
understanding of the following principles below. Please note that you will also be
required to refer to the previous principles found in ULOa section.
Computer Program. These are merely a set of instructions that direct the
computer to perform a certain task.
Algorithm. This is a step by step procedure to be followed in calculations.
.
Flowchart. This is a visual representation of an algorithm.
Pseudocode. This is an alternative way of representing the algorithm that
uses code-like statements.
Syntax. In computer programming, it refers to the character structure that
a computer can understand.
Essential Knowledge
At present, there are several high-level computer languages being used by many
individuals. An example is the C++ having such rich capabilities. Through computer
programming, the task of performing calculations becomes easier and faster.
However, there are certain aspects to consider before programming. This includes
understanding the problem very well to create clear instructions (algorithm) to solve
the problem.
The algorithm or the steps in programming can be represented into two different
ways; flowchart and pseudocode. This can help the programmer to have a clear idea
on what to do. Below is the symbols used in flowchart.
However, there are programmers prefer to use pseudocode. One advantage of
pseudocode is that it is easier to develop a program with it than with a flowchart. The
pseudocode is also easier to modify and share with others. However, because of
their graphic form, flowcharts sometimes are better suited for visualizing complex
algorithms. Below is the sample of flowchart and pseudocode.
Review of Basic C++ Commands
Numerical Method can be programmed through different software available.
However, there are programming languages that will help you enhance your program
development skills. One freeware that can give us that package is C++. In our
application, we will use this language because aside from it can be downloaded for
free, this was also introduced to you in your lower programming subject (EDP 4L).
Parts of C++ Program
Special Characters
Character Name Description
// Double Slash Begins a comment
# Pound Sign Begins preprocessor directive
<> Open, Close Brackets Encloses filename used in
#include directive
() Open, Close Parentheses Used when naming function
{} Open, Close Braces Encloses a group of statements
““ Open, Close Quote Marks Encloses string of characters
; Semicolon Ends a programming statement
Binary Arithmetic Operators
Symbol Operation Example ans
+ addition ans = 7 + 3; 10
- subtraction ans = 7 – 3; 4
* multiplication ans = 7 * 3; 21
/ division ans = 7 / 3; 2
% modulus ans = 7 % 3; 1
Data Types
char = used to hold single character.
int = to store an integer constant.
float = to store real numbers.
Output/Input Object
The cout Object
• Displays information on computer screen
• Use << to send information to cout
cout << "Hello, there!";
• Can use << to send multiple items to cout
cout << "Hello, " << "there!";
The cin Object
User input goes from keyboard to the input buffer, where it is stored as
characters
cin converts the data to the type that matches the variable
int height;
cout << "How tall is the room? ";
cin >> height;
Making Decisions
Relational Operators
Used to compare numbers to determine relative order
Operators:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
! = Not Equal to
The if Statement
• Allows statements to be conditionally executed or skipped over
Format of the if Statement
The block inside the braces is called the body of the if statement. If there is only 1 statement in the
body, the { } may be omitted.
How the if Statement Works
• If (condition) is true, then the statement(s) in the body are executed.
• If (condition) is false, then the statement(s) are skipped.
The if/else Statement
• Allows a choice between statements depending on whether (condition) is true
or false
Format:
if (condition)
{
statement set1;
}
else
{
statement set2;
}
How the if/else Works
• If (condition) is true, statement set 1 is executed and statement set 2 is
skipped.
• If (condition) is false, statement set 1 is skipped and statement set 2 is
executed.
if/else Flow of Control
The if/else if Statement
• Chain of if statements that test in order until one is found to be true
if/else if Format
if (condition 1)
{
statement set 1;
}
else if (condition 2)
{
statement set 2;
}
…
else if (condition n)
{
statement set n;
} Logical Operators
Used to create relational expressions from other relational expressions
Operators Meaning Explanation
&& AND New relational expression is true if both
expressions are true
|| OR New relational expression is true if
either expression is true
! NOT Reverses the value of an expression;
true expression becomes false, false
expression becomes true.
The switch Statement
• Used to select among statements from several alternatives
• May sometimes be used instead of if/else if statements
switch Statement Format
switch (IntExpression)
{
case exp1: statement set 1;
case exp2: statement set 2;
...
case expn: statement set n;
default: statement set n+1;
}
switch Statement Requirements
1) IntExpression must be a char or an integer variable or an expression that
evaluates to an integer value
2) exp1 through expn must be constant integer type expressions and must be
unique in the switch statement
3) default is optional but recommended
How the switch Statement Works
1) IntExpression is evaluated
2) The value of intExpression is compared against exp1 through expn.
3) If IntExpression matches value expi, the program branches to the
statement(s) following expi and continues to the end of the switch
4) If no matching value is found, the program branches to the statement after
default:
The break Statement
• Used to stop execution in the current block
• Also used to exit a switch statement
• Useful to execute a single case statement without executing statements
following it
Looping
The while Loop
Loop: part of program that may execute > 1 time (i.e., it repeats)
while loop format:
The { } can be omitted if there is only one statement in the body of the loop
How the while Loop Works
while (condition)
{
statement(s);
}
condition is evaluated
– if it is true, the statement(s) are executed, and then condition is
evaluated again
– if it is false, the loop is exited
while Loop Flow of Control
while Loop is a Pretest Loop
• while is a pretest loop (condition is evaluated before the loop executes)
• If the condition is initially false, the statement(s) in the body of the loop are never
executed
• If the condition is initially true, the statement(s) in the body continue to be
executed until the condition becomes false
Exiting the Loop
• The loop must contain code to allow condition to eventually become false so
the loop can be exited
• Otherwise, you have an infinite loop (i.e., a loop that does not stop)
Using the while Loop for Input Validation
Loops are an appropriate structure for validating user input data
1. Prompt for and read in the data.
2. Use a while loop to test if data is valid.
3. Enter the loop only if data is not valid.
4. Inside the loop, display error message and prompt the user to re-enter the data.
5. The loop will not be exited until the user enters valid data.
The do-while Loop
• do-while: a post test loop (condition is evaluated after the loop executes)
Format:
do-while Flow of Control
do-while Loop Notes
• Loop always executes at least once
• Execution continues as long as condition is true; the loop is exited when
condition becomes false
• Useful in menu-driven programs to bring user back to menu to make another
choice
The for Loop
• Pretest loop that executes zero or more times
• Useful for counter-controlled loop
Format:
for Loop Flow of Control
for Loop Notes
• If test is false the first time it is evaluated, the body of the loop will not be
executed
• The update expression can increment or decrement by any amount
• Variables used in the initialization section should not be modified in the body of
the loop
for Loop Mechanics
Functions
• Modular programming: breaking a program up into smaller, manageable
functions or modules
• Function: a collection of statements to perform a specific task
• Motivation for modular programming
Simplifies the process of writing programs
Improves maintainability of programs
Defining and Calling Functions
• Function call: statement that causes a function to execute
• Function definition: statements that make up a function
Function Definition includes:
name: name of the function. Function names follow same rules as variable names
parameter list: variables that hold the values passed to the function
body: statements that perform the function’s task
return type: data type of the value the function returns to the part of the program that
called it
Function Header
• The function header consists of
the function return type
the function name
the function parameter list
• Example:
int main()
• Note: no ; at the end of the header
Function Return Type
• If a function returns a value, the type of the value must be indicated
int main()
• If a function does not return a value, its return type is void
void printHeading()
{
cout << "\tMonthly Sales\n";
Calling a Function
• To call a function, use the function name followed by () and ;
printHeading();
• When a function is called, the program executes the body of the function
• After the function terminates, execution resumes in the calling module at the
point of call
• main is automatically called when the program starts
• main can call any number of functions
• Functions can call other functions
Arrays
• Array: variable that can store multiple values of the same type
• Values are stored in adjacent memory locations
• Declared using [ ] operator
const int ISIZE = 5;
int tests[ISIZE];
Array Storage in Memory
The definition
int tests[ISIZE]; // ISIZE is 5
allocates the following memory
Array Terminology
In the definition int tests[ISIZE];
– int is the data type of the array elements
– tests is the name of the array
– ISIZE, in [ISIZE], is the size declarator. It shows the number of
elements in the array.
– The size of an array is the number of bytes allocated for it
(number of elements) * (bytes needed for each element
Accessing Array Elements
• Each array element has a subscript, used to access the element.
• Subscripts start at 0
Inputting and Displaying Array Contents
cout and cin can be used to display values from and store values into an array
Array Subscripts
• Array subscript can be an integer constant, integer variable, or integer
expression
Inputting and Displaying All Array Elements
To access each element of an array
– Use a loop
– Let the loop control variable be the array subscript
– A different array element will be referenced each time through the loop
Array Initialization
• Can be initialized during program execution with assignment statements
• Can be initialized at array definition with an initialization list
Sample Problem1:
(Basic Input/Output). Create a program that will read the two sides of a rectangle and
calculate its area.
Solution:
ALGORITHM
Step 1: Input W,L
Step 2: A←L x W
Step 3: Print A
Sample Syntax using C++:
#include<iostream>
using namespace std;
int A, L, W;
int main()
{
cout<<”enter length”;
cin>>L;
cout<<”enter width”;
cin>>W;
A = L * W;
cout<<”the area is “<<A<<” unit squared”;
return 0;
}
Sample Problem 2:
(Making Decision). Develop a program that reads two values, determines the largest
value and prints the largest value with an identifying message.
Solution:
ALGORITHM
Step 1: Input VALUE1, VALUE2
Step 2: if (VALUE1 > VALUE2) then
MAX ← VALUE1
else
MAX ← VALUE2
endif
Step 3: Print “The largest value is”, MAX
Sample Syntax using C++:
#include<iostream>
using namespace std;
int VALUE1, VALUE2, MAX;
int main()
{
cout<<”enter first number”;
cin>>VALUE1;
cout<<”enter second number”;
cin>>VALUE2;
if(VALUE1>VALUE2)
{ MAX = VALUE1;
cout<<” the greater number is “<<MAX;
}
else if(VALUE1<VALUE2)
{MAX = VALUE2;
cout<<”the greater number is “<<MAX;
}
else
{cout<<”the two numbers are equal”;
}
return 0;
}
Sample Problem 3:
(Using Looping). Create a program that will solve 1+2+3+4+…100.
Solution:
ALGORITHM
Step 1: set VALUE = 1.
Step 2: set SUM = 0.
Step 3. if( VALUE <= 100)then
3.1 SUM ← SUM + VALUE
3.2 increment VALUE by 1
3.3 return step 3
else
proceed to step 4.
Step 4: Print SUM
Sample Syntax Using c++:
#include<iostream>
using namespace std;
int SUM=0;
int main()
{
for(int VALUE = 1;VALUE<=100;VALUE++)
{SUM = SUM +VALUE;
}
cout<<”the sum of 1+2+3+. . . + 100 is “<<SUM;
return 0;
}
Self-Help: You can also refer to the sources below to help you further
understand the lesson:
[] D. Malik, C++ Programming: from problem analysis to program design, Stamford
CT: Cengage Learning, 2015.
[] J. Smith, C++ programs to accompany logic and design, Boston MA: Cengage
Learning, 2015.
[] D. Zak, An introduction to programming with C++, Andover: Cengage Learning,
2016.
[] S. Davis, C++ for Dummies, John Wiley and Sons, Incorporated, 2014.