Computer Programming
Computer Programming
2 steps
Algorithm:
1. walk
2. walk
3. turn
4. sit
50 steps
Algorithm:
1. Repeat 50 times:
walk
2. turn
3. sit
on the result of the decision. On the example below, this illustrates how Rob would decide where he
would drop the ball on a box 20 steps ahead of him
20 Steps
Red
Yellow
Figure 1.3 An example of selection structure
Algorithm:
1. Repeat 20 times
Walk
2. if the balloon is red do this
Drop the balloon in the red box
Otherwise, do this
Drop the balloon in the yellow box.
3. Turn
4. Repeat walk 20 times
Walk
5. Turn
Notice that there are additional instructions that are added to the previous ones. Specifically instruction 2, notice
that this instruction is intended for deciding where Rob would drop the balloon. It is also know as the if and
otherwise instruction, indenting the instructions below either if or otherwise would indicate that when the
condition of the first statement is not met, then it would proceed to the next condition, otherwise it would
proceed to the next instruction.
The start symbol being the start of every flowchart must have no in-arrow.
The stop symbol being the end of every flowchart must have no out-arrow.
The decision represents branching and thus must have at least two out arrows.
Symbol
IPO
Example: You are a worker at CalTron oil and gas industries, currently your salary as a Computer analyst is
$4,500 per month. The management proposes a salary increase 5% salary increase for all employees. Write a
program that would calculate the salary increase for a certain employee, if ever the salary increase would be
implemented. Use IPO chart and Pseudocode and Flowchart to solve this problem
Using IPO and Pseudocode
Input
Processing
Output
Old Monthly Pay Processing items:
New Monthly Pay
Monthly Raise, New Monthly Pay
Algorithm:
1. Enter the current monthly pay
2. Calculate the monthly raise by
multiplying the Old monthly
pay by 5%
3. Calculate the new monthly pay
by adding the monthly raise and
the Old monthly pay
4
Processing
Processing items:
Monthly Raise, New Monthly Pay
Algorithm:
Output
New Monthly Pay
C++ Instructions
double oldPay = 0.0;
double monthlyRaise=0.0;
double newPay=0.0;
C++ Instructions
double oldPay = 0.0;
double monthlyRaise=0.0;
double newPay=0.0;
cout<< Enter current monthly
;
cin>> oldPay;
monthlyRaise=oldPay*0.05;
pay:
int main()
{
//declare variables
double oldPay = 0.0;
double monthlyRaise=0.0;
double newPay=0.0;
//enter input items
cout<< Enter current monthly pay: ;
cin>> oldPay;
//calculate raise and new pay
monthlyRaise=oldPay*0.05;
newPay=oldPay+monthlyRaise;
//display output items
cout<<New Pay: <<newPay<<endl;
return 0;
//end of main function
}
Figure 2.1 Shows the C++ program of calculating Caltron salary increase.
All programs can be broken drawn into 3 major sections namely:
a) heading
b) declaration
c) block
The heading section is necessary for documentation and initialization purposes and is required in
some languages. In C or C++, headings are written as simple comments. It is a good programming
practice to put all necessary information about the program. Below, the text prefixed with the symbol //
is an example of a heading if it is used for a single line and /* [code] */ for multiple lines. Based the
source code above
//Title: Calculating and displaying Caltron salary increase
//Created by: <your name> on <current date>
The declaration section includes definitions for variables, constants, labels, types and userdefine functions. The declaration section must be in the specific order that follows: constants, types,
variables. The only requirement is that any identifier or variable must be declared before using it. The
declaration section also contains at least one pre-defined system or user libraries/headers so that
functions will work properly. This done using the define statement. Most common libraries are
iostream.h, stdlib.h, stdio.h, string.h, math.h, conio.h . C++ Standard Library is a collection of classes and
functions, which are written in the core language and part of the C++ ISO Standard itself. The C++
Standard Library provides several generic containers, functions to utilize and manipulate these
containers, function objects, generic strings and streams (including interactive and file I/O), support for
some language features, and everyday functions for tasks such as finding the square root of a
number.
#include <iostream.h>
//declare variables
double oldPay = 0.0;
double monthlyRaise=0.0;
double newPay=0.0;
#include <iostream.h>
are directives for the preprocessor
they are not regular code lines with expressions but indications for the compiler's
preprocessor
the directive #include <iostream> tells the preprocessor to include the iostream
standard file
this specific file (iostream) includes the declarations of the basic standard input-output
library in C++, and it is included because its functionality is going to be used later in the
program.
The block section can be a program block, function block, etc. It consists of the actual C++
statements which starts with the reserved symbol { and finishes with the reserved symbol }. This
contains either/or input process and output of the program. And also this section actual human logic is
implemented in a language that is understood by the C++ compiler. The example below shows the
block section of the C++ example shown above.
7
int main ()
corresponds to the beginning of the definition of the main function
the main function is the point by where all C++ programs start their execution,
independently of its location within the source code
It does not matter whether there are other functions with other names defined before or
after it - the instructions contained within this function's definition will always be the first
ones to be executed in any C++ program.
it
is
essential
that
all
C++
programs
have
a
main
function.
The word main is followed in the code by a pair of parentheses (()). That is because it is
a function declaration: In C++, what differentiates a function declaration from other
types of expressions are these parentheses that follow its name. Optionally, these
parentheses
may
enclose
a
list
of
parameters
within
them.
Right after these parentheses we can find the body of the main function enclosed in
braces ({}). What is contained within these braces is what the function does when it is
executed.
return 0;
This statement causes the main function to finish. return may be followed by a return
code (in our example is followed by the return code 0).
A return code of 0 for the main function is generally interpreted as the program worked
as expected without any errors during its execution.
This is the most usual way to end a C++ console program.
letter
Identifier
Underscore
letter
digit
underscore
Incorrect Identifiers
4thDigit
if
id number
(age)
pre-paid
Description
Character
Size*
1byte
Short int
Integer.
2bytes
Range*
signed: -128 to 127
unsigned: 0 to 255
signed: -32768 to 32767
unsigned: 0 to 65535
9
Long int or
int
Long integer.
float
Floating point number
double
Double precision floating point number.
long double
Long double precision floating point number.
Table 2.1: Fundamental Data Types
4bytes
4bytes
8bytes
10bytes
signed:
-2147483648
to
2147483647
unsigned:
0 to 4294967295
3.4e +/- 38 (7 digits)
1.7e +/- 308 (15 digits)
1.7e +/- 4932
C++ programming language contains one or more data types for storing integers (whole
numbers), floating-point numbers (numbers with decimal place), and characters (letters, symbols, and
numbers that will not be used in calculations). The appropriate data type to use for a memory location
depends on the values the memory location will store. For example, memory locations assigned
either the short or int data type can store integers only, with its specific range. However, keep in mind
that memory usage is not the only important factor in determining the program efficiency. We could
compare that the short int uses lesser memory that long int, but a calculation containing int memory
location takes less time to process than a calculation containing short locations. That is because
computers coverts short memory location to int data type when a calculation is being performed. On
the other hand floating point number store data in approximation, the number enclosed in the
parenthesis (in Table 2.1), thus a repeating number 2.3333333333 stored in a single precision would
only be approximated up to 7 digits max.
2.2.4. Initializing a Memory location
In addition to assigning an appropriate name and data type for each variable and named
constant, you should also assign an initial value to each. You typically initialize a memory location by
assigning a literal constant to it. Unlike variables and named constant, a literal constant is an item of
data that can appear in a program instruction, and that can be stored in a memory location. It is
classified into two:
Numeric literal constant: That is simply a number. It can consist of a (+) sign, (-) sign, (.)
decimal point and either the letter e or E (used for exponential notation). It cannot contain comma,
space, special character, dollar sign and percent sign. Numeric literal constant is only applicable for int
and float data types. Numeric literal constant can also be specified in base 8 or base 16 (octal or
hexadecimal); this is done by prefixing an extra 0 (zero) for octal or 0x for hexadecimal: the constants
100, 0144, and 0x64 all represent the same number.
Character literal constant: Is one character enclosed in single quotation marks. The letter X is
a character constant, and so are the dollar sign $and a space. Character Literal constant is only
applicable for the char memory location
2.2.5. Type Conversion
When a program instructs the computer to assign a value to a memory location, the computer
first compares the values data type with the memory locations data type. The comparison is made to
verify the value is appropriate for the memory location. If the values data type does not match the
memory locations data type, the computer uses a process called implicit type conversion to convert
the value to fit the memory location. For example you declared a float data type, if you would initialize
it with a 10 integer value, the compiler would automatically convert it to 10.0, in this case the value is
promoted. However if an int data type is assigned with a floating value of 13.42343, because this is
not supported in int data type, thus the compiler would convert it into 13, in this case the value is
demoted. Implicit conversion is also applicable when processing calculation statements having
different data types.
To prevent the computer from making implicit type conversion, you could either declare the
same data type for all variables in a program. Another is you could use explicit type conversion, also
called type casting, to explicitly convert an item of data from one data type to another.
Syntax:
(data type) variablename
Example:
int a = 100;
float b,c,d;
c=a/8;
//c yields 12.0 because int a over int 8 results to int
b = (float)a/8;
//b yields 12.5 note that 100/8 is 12.
d=a/8.0;
//d yields 12.5 because int a over double d results to double
10
example:
int num = 5;
my_char= '5';
x= y + z;
i = sqrt (j) - i * k;
Named Constant
Variables
int age = 0;
float rate=0.0;
double sale=(float) 0.0;
char grade=;
Operator Description
()
[]
.
->
++ -++
+
!
(type)
*
&
Associativity
Parentheses
(function
call)
(see
Note
1)
Brackets
(array
subscript) left-to-right
Member
selection
via
object
name
Member
selection
via
pointer
Postfix increment/decrement (see Note 2)
-- Prefix
- Unary
~ Logical
Cast
Dereference
Address
increment/decrement right-to-left
plus/minus
negation/bitwise
complement
(change
type)
* / %
Multiplication/division/modulus
left-to-right
+ -
Addition/subtraction
left-to-right
<< >>
left-to-right
<
> >=
to left-to-right
== !=
left-to-right
&
Bitwise AND
left-to-right
Bitwise exclusive OR
left-to-right
Bitwise inclusive OR
left-to-right
&&
Logical AND
left-to-right
||
Logical OR
left-to-right
?:
Ternary conditional
right-to-left
=
+=
*=
Assignment
-= Addition/subtraction
/= Multiplication/division
right-to-left
assignment
assignment
11
%=
&= Modulus/bitwise
AND
^=
|= Bitwise
exclusive/inclusive
<<= >>= Bitwise shift left/right assignment
OR
assignment
assignment
left-to-right
Note 1:
Parentheses are also used to group expressions to force a different order of evaluation;
such parenthesized expressions can be nested and are evaluated from inner to outer
Note 2:
Postfix increment/decrement have high precedence, but the actual increment or
decrement of the operand is delayed (to be accomplished sometime before the
statement completes execution)
e.g.
float a = 6 * 4 + 4 * 2;
float a = 6 * (4+4) * 2;
// answer is 32
// answer is 96
// expression is incomprehensible
float a = b+c * 2/d + 3 + b/c + d - b *c/d;
// same as
float a = b + ((c*2)/d)+3)+(b/c)+d)-((b*c)/d);
Name
Description of
Argument
Computation
abs
The absolute value of double/integer
the argument
exp
The value of e(2.71828) double/integer
raised to the power of
the argument
log
The logarithm (to the double/integer
base e) of the argument
sqrt
The positive square root double/integer
of the argument
(positive)
pow
pow(x, y) raises x to y
double
atan
The arc tangent of the double/integer
argument
cos
The cosine of the double/integer
argument
sin
The
sine
of
the double/integer
argument
Result
same
argument
double
as
double
double
double
double (radians)
double (radians)
double (radians)
12
Gets statement: Gets statement is found in the <stdio.h> library. It collects a string of characters
terminated by a new line from the standard input stream and puts it into s. The new line is replaced by a
null character (\0) in s.
example:
char string[80];
printf("Input a string:");
gets(string);
printf("The string input was: %s\n", string);
Getchar() and Getche():This macros are found in stdio and conio.h libraries. They are designed to
capture single characters from the standard input stream except for the follow differences:
getchar():getchar reads from stdin and is line buffered; this means that it will not return until the user
press ENTER.
getche() gets character from the keyboard, echoes to screen.Reads a single character from the
keyboard and echoes it to the current text window and returns the character read from the keyboard.
e.g.
cout << age;
cout << This is a simple text output;
cout << expression << expressions
e.g.
cout<<x is equals to <<x;
cout<<100+100\n<<(100+100);
Printf: (found in the stdio.h library) is useful for format specification which is not found in cout.
The format specification feature uses % symbol as format specifiers
syntax:
printf(string_expression, variablenames);
Example
printf(my name is %s, name)
printf(your age is \n %d, age);
printf(%s %s, firstname, lastname);
of
the
must correspond to the number of variablenames.
%d
%o
%f
%0.2f
%x
examples
printf(" %d\n%o\n%x", 255, 255, 255);
printf(" Interest = %0.2f", x);
printf(vital statistics %d \t%d \t %d", 36, 24,
64);
printf("%s %d years old", "VSU, 83);
Puts:
Puts
statement
copies
the
nullterminated string s to the standard output stream stdout and appends a newline character.
Example:
char string[] = "This is an example output string\n";
puts(string);
The rest of the screen is the desktop , which contains one or more windows. One of them is the
active window which most commands act upon. Whenever one types in a character, it goes into
the active window. Each window in the desktop is a work area, either for editing a file, watching
debug information, or examining the output area. The window that appears in the initial screen
is an editor window for the file NONAME1.cpp. Inside this window, one can enter all the text for
a C++ program. Some of the commonly used hot keys in the editor window are given in
------------------------------------------------------------------------------------------------------------------Hot Key
Equivalent Menu Option
Description
------------------------------------------------------------------------------------------------------------------F1
Help| Help
Display the help screen
Alt-F9
Compile | Compile
Compile program in the active window
Ctrl-F9
Run | Run
Execute program in the active window
Alt-X
File | Exit
Exit Turbo C++
---------------------------------------------------------------------------------------------------------------Table 2.6: Commonly Used Hot Keys on the Standard Screen
---------------------------------------------------------------------------------------------------------------Hot Key
Function
---------------------------------------------------------------------------------------------------------------Ctrl-KB
mark the start of a block
Ctrl-KK
mark the end of a block
Ctrl-KC
copy a highlighted block
Ctrl-KH
unhighlight a block
Ctrl-QY
delete characters starting from cursor position up to the end of the line
Ctrl-Y
delete the whole line
Ctrl-KY
delete a block
Ctrl-KW
write block to a file
Ctrl-KR
insert a file
---------------------------------------------------------------------------------------------------------------Table 2.7: Commonly Used Hot Keys on the Window Editor
Chapter 3
Program Control Structures
3.1.
Figure 3.1
In the example above, the portion enclosed in a parenthesis is called the condition, which
specifies the decision you are making and is phrased so that it results in either true or false only.
Like you, the computer also can evaluate a condition and then select the appropriate task to perform
based on that evaluation. When using the selection structure, the programmer must be sure to phrase the
condition so that it results in either true or false only. The programmer also must specify the tasks to be
performed when a condition is true, or if necessary if the condition is false. Most programming language
offers three forms of selection structure, the if, if/else, and the switch (also called case).
3.2.
set is processed when the condition is true and the other set is processed when the condition is false.
Written in the figure below is an example of a pseudocode for an if and if/else statement.
If selection structure:
1. Enter the product serial number and price
2. If (the serial number is equal to 39301)
Calculate the price by multiplying the price by 1.2
Display Product price has increased
End if
3. Display the serial number and price
If/else selection structure:
1. Enter Sales amount
2. If (the amount is greater than 1500)
Calculate the commission by multiplying the sales amount by .02
Else
Calculate the commission by multiplying the sales amount by .01
End if
3. Display the commission
Figure 3.2
In the example shown above, the instruction that is following a condition is known as the true
path. The true path ends when you come to the else or, if there is no else, when it come to the end of
the selection structure. The false path depends on whether the selection structure contains an else
statement, if there is no else statement then it would automatically go to the end of the selection
structure, but is an else exist, it would process the contents of that statement. The flowchart on figure
below would further illustrate the selection structure psuedocode.
if selection structure
Start
Sales>1500
Commission =sales*.02
Stop
Display Serial number and price
Stop
Figure 3.3
16
In C++, you can use the if statement to code if and if/else forms selection structure. The syntax of
an if and else if statement is shown below.
//this is for if statement
if (boolean_expression){
statements;
}
//this statement is for if/else
or
if (boolean_expression){
statements;
} else {
statements;
}
Note: { } (Open and close bracket) is optional, for single statements you may not use the { }
3.2.1. Comparison Operators
Comparison operators are often referred as relational operators The figure below shows the precedence of these
operators. The precedence numbers indicate the order in which the computer performs the comparisons in C++
expression. Comparisons of precedence 1 are performed first; 2 second, but a parenthesis overrides the order of
precedence.
Operator
<
<=
>
>=
==
!=
Operation
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
Precedence number
1
1
1
1
2
3
Figure 3.4
Examples:
than or equal to 25, then the if statement would evaluate true, otherwise, it evaluates false. The third example,
if (onHand == target),would evaluate a true if both onHand and target variables are equal,
otherwise it evaluates false. The fourth if (quality!= 7500), would compare quality and 7500 and
evaluate true if quality is not equal to 7500, if they are equal then it would evaluate false.
It is easy to confuse the equality operator (= =) with the assignment statement operator (=). Please take
note that the equality operator would compare 2 values and determine which whether they are equal, on the
other hand the assignment operator would assign a value to a memory location.
For example:
int quantity, age;
float price;
The first if statement would determine whether the number of stored in the quantity variable is
greater than zero and, at the same time, less than 50. When the number falls within range, the compound
condition evaluates to true, otherwise it evaluates false. In the second example, the condition compare
the age variable with the numbers 21 and 55, the compound condition evaluates true when the number
stored in the age variable is either less than 21 or greater than 55, otherwise it evaluates false. The third
example compare the contents of the quantity with the number 100 and the price with the number
10.35. The compound condition evaluates to true when the quantity variables value is less than 100
and, at the same time, the price variable is less than 10.35, otherwise it would be false. The truth table
below summarizes on how the computer evaluates logic expressions.
Logical AND (&&) truth table
Left hand expression
Right hand expression
Truth value of expression
1 (true)
1 (true)
1 (true)
1 (true)
0 (false)
0 (false)
0 (false)
1 (true)
0 (false)
0 (false)
0 (false)
0 (false)
Figure 3.6
Logical OR (||) truth table
Left hand expression
Right hand expression
Truth value of expression
1 (true)
1 (true)
1 (true)
1 (true)
0 (false)
1 (true)
0 (false)
1 (true)
1 (true)
0 (false)
0 (false)
0 (false)
Figure 3.7
When you use the && (And) operator to combine two condition in C++ expression, the computer does
not evaluate the second condition when the first condition is false. Because the && statements needs all
of the statements to be true. On the other hand the, when the | | (Or) operator is used to combine two
conditions, the computer does not evaluate the second condition if the first condition is true. Because
only one of the conditions combined with the | | operator needs to be true for the compound for the
condition to be true. Thus the concept of evaluating condition 2 based on the result of condition 1 is
referred to as short circuit evaluation.
3.3.
End if
Flowchart
Start
Enter Age
Registration status is Y
F
Stop
Figure 3.8
The source code below is the C++ implementation of the flowchart above.
#include <iostream.h>
#include <ctype.h>
int main()
{
int age=0;
cout<<"Enter your age: ";
cin>>age;
if (age>=18)
19
3.4.
C
D,F
Other
Flowchart
display Average
display Below Average
display Error
Start
Enter Grade
grade
D, E
Other
C
Display
Excellent
Stop
Figure 3.9
In C++, you use the switch statement to code the switch form of the selection structure. The syntax is
shown below.
switch (selectorExpression)
{
case value1:
one or more statements
case value2:
one or more statements
case value3:
one or more statements
case value4:
one or more statements
[default:
One or more statements
match any of the values]
}
//end switch
[break;]
[break;]
[break;]
[break;]
processed when the selectorExpression does not
The switch statement starts and with open braces and end with open braces. The selector
expression in enclosed in parenthesis can contain any combination of variables, constants, functions, and
operators, as long as the combination results to whose data type is char, short, int, or long. Notice that
there are individual case clauses within a switch statement contains a value followed by a colon. The
value can be literal constant, a named constant or an expression composed of either literal or named
constant. The data type of value should be compatible with the data type of the selectorExpression.
The break statement tells the computer to leave (break out of) the switch statement at that
point. If you do not use the break statement to leave the switch statement, the computer continues to
process the remaining in the switch statement.
#include <iostream.h>
#include <ctype.h>
int main()
{
char grade = ' ';
cout<<"Letter Grade: ";
cin>>grade;
grade=toupper(grade);
//Enter input items
switch (grade)
{
case 'A':
cout<<"Excellent"<<endl;
break;
case 'B':
cout<<"Above Average"<<endl;
break;
case 'C':
cout<<"Average"<<endl;
21
break;
case 'D':
case 'F':
cout<<"Below Average"<<endl;
break;
default:
cout<<"Input error"<<endl;
}//end switch
return 0;
//end main function
}
3.5.
3.6.
Pretest Loops
In a pretest loop, the loop condition appears at the beginning of the loop and determines the number of
times the instructions within the loop are processed. The instructions within the loop are referred to as
the loop body. Similar to a selection structure condition, a loop condition must result in either true of
false only. The flowchart of a pretest loop is shown below. Some loops, require the user to enter a
special value to end the loop. Values that are used to end loops are referred to as sentinel values.
3.6.1. Using while Statement
The syntax of a while statement and flowchart are shown below:
while (boolean_expression) {
}
While expression
Example:
int age=0;
cout<<"Enter age: ";
cin>>age;
while (age>0)
{
cout<<"Age:"<<age<< endl;
cout<< "Enter age:";
cin>> age;
}//end while
T
Statements
In this example, the while (age>0) clause tells the computer to repeat the loop body instructions as
long as (or while) the value of the age variable is greater than zero.
3.6.2. Accumulators and Counters for Loop Control
In most loops a counter is a numeric variable used for counting something. While an accumulator is a
numeric variable used for accumulating (adding together) something. Two tasks are associated with
counter and accumulators, initializing and updating. Initializing means to assign a beginning value to
the counter or accumulator variable. Typically, counter and accumulator variables are initialized to zero.
However, they can be initialized to any formed before the loop is processed, because it needs to be
performed only once. Updating also called incrementing means adding a number to the value stored in
the counter or accumulator. The number can either be positive or negative, integer or non-integer. A
counter is always incremented by a constant value-whereas an accumulator is incremented by a value
that varies. The assignment statements that updates a counter or an accumulator is placed within the loop
in a program, because the update task must be performed each time the loop instruction are processed.
See the example below
int salesMan=0;
float totalSales=0.0;
int sales=0;
while (sales>=0.0)
{
salesMan=salesMan+1;
totalSales=totalSales + sales;
cout<< "Next sales amount: ";
cin>> sales;
}//end while
// a counter
//an accumulator
22
The program above illustrates that as long as the sales is a non-negative number, the number of
salesMan would increase by 1 and the totalSales would accumulate each time a non negative sales
is made
Another use of a counter is to control the loop operation, see the example below:
int salesMan=0;
float totalSales=0.0;
int sales=0;
while (salesMan<5)
{
cout<< "Next sales amount: ";
cin>> sales;
salesMan=salesMan+1;
totalSales=totalSales + sales;
}//end while
// a counter
//an accumulator
In this code snippet, this indicates that the number loop would depend on the number of salesMan that
would key in their sales, in this case only 5 salesMan are allowed.
Example:
int salesMan=0;
float totalSales=0.0;
int sales=0;
for (salesMan=0;salesMan<5;salesMan++)
{
cout<< "Next sales amount: ";
cin>> sales;
totalSales=totalSales + sales;
}
This example has similar logic to the example in a counter controlled loop using while, but as you can
see the entire loop statement is one line lesser than the while counterpart.
3.7.
Posttest Loops
As is true of the condition in a pretest loop, the condition in a posttest loop is evaluated with each
repetition, or iteration, of the loop. However, unlike the evaluation in a pretest loop, the evaluation in a
posttest loop occurs after the instructions within the loop are processed, rather than before the instruction
are processed.
statement/s
} while (Boolean_expression)
23
Statements
For example:
int salesMan=0;
float totalSales=0.0;
int sales=0;
do
{
cout<< "Next sales amount: ";
cin>> sales;
salesMan=salesMan+1;
// a counter
totalSales=totalSales + sales;
//an accumulator
While expression
This operates on a similar way the while loop operates in the example on counter controlled loop, but if
we would have salesMan<0, the loop would still execute once.
3.8.
Nested Loops
A nested repetition structure, one loop (referred to as the inner loop) is placed entirely within another
loop (called the outer loop). Although the idea of nested loops may sound confusing, you already are
familiar with the concept. Such as a clock, for instance uses nested loops to keep track of the time.
Consider that the second hand of the clock being the inner loop and the minute hand as the outer loop.
We all know that in order to move minute hand into one position the second hand should move 60
position, then the second hand begin its journey once again. Example
int salesMan=0;
float totalSales=0.0;
int sales=0;
int region=0
while (region<3)
{
region=region+1;
cout<<"Enter Sales for region" <<region<<":";
for (salesMan=0;salesMan<10;salesMan++)
{
totalSales=totalSales + sales;
cout<< "Next sales amount: ";
cin>> sales;
}//end for
}//end while
This is a modified example in the example found in pretest for statement. The added items is that when
there are many regional sales group and each region has 10 salesMan, so to accommodate this
needed problem a nested while and for statement accomplishes the task.
Chapter 4
Functions
5.1.
Introduction to Functions
A function is a block of code that performs a task. Every C++ program contains at least one function
main() and most contain many more. Programmers use function for two reasons, First, function allows
programmer to avoid duplicating code in different parts of a program. If different sections of a program need to
perform the same task, it is more efficient to enter the appropriate code once, in a function, and then call the
function to perform its task when needed. Second, functions allow large and complex programs, which typically
are written by a team of programmers, to be broken into small and manageable task. Each member of the team
can be assigned one of the tasks to code as a function. Typically, the main() function is the program responsible
for calling (or invoking) each of the other function when needed; however, any function can call another
function.
5.2.
Predefined Functions
C++ comes with libraries of predefined functions that you can use in your programs.
There are two kinds of functions in C++: functions that return (produce) a value and
functions that do not return a value. Functions that do not return a value are called Void
functions. Always include the specific libraries which contain the function/s so that your
program would not be erroneous.
We will use the sqrt function to illustrate how you use a predefined function that returns
a value. The sqrt function calculates the square root of a number. The function sqrt starts
with a number, such as 9.0, and computes its square root, in this case 3.0.The value the
function starts out with is called its argument . The value it computes is called the
value returned. Some functions may have more than one argument, but no function
has more than one value returned.
Syntax:
Function_Name(Argument_List)
Where the Argument_List is a comma-separated list of arguments:
Argument_Last)
(Argument_1, Argument_2,. . .,
Example:
side=sqrt (area);
cout << "2 to the power 3 is "<<pow(2,3);
5.3.
(Argument_1, Argument_2,. . .,
The function that the user would create are referred to as value user defined functions. The syntax is
shown below
Syntax:
returnDataType Function_Name(parameter_List) {statements}
Wherein:
returnDataType: is the data type specifier of the data returned by the function. Note that void returns
nothing
function_name: is the identifier by which it will be possible to call the function. The rules for naming
functions are the same as for naming variables, however, it is a common practice to begin a function
name with a verb.
parameter_list: (or also known a formal parameters) store the information passed to the function when
the function is invoked (called)
statements: (or also known as function body) consists of declarations and executable
statements enclosed within a pair of braces. When the function is called, the
argument values are plugged in for the formal parameters, and then the
statements in the body are executed. The value returned by the function is
determined when the function executes a return statement.
Most C++ implementation require definition of function prototypes at the declaration section.
Function prototypes are simple function declaration without a block. You usually place function
prototypes at the beginning of a program, after the #include directives. It may help to think of function
prototypes of a program being similar to the table contents in a book. Creating function prototypes are
standard programming practice.
Example:
float average(int a, int b);
void main()
{
int x,y;
cout<<Enter first number: ;
cin>>x;
25
5.4.
Passing Parameters
The parameter allows the programmer to send values to the function for its internal operations. When
you call the function the parameters passed are called actual parameters. When the function starts executing the
actual parameter are placed in its parameter block. This is called the formal parameters.
int addition (int a, int b){
Formal Parameters
int r;
r=a+b;
return (r);
Actual parameters
We can see how the main function begins by declaring the variable z of type int. Right after that, we see a
call to a function called addition. Paying attention we will be able to see the similarity between the structure of
the call to the function and the declaration of the function itself some code lines above:
Function addition declares another local variable (int r), and by means of the expression r=a+b, it assigns to
r the result of a plus b. Because the actual parameters passed for a and b are 5 and 3 respectively, the result is 8.
The following line of code:
return (r);
Finalizes function addition, and returns the control back to the function that called it (in this case, main)
Additionally, because the return statement in function addition specified a value: the content of variable r (return
(r);), which at that moment had a value of 8. This value becomes the value of evaluating the function call. So
being the value returned by a function the value given to the function call itself when it is evaluated, the variable z
will be set to the value returned by addition (5, 3), that is 8.
5.4.1. Pass by Value
Value Parameters are those parameters follows the standard variable declared like the example
above. When this type of parameter is used, changes made to the values of the variables within the
functions are not reflected in the calling program or function. The changes are temporary because
temporary copies of the variables are made in the memory and the copies are used while the function is in
execution. Think of it as passing copies of the contents of a container to a function, the function uses a
different container. Any changes to this copy will not affect the original.
26
The first thing that should call your attention is that in the declaration of duplicate the type of each
parameter was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding
arguments are to be passed by reference instead of by value.
When a variable is passed by reference we
are not passing a copy of its value, but we are somehow passing the variable itself to the function and any
modification that will have an effect in their counterpart variables passed as arguments in the call to the
function.
To avoid programming errors, the following rules for parameter list correspondence are given:
5.5.
Global variable
27
Local variable
int y=0;
double tss=0;
while(y<5)
{
tss=tss+(x*x);
y++;
}
return tss;
}
int main()
{
int x=0;
cout<<"Enter a positive integer: ";
cin>>x;
z= sumsqr(x);
cout<<"The sum of square is: "<<z;
return 0;
}
Chapter 5
Arrays
5.1.Introduction to Arrays
All of the other variables you have used so far have been simple variable. A simple variable also called
a scalar variable is one that is unrelated to any other variable in the computers internal memory. In
many programs, however you may reserve a block of variables, referred to as an array. An array is a
group of variables that have the same name and data type and are related in some way. Each variable in
the array might contain inventory quantity, or might contain a state name, or each might contain an
employee record. It might be helpful to the boxes and you can read information from the boxes, you
just cannot see the boxes. Programmers use arrays to temporarily store related data in the internal
memory of the computer.
numberOfElements in square
arrays are blocks of non-dynamic memory whose size must be determined before execution.
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square
brackets empty []. In this case, the compiler will assume a size for the array that matches the number of
values included between braces { }:
28
After this declaration, array number would be 5 ints long, since we have provided 5 initialization values.
number [0]
16
number [1]
2
number [2]
77
number [3]
40
number [4]
12071
Strings are considered arrays because it is composed of individual character grouped together hence
array initialized with strings are perfectly ok.
5.2.2. Accessing and Manipulating Data in a one Dimensional Array
In any point of a program in which an array is visible, we can access the value of any of its elements
individually as if it was a normal variable, thus being able to both read and modify its value.
The syntax is:
name[index]
For example, to store the value 75 in the third element of number, we could write the following statement:
number[2] = 75;
and, for example, to pass the value of the third element of number to a variable called a, we could write:
a = number[2];
Therefore, the expression number[2] is for all purposes like a variable of type int.
At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to
arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second
one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets [ ] with
arrays.
int number[5];
number[2] = 75;
If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it never
precedes an access.
Some other valid operations with arrays:
number[0] = a;
number[a] = 75;
b = number [a+2];
number[number[a]] = number[2] + 5;
Example:
// array example - that would calculate
//the summation of all value in an array
#include <iostream.h>
int number [5] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result = result + number[n];
}
cout << result;
return 0;
}
To pass an array to a function, you need to simply enter the data type and name of the formal
parameter, followed by an empty set of square brackets in the receiving functions header. You also
enter the data type and an empty set of square brackets in the receiving function s prototype.
Example:
// array example that would pass an array to
a //function using pass by reference and locate the
//largest variable
#include <iostream.h>
int getLarge(int number[]);
void main ()
{
int number [5] = {16, 2, 77, 40, 12071};
cout<<getLarge(number);
}
int getLarge(int number[])
{ int large=number[0];
for ( int n=0 ; n<5 ; n++ )
{
if (large<number[n])
large=number[n];
}
return large;
}
To determine the number of elements in a two-dimensional array, you simply multiply the number of
rows by the number of columns. You can initialize the array elements in a two-dimensional array by
entering a separate initial values separated in braces, for each row in the array. If the array has two
rows , then the statement that declares and initializes the array can have a maximum of two initial
values section.
Example
int nums [2][4]= {{1,2,3,4},{5,6,7,8}}
int nums1 [2][4]= {0}
int nums2 [2][4]= {{0},{1}}
//the first declaration initializes the array
column 0 //with 1-4 and column 1 with 5-8
//initializes columns 0&1 with 0
//initializes column 0 with 0 and column 1 with 1
5.3.1. Storing & Accessing Data in Two Dimensional Array
As with one-dimensional arrays, you generally use an assignment statement to enter data into a
two-dimensional array. The syntax is dataType
arrayName
[RowsSubscript]
[ColumnsSubscript], is the name of and subscript of the array variable to which
you want the value(data) assigned. In addition to showing the syntax, you can
use two loops to access every element in a two dimensional array. One of the
loops keeps track of the row subscript, while the other loop keeps track of the
column subscript. Examine the example below:
}//end col
cout<<endl;
}//end row
31