ComEng22 Syllabus Revised
ComEng22 Syllabus Revised
ComEng22 Syllabus Revised
Definition
Programming
Programming Language
2. Assembly language
Example : ADD 1, 2
MUL 2, 3
An assembly
Language
Program
Translation
program
(assembler)
Machine
Language
program
Purpose :
be
constructed of units that pass information to each object to produce
the desired results.
C++
Programming Languages
On a fundamental level, all computer programs do the same thing, they
direct a computer to accept data (input), to manipulate the data ( process),
and to produce reports (output). This implies that all computer programming
languages that support a procedure orientation must provide essentially the
same capabilities for performing these operations.
Input
Data
Process
the
Data
Output
results
Software Development
Software Development Procedure
methods used by professional software developers for
understanding the problem that is being solved and for creating
an effective and
appropriate software solution.
Three Overlapping Phases :
1. Development and Design
2. Documentation
3. Maintenance
Software Engineering is concerned with creating, efficient, reliable, and
maintainable programs and systems, and it uses the software development
procedure to achieve this goal.
maintenance
Program
Life Cycle
Stages
documentation
development
and design
Program no
longer used
testing
coding
design
analysis
Time
Data
Entry
Section
Calculation
Sect ion
Report
Section
Data
Entry
Section
enter
data
change
data
Calculation
Sect ion
Delete
Data
Report
Section
Screen
Reports
Printer
Reports
program description
algorithm development and changes
well-commented program listing
sample test runs
users manual
Back up not part of the design process, it is critical to make and keep back up
copies of the program at each step of the programming and debugging process.
Algorithm
-
Flowchart Symbols
Process
Terminal
input / output
decision
loop
predefined process
calling a function
connector
flow lines
Exercises :
1. Create a flowchart to find the weighted average of four test scores.
2. Create a flowchart ,given the radius in inches, and price of the pizza.
3. Create a flowchart given the cost of service charge in sending an
international fax at $3.00, $0.20 per page for the first 10 pages; and $0.10
for each additional page. Calculate the amount due using the number of
pages.
Introduction to C++
C++
preeminent language for the development of high-performance software
its syntax has become the standard for professional programming
language.
The language from which both JAVA and C# are derived
History
C++
Module 3
Module 5
Module 6
first number
a
second number
x
result
2. class is a more complicated unit than a function because it contains both data
and functions appropriate for manipulating the data
3. identifiers the names permissible for functions and classes are also used to
name other elements of C++ language.
can be made by any combination of letters, digits or underscores ( _ )
4. keyword - is a word that is set aside by the language for a special purpose and
can only be used in a specified manner.
auto
break
case
catch
char
class
const
continue
delete
default
do
double
else
enum
extern
float
for
friend
goto
if
inline
int
long
new
overload
private
protected
public
register
return
short
signed
sizeof
static
struct
switch
this
template
typedef
union
unsigned
virtual
void
volatile
while
Structure
Sample program1 :
/* This is a simple C++ program */
#include <iostream>
using namespace std;
int main ( )
{
std namespace
main( )
{}
int
<<
cout
String
return 0;
system)
for most OS, a return value of 0 normally terminates the
program.
Sample Program2 :
#include <iostream>
using namespace std;
int main ( )
{
cout << Computers, computers everywhere ;
cout << \n as far as I can C ;
return 0;
}
\n newline escape sequence ( tell cout to send instructions to the display device to move to a
newline)
// - with no spaces between them, designate the start of the line comment. (one line comment)
/* comment */ - multiple line comments
Exercises :
1. Write a C++ program to display the following :
The cosecant of an angle
is equal to one over
the sine of the angle
2. Write a C++ program to display the following
____________________________
Radians
Degrees
0
0.0000
90
1.5708
180
3.1416
270
4.7124
360
6.2832
=========================
3. Write a program that produces the following output : Substitute ??? with your and curremt
date.
****************************************
* Programming Assignment 1 *
* Computer Programming 1 *
*
Author :???
*
* Due Date :???
*
****************************************
4. Write a program to produce this output :
CCCCCCCCCC
++
++
CC
++
++
CC
+++++++++++++
+++++++++++++++
CC
+++++++++++++
CC
++
CCCCCCCCCC
++
+++++++++++++++
++
++
\
\nnn
single quote
treat nnn as octal number
Operator
+
*
/
%
Sample Program3 :
#include <iostream>
using namespace std;
int main ( )
{
cout << "15.0 plus 2.0 equals "
<< (15.0 + 2.0) << '\n';
cout << "15.0 minus 2.0 equals " << (15.0 - 2.0) << '\n';
cout << "15.0 times 2.0 equals " << (15.0 * 2.0) << '\n';
cout << "15.0 divided by 2.0 equals " << (15.0 / 2.0) <<\n;
return 0;
}
45
12
1652
2548
Memory addresses
Variables
-
Rules :
num 1
45
12
1652
2548
Memory Addresses
total
57
45
Assignment Statement
Tells the computer to assign (store) a value into a variable
Always have an equal (=) sign and one variable name
immediately to the left of the sign.
Example :
num1 = 45;
num2 = 12;
total = num1 + num2;
Declaration Statements
naming a variable and specifying the data type that can be
stored in it
general form :
example :
int sum;
cout the value stored in the variable is placed on the output stream and
displayed
char a reserved word used to declare character variables
Sample program5 : character
#include <iostream>
using namespace std;
int main( )
{
char ch;
ch = 'a' ;
cout << "The character stored in ch is " << ch << endl;
ch = 'm';
cout << "The character stored in ch is " << ch << endl;
return 0;
}
Exercises :
1. A boy purchases a computer for $1,085. The sales tax on the purchase is
5.5%. Compute and print the total purchase price.
2. Find and print the area and perimeter of a rectangle that is 13.5 feet long and
2.3 feet wide.
3. A 14.5-kilogram object is traveling at 10 meters per second. Compute and
print its momentum. ( momentum = mass x velocity)
4. Convert 198.0 degrees Fahrenheit to degrees Celsius. ( C = (F 32) * 5/9)
5. Write a program that add the five decimal numbers 12.3, 34.6, 13.0, 45.6 and
15.5 and get the average.
6. Write a program that computes the salary of an employee. Given the data :
hours worked is 12.5 and pay rate per hour is 45.50.
Multiple Declarations
Variables having the same data type can always be grouped together and declared using a single
declaration statement.
Form : data-type variable list ;
Declaration statements can also be used to store an initial value into declared variables.
Example :
int num1 = 15
Sample program6 :
#include <iostream>
using namespace std;
int main( )
{
int num;
num = 22;
cout << The value stored in num is << num << endl;
return 0;
}
Exercises :
1. Write a program that would add two numbers and compute for the average.,
num1 = 25.6 and num2 is 23.4 and display the average
2. Calculate the resistance of the wire and display the result given the data
resistance = (resistivity * length) / area
resistivity = 10.4
cross-sectional area = 500
length = 125
3. Calculate the number of direct lines for 100 subscribers
Calculate the number of direct lines for 110 subscribers
Calculate the additional lines needed, display the number of lines for 100
subscribers and the additional lines needed.
Formula : lines = n(n 1) / 2
Additional lines = lines2 lines1
4. Write a program that multiplies num1 = 12 by 2, adds the value of num2 = 45 to it and then
stores the result to newNum.
5. Write a program to get the weighted average of the four test scores. Given the data
85
76
96
87
0.20
0.30
0.35
0.25
Assignment Operators
The equal ( = ) symbol is called the assignment operator and an expression
using this operator is an assignment expression.
Form :
variable = expression;
Example :
factor = 1.06;
weight = 155.0;
totalWeight = factor * weight;
Values stored in variable
factor
1.06
weight
155.0
totalWeight
164.30
Sample Program7 :
// this program calculates the volume of a cylinder,
// given its radius and height
#include <iostream>
using namespace std;
int main( )
{
float radius, height, volume;
radius = 2.5 ;
height = 16.0;
volume = 3.1416 * radius * radius * height;
cout << The volume of the cylinder is <<volume << endl;
return 0;
}
Accumulating
These expressions are required in accumulating subtotals when data is
entered one number at a time.
Example : Add the numbers 96, 70, 85 and 60
Statement
sum = 0;
sum = sum + 96;
sum = sum + 70;
sum = sum + 85;
sum = sum + 60;
Value in sum
0
96
166
251
311
Sample Program8:
#include <iostream>
using namespace std;
int main( )
{
int sum;
sum = 0;
cout << " The value of sum is initially set to "<< sum <<"\n";
sum = sum + 96;
cout << " sum is now " << sum <<"\n";
sum = sum + 70;
cout << " sum is now " << sum <<"\n";
sum = sum + 85;
cout << " sum is now " << sum <<"\n";
sum = sum + 60;
cout << " The final sum is " << sum <<endl;
return 0;
}
Counting
Similar to the accumulating statement
Form : variable = variable + fixed_number;
++ increment operator
Expression
i=i+1
n=n+1
count = count + 1
Alternative
i ++ or ++ i
n++ or ++n
count++ or ++count
Sample Program9:
#include <iostream>
using namespace std;
int main( )
{
int count;
count = 0;
cout << " The initial value of count is " <<count<<"\n";
count ++;
cout << " count is now " << count<<"\n";
count ++;
cout << " count is now " << count<<"\n";
count ++;
cout << " count is now " << count<<"\n";
count ++;
cout << " count is now " << count<<endl;
return 0;
}
-- decrement operator
When it appears before a variable is prefix decrement operator, when the
decrement appears after a variable it is called postfix decrement operator.
Formatting Numbers For Program Output
The format of numbers displayed by cout can be controlled by field width
manipulators included in each output stream.
Commonly Used Stream Manipulators
width (n)
precision (n)
Setf (flags)
Dec
Hex
Oct
Manipulator
- cout.width
- cout.precision
- cout.setf(ios: :showpos)
Action
set the field width to n
Set the floating-point precision to n places
Set the format flags
Set output for decimal display
Set output for hexadecimal display
Set output for octal display
Field manipulators are useful in printing columns of numbers so that the numbers in
each column are align correctly.
Width(n) manipulator tells cout to display the number in a total field of 10
Precision (n) tells cout to display a three digits to the right of the decimal point.
Set input/output flags
Setf using the ios::fixed flag ensures that the output is displayed in a conventional
format; that is, as a fixed point rather then an exponential number
Setf (ios::showpos) causes a leading plus sign to be displayed before positive values
Setf(ios::showpoint) causes a decimal point and trailing zeroes to be displayed for all
floating point output
setf(ios: :scientific) floating-point numeric values are displayed using scientific
notation
fill ( )
character, becomes a new fill character
Sample Program10 :
#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
cout.width(3);cout << 6<<"\n";
cout.width(3);cout <<18<<"\n";
cout.width(3);cout <<124<<"\n";
cout << "---\n";
cout << (6+18+124)<<endl;
return 0;
}
Sample Program11 :
#include<iostream>
using namespace std;
int main()
{
cout.setf(ios::showpos);
cout.setf(ios::scientific);
cout.precision(2);
cout<< 123 <<" "<<123.23 << " " <<endl;
return 0;
}
Sample Program12 :
#include<iostream>
using namespace std;
int main()
{
cout.setf(ios::showpos);
cout.setf(ios::scientific);
cout<< 123 <<" "<<123.23 << " " <<endl;
cout.precision(2);
cout.width(10); cout<< 123 << " ";
cout.width(10); cout<< 123.23 << "\n ";
cout.fill('*');
cout.width(10);cout<< 123 << " ";
cout.width(10); cout<< 123.23 << "\n";
return 0;
}
Exercises :
1. Write a program that displays the results of the expressions 3.0 * 5.0,
7.1* 8.3 2.2 and 3.2 / ( 6.1 * 5).
2. Write a program that displays the results of the expressions 15 / 4 , 15 % 4,
and 5 * 3 (6 * 4) .
Value Returned
2.0
4.123106
5.0
32.3
2.54
#include <cmath>
To access the math functions, mathematical header is needed
Common C++ Functions
Function Name
Description
Returned Value
abs(a)
pow (a1, a2)
sqrt (a)
sin (a)
cos (a)
tan (a)
log (a)
log10 (a)
exp (a)
absolute value
a1 raised to the a2 power
square root of a
sine of a (a in radius)
cosine of a (d in radians)
tangent of a (d in radians)
natural logarithm of a
common log (base 10) of a
e raised to the a power
Example
Returned value
abs(-7.362)
abs(-3)
pow(2.0, 5.0)
7.362000
3
32.00000
pow(10, 3)
log(18.69)
log10(18.697)
exp(-3.2)
1000
2.92863
1.271772
0.040762
Sample Program13:
#include <iostream>
#include<cmath>
using namespace std;
int main ()
{
int height;
double time;
height = 800;
time = sqrt ( 2 * height / 32.2);
cout << " It will take " << time << " seconds to fall at "
<< height << " feet. \n" ;
return 0;
}
Sample15
#include <iostream>
#include<cmath>
using namespace std;
int main ()
{
cout.width(3);
cout.precision(2);
cout<<" Power function : " << pow(2.0, 5.0) <<"\n";
cout<<" Absolute value is : " << abs(-7.362) <<"\n";
cout<<" Log function is: " << log(18.69) <<"\n";
cout<<" Logarithmic : " << log10(18.697) <<"\n";
cout<<" Exponential is : " << exp(-3.2) <<endl;
return 0;
}
3. Write a program that calculates the distance between two points whose
coordinates are (7, 12) and (3, 9). Use the fact that the distance between two
points having coordinates (x1, y1) and (x2, y2) is :
distance = sqrt([x1 x2]2 + [y1 y2]2).
# include <iostream>
using namespace std;
int main ( )
{
cin >>
cout <<
keyboard
}
Screen
Sample program14 :
#include <iostream>
using namespace std;
int main ()
{
float num1, num2, product ;
cout << Enter a number: \n ;
cin >> num1;
cout << Enter another number : \n;
cin >> num2;
product = num1 * num2;
cout << num1 << times << num2 << is << product ;
return 0;
}
Sample program15:
#include <iostream>
using namespace std;
int main ()
{
int num1, num2, num3;
float average ;
cout << enter three integers : \n ;
cin >> num1 >> num2 >> num3;
average = ( num1 + num2 + num3) / 3.0 ;
cout << The average of the numbers is << average;
return 0;
}
Exercises :
1. Write a program that will convert a number entered in Celsius to degrees Fahrenheit.
Formula :
SELECTION STRUCTURES
Flow of control
2. Selection
3. Repetition
4. Invocation
Selection Criteria
In the solution of many problems, different actions must be taken depending
upon the value of the data.
If-else statement
Pseudocode syntax :
if ( condition)
statement is executed if condition is true ;
else
statement is executed if condition is false ;
Condition used is any valid C++ expression :
Relational expressions consist of relational operator that compares
two operands.
- can either be a variable or a constant
- sometimes called condition
operand
Example
age < 30
height > 6.2
taxable < = 20000
temp > = 98.6
grade == 100
number ! = 250
Numerical operands
Example :
3 < 2 true = 1
2.0 > 3.0 false = 0
Character Data (comparing letters is essential in alphabetizing names)
Expression
A > C
D < = Z
E == F
G > =M
B ! = C
Meaning
0
1
0
0
1
Example
False
True
False
False
True
Logical Operators
1. AND (symbol &&) the condition is true only if both individual expression are
true themselves
Example :
2. OR (symbol || )
Example :
3. NOT !( expression)
Example : Assuming 26 is stored in age, the expression age > 40 has a value of
zero (false), while the expression !(age > 40) has a value of 1
Precedence of Operators
Operator
! unary - ++ -*/%
+< <= > >=
== !=
&&
||
= += - = * = /=
Associativity
right to left
left to right
left to right
left to right
left to right
left to right
left to right
right to left
Example : assume a = 5, b = 2, c = 4, d = 6, e = 3
a * c != d * b
5*4!=6*5
20 ! = 30
d * b == c * e
6 * 5 == 4 * 3
30 == 12
General syntax :
if (expression) statement 1 ;
else statement2;
or
if (expression)
statement 1 ;
else
statement2;
Flow chart
start
input
is
condition
true ?
no
(else part)
yes
statement 1
statement 2
display
end
Compound Statements
is a sequence of single statements contained between braces
General form :
If (expression)
{
statement1;
statement2;
statement3;
}
Else
{
statement4
statement5;
:
:
statementn;
}
Block Scope
All statements contained within a compound statement constitute a single
block of code and any variable declared within such a block only has meaning
between its declaration and the closing braces defining the block
Example ;
{
One-Way Selection
is only executed if the expression has a nonzero value (true
condition)
if (expression)
statement;
return 0;
}
Exercises :
1. Write a program that asks the user to input two numbers. If the first
number entered is greater than the second number the program should
print the message The first number is greater , else it should print the
message The first number is smaller.
2. An insulation test for a wire requires that the insulation withstand at least
600 volts. Write a C++ program that accepts a test voltage and prints
either the message PASSED VOLTAGE TEST or the message FAILED
VOLTAGE TEST as appropriate.
3. A certain waveform is 0 volts for time less than 2 seconds and 3 volts for
time equal or greater than 2 seconds. Write a C++ program that accepts
time into the variable time and display the appropriate voltage depending
on the input value.
4. Write a program that will display the message, Boiling point of water , if
temperature value is 100,else display Above the boiling point of water if
the temperature value is above 100 degrees else display the message
Below boiling point
5. Write a program that prompts the user to enter the lengths of three sides
of a triangle and then output the message whether the triangle is a right
triangle.
Nested if Statements
-
Example :
if (hours < 9)
if ( distance > 500)
cout << snap;
else
cout << pop;
General form of a nested if-else statement
a.) within the if part of an if-else statement
b.) within the else part of an if-else statement
is
expression-1
true
no (else part)
yes
is
expression-2
true
no (else part)
yes
statement 1
statement 2
statement 3
Figure 4a
no (else part)
yes
statement-1
is
expression-2
true
no (else part)
yes
statement 3
statement 2
Input Code
S
M
C
T
#include <iostream>
using namespace std;
int main( )
{
char code;
cout << Enter a specification code: ;
cin >> code;
if (code == S)
cout << The item is space exploration grade.;
else if (code == M)
cout << The item is military grade.;
else if (code == C)
cout << The item is commerical grade.;
else if (code == T)
cout << The item is toy grade.;
else
cout << An invalid code was entered. ;
return 0;
}
Sample Program20:
Determine the output of a digital converter using the following input/output
relationship.
Input Weight
Output Reading
1111
1110
1101
1100
1011
#include <iostream>
using namespace std;
int main( )
{
int digout;
float inlbs;
cout << Enter the input weight : ;
cin >> inlbs;
if (inlbs == 90)
digout = 1111;
else if (inlbs >= 80)
digout = 1110;
else if (inlbs >= 70)
digout = 1101;
else if (inlbs >= 60)
digout = 1100;
else
digout = 1011;
cout << The digital output is << digout;
return 0;
}
Exercises :
1. The grade level of undergraduate college students is typically determined
according to the following schedule:
Number of Credits Completed
Less than 32
32 to 63
64 to 95
96 or more
Grade level
Freshman
Sophomore
Junior
Senior
Using this information, write a C++ program that accepts the number of
credits a student has completed, determines the students grade level, and
displays the grade level
Letter grade
A
B
C
D
F
Using this information, write a C++ program that accepts a students numerical
grade, converts the numerical grade to an equivalent letter grade, and displays
the letter grade.
3. Write a program that prompts the user to input a number. The program should
output the number and a message will be displayed whether it is positive,
negative or zero.
default
switch (opselect)
{
case 1:
cout << The sum of the numbers entered is << fnum + snum;
break;
case 2:
cout << The product of the numbers entered is << fnum * snum;
break;
case 3:
cout << The first number divided by the second number is << fnum / snum;
break;
}
return 0;
}
Exercises : Switch Statement
1. A students letter grade is calculated according to the following schedule.
Numerical grade
Letter grade
A
B
C
D
F
Using this information, write a C++ program that accepts a students numerical
grade, converts the numerical grade to an equivalent letter grade, and displays
the letter grade.
2. Each disk drive in a shipment of these devices is stamped with a code
Write a C++ program that accepts the code number as an input and based on
the value entered displays the correct disk drive manufacturer
3. Write a program that prompts the user to input the shape ( rectangle, circle or
cylinder) and display the area and perimeter of a rectangle, area and
circumference of a circle and volume and surface area of a cylinder. Input also
the appropriate dimension, height and width for rectangle, radius for circle.
Height and radius for cylinder.
Note : Perimeter of a rectangle = 2*(L+W)
Area = L*W
Area of a circle = PIr2
Circumference = 2 PIr2
Volume of a cylinder = PIr2 *Height
REPETITION STRUCTURES
Many problems, require a repetition capability in which the same calculation or sequence
of instructions is repeated, over and over, using different sets of data.
Example :
1. continual checking of user data entries until an acceptable entry, such as
a valid password is entered.
2. counting and accumulating running totals
3. constant acceptance of input data and recalculation of output values that
only stops upon entry of a sentinel value
Repetitive section of code requires four elements :
1. repetition statement
4. There must be a statement within the repeating section of code that allows the
condition to become false
at some point, the repetitions stops.
Pretest and Posttest Loops
1. Pretest Loop
is
the condition
true ?
yes
loop
statement
No
next
statement
2. Posttest Loop
loop
statement
is
the condition
true ?
Yes
No
next
statement
Fixed Count versus Variable-Condition Loops
Types of Condition tested
1. Fixed count loop
while Loops
the statement following the expression is executed repeatedly as
long as the expression evaluates to a nonzero value
considering just the expression and the statement following the
parentheses.
Literally loops back o itself to recheck the expression until it
evaluates to zero (becomes false)
Syntax
Process used :
while (expression)
statement;
1. test the expression
2. if the expression has a nonzero (true) value
a. execute the statement following the parentheses
b. go back to step 1
else
exit the while statement and execute the next executable
statement following the while statement
enter the
while statement
expression
evaluates
to zero
test
the expression
(step 1)
( a false condition)
exit the
while statement
expression
evaluates
to a nonzero
number
( a true condition)
loop
execute the
statement
after the
parentheses
(Step 2a)
2.
count = 1;
while (count < = 10)
cout << count;
3.
count = 1;
while (count < = 10)
{
Sample program24 :
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
int num;
cout << NUMBER
<<--------------
SQUARE
------------
CUBE\n
---------\n;
num = 1;
while (num < 11)
{
cout << setw(3) <<num <<
DEGREES\n
FAHRENHEIT\n
-------------------\n;
celsius = START_VAL;
cout << setiosflags (ios ::showpoint)
<< setpresision (2);
while ( celsius <= MAX_CELSIUS)
{
fahren = (9.0 / 5.0) * celsius + 32.0;
cout << setw (4) << celsius
<< setw(13) << fahren;
celsius = celsius + STEP_SIZE;
}
return 0;
}
Exercises :
1. Write a C++ program that converts gallons to liters. The program should
display gallons from 10 to 20 in one-gallon increment and the corresponding liter
equivalent. Use the relationship that 1 gallon contains 3.785 liters.
2. Write a C++ program that converts feet to meters. The program should
display feet from 3 to 30 in three-foot increment and the corresponding meter
equivalent. Use the relationship that there are 3.28 feet to a meter.
3. Rewrite sample program5.3 to produce a table that starts at a Celsius
value of 10 and ends with a Celsius value of 60, in increment of 10 degrees.
Sample Program26 :
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
const int MAXNUMS = 4;
int count;
float num;
cout << \nThis program will ask you to enter
<< MAXNUMS << numbers.\n ;
count = 1;
while (count <= MAXNUMS)
{
cout << \nEnter a number : ;
cin >> num;
cout << The number entered is << num;
count++
}
cout << endl;
return 0;
}
Exercises:
Refer to exercises on page 50. Use interactive while statement.
start
print a
message
set count
equal to 1
is
count less
than or equal
to 4
no
stop
condition is false
yes
(condition is true)
print the
message
enter a
number :
Loop
accept a
number
using cin
these statements
are executed
each time the loop
is traversed
print value
of number
add 1 to
count
end of program
new
number
cin
new number
goes in here
num
the variable total
new total
total
+
total = total + sum
is
count
no
print total
yes
accept a num
add num
stop
to total
add 1 to
count
Sample Program27 :
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
const int MAXNUMS = 4;
int count;
float num, total;
cout << \nThis program will ask you to enter
<< MAXNUMS << numbers.\n ;
count = 1;
total = 0;
while (count <= MAXNUMS)
{
cout << \nEnter a number : ;
cin >> num;
total = total + num;
cout << The total is now << total;
count++
}
cout << \nThe final total is << total ;
return 0;
}
Sentinels
All of the loops we have created thus far have been examples of fixed count
loops, where a counter has been used to control the number of loop iterations by
means of a while statement variable condition loops may also be constructed.
Sentinels
Example :
Sample program28 :
#include <iostream>
using namespace std;
int main()
{
const int HIGHGRADE = 100;
float grade, total;
grade = 0;
total = 0;
cout << \nTo stop entering grades, type in any number ;
cout << \n greater than 100. \n\n;
while (grade <= HIGHGRADE)
{
total = total + grade;
cout << Enter a grade: ;
cin >> grade;
}
cout << \nThe total of the grades is << total ;
return 0;
}
// value higher than 100 is entered, the loop is exited. Sum is displayed.
Two useful statements in connection with repetition statements :
1. break forces an immediate break, or exit from switch, while, for and do
while statements
example :
2. continue applies only to loops created with while and do-while and for
statements.
is encountered in a loop, the next iteration of the loop
immediately begun.
Example :
Syntax :
for (initializing list; expression; altering list)
statement;
initializing list
expression
altering list
Example :
1. for (count = 1; count < 10 ; count + 1
cout << count;
( counter variable is count, initial value assigned is 1, the loop continues as long
as the value of count is less than 10, value of count is incremented by 1 each
time through the loop)
2. for ( i = 5; i <=15 ; i = i + 2)
count << i ;
( counter variable is i, initial value for i is 5, the loop continues as long as is
value is less than or equal to 15, and the value of i is incremented by 2)
Sample program29 :
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main ( )
{
const int MAXCOUNT = 5;
int count;
cout <<NUMBER
cout <<-----------
SQUARE ROOT\n;
-------------------\n;
SQUARE ROOT
---------------------1.00000
1.414214
1.732051
2.000000
2.236068
Sample program30:
#include <iostream>
using namespace std;
int main ( )
{
int count;
for ( count = 2 ; count <= 20; count = count +2)
cout << count << ;
return 0;
}
Three ways in showing sample program30
Sample program30a
#include <iostream>
using namespace std;
int main ( )
{
int count;
count = 2 ;
for ( ; count <= 20; count = count +2)
cout << count << ;
return 0;
}
Sample program30b
#include <iostream>
using namespace std;
int main ( )
{
int count;
count = 2 ;
for ( ; count <= 20;)
{
cout << count <<
count = count + 2;
}
return 0;
}
Sample program30c
#include <iostream>
using namespace std;
int main ( )
{
int count;
for ( count = 2 ; count <= 20; cout << count <<
return 0;
}
enter the
for statement
initializing
statement
expressions value
is zero
evaluate
the tested
exit the
expression
false condition
for statement
expressions value
is nonzero
( true condition)
Loop
execute the
statement
after the
parentheses
execute the
altering
list
(false condition)
exit for
statement
{
statement 1
through
statement n
}
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
const int MAXNUMS = 10;
int num;
cout << NUMBER
<<--------------
SQUARE
------------
CUBE\n
---------\n;
Exercises :
1.
The expansion of a steel bridge as it is heated to a
final Celsius temperature, TF, from an initial Celsius temperature T0, can be
approximated using the formula
Increase in length = a * L * (TF T0)
Where a is the coefficient of expansion (which is for steel 11.7e-6) and L is the
length of the bridge at temperature T0 . Using this formula, write a program that
displays a table of expansion lengths for a steel bridge that is 7365 meters long
at 0 degrees Celsius, as the temperature increases to 40 degrees in a 5 degree
increment.
2.
Write a program that displays a table of 20
temperatures converting from Fahrenheit to Celsius. The table should start with
a Fahrenheit to Celsius. The table should start with a Fahrenheit value of 20
degrees and be incremented in values of 4 degrees.
Celsius = (5.0 / 9.0) * (Fahrenheit 32)
// initialized to zero
Sample Program33 : this program computes the positive and negative sums of
a set of MAXNUMS user entered numbers
#include <iostream>
using namespace std;
int main ( )
{
const int MAXNUMS = 5;
int i ;
float usenum, postot, negtot;
postot = 0;
negtot = 0;
for ( i = 1; i <= MAXNUMS; i++)
{
cout << Enter a number [positive or negative] : ;
cin >> usenum;
if (usenum > 0)
postot = postot + usenum;
else
negtot = negtot + usenum;
}
cout << The positive total is << postot;
cout << The negative total is << negtot;
return 0;
}
float x, y ;
cout << x value
y value\n
<< -------------------- ;
cout << setiosflags (ios: : fixed)
<< setiosflags (ios: : showpoint)
<< setprecision (6);
for ( x = 2.0; x <= 6.0; x = x + 0.5)
{
y = 10.0 * pow(x, 2.0) + 3.0 * x 2.0 ;
cout << setw (7) << x
<< setw (14) << y;
}
return 0;
}
3. Interactive Loop Control
Values used to control a loop may be set using variables rather than constant
values.
i = 5;
j = 10;
k = 1;
for (count = i ; count <= j ; count = count + k)
produce the same effect as the single statement
for (count = 5 ; count <= 10 ; count = count + 1)
Sample Program35:
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
int num, final;
cout << Enter the final number for the table: ;
cin >> final;
cout << NUMBER
cout <<--------------
SQUARE
------------
CUBE\n;
---------\n;
Exercises :
1. Produce a table for y values
y = 3x5 2x3 + x
for x between 5 and 10 in increments of 0.2
2. Write a program that accepts individual values of gallons, one at a time,
and converts each value entered to its liter equivalent before the next
value is requested. Use a for loop in your program. 3.785 liters in one
gallon.
3. Write a program that selects and displays the maximum value of five
numbers that are to be entered when the program is executed. (use a for loop
with both a cin and if statement internal to the loop)
Nested Loops
loops contained within another loop
Example :
Output :
a is now 1
j=1
a is now 2
j=1
a is now 3
j=1
a is now 4
j=1
a is now 5
j=1
Sample Program36
#include <iostream>
using namespace std;
int main ( )
{
const int MAXA = 5;
const int MAXJ = 4;
int a, j;
for (a = 1; a <=5; a++)
{
j=2
j=3
j=4
j=2
j=3
j=4
j=2
j=3
j=4
j=2
j=3
j=4
j=2
j=3
j=4
#include <iostream>
using namespace std;
int main ( )
{
const int NUMGRADES = 4;
const int NUMSTUDENTS = 20;
int x , y ;
float grade, total, average;
for ( x = 1; x <= NUMSTUDENTS ; x++)
{
total = 0;
for ( y = 1 ; y NUMGRADES <= ; y++)
{
cout << Enter an exam grade for this student: ;
cin >> grade;
total = total + grade;
}
average = total / NUMGRADES ;
cout << \n The average for student << x
<< is << average << \n\n;
}
return 0;
}
Exercises :
1.
23.2
34.8
19.4
36.9
31
45.2
16.8
39
16.9
27.9
10.2
49.2
27
36.8
20.8
45.1
25.4
33.4
18.9
42.7
28.6
39.4
13.4
50.6
do loop
statement
is
the condition
true ?
No
next
statement
do while structure
General form :
do
statement ;
while (expression) ;
Yes
Sample Program35:
#include<iostream>
#include <iomanip.h>
using namespace std;
int main ( )
{
int count;
count = 0;
do
{
count = count + 1;
cout << count << endl;
} while (count < 5);
cout << setw(10) << All Done << endl;
return 0;
}
Sample Program36:
#include<iostream>
using namespace std;
int main ( )
{
int price, salestax, RATE;
do
{
cout << \nEnter a price : ;
cin >> price ;
cout<<Enter rate: \n;
cin>>RATE;
if (abs(price SENTINEL) < 0.0001)
break;
salestax = RATE * price;
cout << setiosflags ( ios : : showpoint)
<< setprecision (2)
Sample Program37:
#include<iostream>
using namespace std;
int main ( )
{
char selection;
do
{
cout <<Which of the following recipes do you wish to see? \n;
cout << (1)Tacos\n;
cout << (2)Jambalaya\n;
cout << (3)Gumbo\n;
cout << (4)Quit ;
cout << Enter the first letter and press<Enter>: ;
cin >> selection;
} while( selection < 1 || selection >4 );
switch (selection) {
case 1 :
cout << Tacos;
break;
case 2 :
cout << Jambalaya ;
break;
case 3 :
cout<< Gumbo ;
break;
case 4 :
cout << Goodbye ;
}
return 0;
}
Validity Checks
The do statement is particularly useful in filtering user-entered input and
providing data validation checks.
Example : (Assume that an operator is required to enter a valid customer identification
number between 1000 to 1999. A number outside this range is rejected)
do
{
cout << \nEnter an identification number: ;
cin >> id_num;
}
while ( id_num < 1000 || id_num > 1999);
// A request for an identification number is repeated until a valid number is entered. This
section of code is bare bones in that it neither alerts the operator to the cause of the
new request for data nor allows premature exit from the loop if a valid identification
number is found. //
Sample Program38:
#include<iostream>
using namespace std;
int main()
{
int id_num;
do
{
cout << "\nEnter an identification number: ";
cin >> id_num;
if (id_num < 1000 || id_num > 1999)
{
cout << "An invalid number was just entered\n";
cout << "Please check the ID number and re-enter\n";
}
else
break ;
} while (1);
return 0;
}
Exercises :
1. Write a program that continuously requests a grade to be entered. If the grade is less
than 0 or greater than 100, your program should print an appropriate message informing
the user that an invalid grade has been entered, else the grade should be added to a
total. When a grade of 999 is entered the program should exit the repetition loop and
display the average of the valid grades entered.
2. Write a program that requires the use of Menu to give the user a choice of options.
The menu should display the following :
1.
2.
3.
4.
5.
If else
Switch
For
While
Do while
and an invalid message would be displayed if the choice entered is not in the selection.
For every choice of the user, for example If- else, a syntax of the selected statement will
be displayed.
Input Code
S
M
C
T
ARRAYS
Arrays
Characteristics
a. name
b. component type
c. indices of the first and last components
Two types of Arrays
1. One-Dimensional Array -
[number of items]
Examples:
const int NUMELS = 6;
int volts [NUMELS];
an
integer
an
integer
an
integer
an
integer
an
integer
element or component
item in an array
are stored sequentially
Index or subscript
elements position
an
integer
temp [0] refers to the first temperature stored in the temp array
temp [1] second temperature stored
temp [2] third temperature stored
temp [3] fourth temperature stored
temp [4] fifth temperature stored
Illustrated temp array in Memory
temp [0]
temp [1]
temp [2]
temp [3]
temp [4]
temp
array
element 0 element 1 element 2 element 3 element 4
temp [0], is read as temp sub zero (shortened for temp array subscripted by zero)
the array name temp identifies
the starting location of the array
temp [0]
temp [1]
temp [2]
temp [3]
temp [4]
sum = temp [0] + temp [1] + temp [2] + temp [3] + temp [4]; is
}
cout << endl;
for ( x = 0 ; x < MAXTEMPS; x++)
cout << temperature << x << is << temp [x] <<endl;
return 0;
}
Sample Program39: Displaying temperature values entered and the total.
#include <iostream>
using namespace std;
int main( )
{
const int MAXTEMPS = 5;
int x, temp [MAXTEMPS] , total = 0 ;
for ( x = 0 ; x < MAXTEMPS; x++)
{
cout << Enter a temperature: ;
cin >> temp [x];
}
cout << \n The total temperatures ;
for ( x = 0 ; x < MAXTEMPS; x++)
{
cout << << temp [x] ;
total = total + temp [x];
}
cout << is << total << endl;
return 0;
}
Exercises :
1. Write a program to input eight integer numbers into an array named temp. As each
number is entered, add the numbers into a total. After all numbers are entered, display
the numbers and their average.
2. Write a program to input the following values into an array named volts: 10.95, 16.32,
12.15, 8.22, 15.98, 26.22, 13.54, 6.45, 17.59. After the data has been entered, have
your program output the values.
3. Write a program to input the following integer numbers into an array named grades :
89, 95, 72, 83, 99, 54, 86, 99, 54, 86, 75, 92, 73, 79, 75, 82, 73. As each number is
entered, add the numbers to a total. After all numbers are entered and the total is
obtained, calculate the average of the numbers and use the average to determine the
deviation of each value from the average. Store each deviation in an array named
deviation. Each deviation is obtained as the element value less the average of the data.
Have your program display alongside its corresponding element from the grades array.
Array Initialization
Array elements can be initialized within their declaration statements, the initializing
elements must be included in braces.
Examples :
int temp [5] = { 98, 87, 92, 79, 85};
char codes [6] = { s, a , m , p , l , e};
double slopes [7] = {10.96, 6.43, 2.58, .86, 5.89, 7.56, 8.22};
Initializers are applied in the order they are written, with the first value used to initialize
element 0, second value used to initialize element 1, until all values have been used.
Initializing values may extend across multiple lines.
Example :
int gallons[20] = {19, 16, 14, 19, 20, 18,
12, 10, 22, 15, 18, 17,
16, 14, 23, 19, 15, 18,
21, 5};
A unique feature of initializers is that the size of the array may be omitted when
initializing values are included in the declaration statement.
Example :
int gallons [] = {16, 12, 10, 14, 11};
char codes [6] = {s, a, m, p, l, e};
char codes [] = {s, a, m, p, l, e};
Useful simplification when initializing characters in arrays.
char codes [] = sample;
This last declaration creates an array having seven elements and fills the array with the
seven characters :
Codes [ 0 ] [ 1 ]
[2]
[3]
[4]
[5]
[6]
\0
Null character
8
3
14
16
15
25
9
2
2
52
6
10
two-dimensional array of
integers (consists of three rows
and four columns)
To reserve storage for this array, both the number of rows and columns must
be included in the array declaration.
Calling the array val the correct specification is
Sample declarations :
float volts [10] [5];
char code [6] [26];
Rows and Column position of an Array
Row 0
Row 1
Row 2
Col 0
Col 1
8
3
14
16
15
25
Col 2 Col 3
9
2
2
52
6
10
Examples :
watts = val [2] [3];
{ 8, 16, 9, 52},
{3, 15, 27, 6},
{14, 25, 2, 10}};
Can be initialize also by omitting the inner braces :
int val [3][4] =
{ 8, 16, 9, 52,
3, 15, 27, 6,
14, 25, 2, 10 };
The separation of initial values into rows in the declaration statement is not necessary
since the compiler assigns values beginning with [0][0] element and proceeds row by row
to fill in the remaining values.
Example :
This is equally valid but does not illustrate to the programmer where one row ends and
another begins.
Storage and initialization of the val [ ] array
val[0][0] = 8
val [0][1] = 16
val [0][2] = 9
val [0][3]= 52
val[1][0] = 3
val [1][1] = 15
val [1][2] = 27
val [1][3]= 6
val[2][0] = 14
val [2][1] = 25
val [2][2] = 2
val [2][3]= 10
int main ( )
{
const int NUMROWS = 3;
const int NUMCOLS = 4;
int i, j;
int val [NUMROWS][NUMCOLS] = { 8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10 };
cout << \nDisplay of val array by explicit element
<< \n << setw(4) << val[0][0] << setw(4) << val[0][1]
<< setw(4) << val[0][2] << setw(4) << val[0][3]
<< \n << setw(4) << val[1][0] << setw(4) << val[1][1]
<< setw(4) << val[1][2] << setw(4) << val[1][3]
<< \n << setw(4) << val[2][0] << setw(4) << val[2][1]
<< setw(4) << val[2][2] << setw(4) << val[2][3];
cout << \n\nDisplay of val array using a nested for loop;
for ( i = 0; i < NUMROWS; i++)
{
cout << \n;
for ( j = 0; j < NUMROWS; j++)
cout << setw(4) << val[ i ][ j ];
}
int i, j;
int val [NUMROWS][NUMCOLS] = { 8, 16, 9, 52,
3, 15, 27, 6,
14, 25, 2, 10 };
//multiply each element by 10 and display it
cout << \nDisplay of multiplied elements ;
for ( i = 0; i < NUMROWS; i++)
{
cout << endl;
for ( j = 0; j < NUMROWS; j++)
{
val [ i ] [ j ] = val [ i ] [ j ] * 10;
cout << setw(5) << val [ i ] [ j ] ;
}
}
cout << endl;
return 0;
}
Larger Dimensional Array
Although arrays with more than two dimensions are not commonly used, C++
does allow any number of dimensions be declared. This is done by listing the maximum
size of all dimensions for the array.
Example :
example, element[1][2] of the resulting array should be the sum of First [1][2] and
Second [1][2]. The first and second arrays should be initialized as follows.
16
54
First
18
23
91
11
24
16
Second
52
77
19
59
return 0;
}
Diagnostics of the Sample program :
Findmax ()
Function Prototypes
declaration statement for a function ( before a function is called, it must
be declared to the function that will do the calling)
tells the calling function the type of value that will be formally
returned, if any, and the data type and order of the values that the
calling function should transmit to the called function.
General form :
Examples :
fmax ( )
declares that this function expects to receive two integer arguments and
will formally return an integer value
swap ( )
display ( )
declares that this function requires two double precision arguments and
does not return any value and such a function might be used to display
results of a computation directly, without returning any value to the called
function.
Arguments
only requirements are that the name of the function be used and that any
data passed to the function be enclosed within the parentheses following
the function name using the order and type as declared in the function
prototype.
- are items enclosed within the parentheses.
FindMax
( firstnum, secnum )
ststored in firstnum
a value
the variable
firstnum
stored in secnum
get the value
a value
Send the
value to
FindMax ( )
Send the
value to
FindMax ( )
Defining a Function
-
the variable
secnum
each function is defined once in a program and can then be used by any
other function in the program that suitably declares it.
b. function body
General format :
Function header
{
constant and
variable declarations;
any other C++ statements;
Function body
Example :
void FindMax ( int x, int y)
This statement
Calls FindMax ( )
The value
in
secnum
is passed
the
parameter
named x
the
parameter
named y
Sample Program44 :
#include <iostream>
int main ( )
// driver function
return 0;
}
// following is the function FindMax ()
void FindMax (int x, int y)
{
int maxnum ;
if (x >= y)
maxnum = x;
else
maxnum = y;
return;
// end of function body and end of function
Sample Output :
Enter a number : 25
Great! Please enter a second number : 5
The maximum of the two numbers is 25
Placement Statements
preprocessor directives
function prototypes
int main ( )
{
named constants
variable declarations
other executable statements
return value
}
function definitions
Function Stubs
Stub
Sample Program44a :
#include <iostream>
int main ( )
{
int firstnum, secnum;
cout << \n Enter a numer: ;
cin >> firstnum;
cout << great ! Please enter a second number: ;
cin >> secnum;
FindMax(firstnum, secnum);
return 0;
}
void FindMax(int x, int y)
{
cout << "In FindMax()\n";
cout << "The value of x is "<<x <<"\n";
cout << "The value of y is "<<y;
getch ();
return;
}
Functions with Empty Parameter Lists
The function prototype for such function requires either writing the keyword void
or nothing at all between the parentheses following the functions name.
Example :
sqr_it (first);
return 0;
}
void sqr_it(double num)
{
cout << The square of << num << is << (num * num) ;
return ;
}
Exercises :
1. Write a function called mult() that accepts two floating-point numbers as
parameters, multiplies these two numbers, and displays the result.
2. Write a C++ program that returns the fractional part of any user entered number.
For example, if the number 256.879 is entered, the number .879 should be
displayed.
3. Write a function that produces a table of the numbers from 1 to 10, their squares
and their cubes.
return expression;
To actually use a returned value we must either provide a variable to store the value or
use the value directly in an expression. Storing the returned value in a variable is
accomplished using a standard assignment statement.
max = FindMax(firstnum, secnum);
// return statement
}
Sample Program45 :
#include <iostream>
int main ( )
// driver function
{
int firstnum, secnum, maxnum;
cout << \n Enter a numer: ;
cin >> firstnum;
cout << great ! Please enter a second number: ;
// return statement
Sample Program46 :
#include <iostream>
//function prototype
int main()
{
const CONVERTS = 4;
int count;
double fahren;
Exercises :
1. Write a C++ function named find_abs ( ) that accepts a double-precision number
passed to it, computes its absolute value, and returns the absolute value to the
calling function. The absolute value of a number is the number itself if the
number is positive and the negative. Use a cout to display the value returned.
2. The surface area, s, of a cylinder is given by the formula
S = 2rl
where r is the cylinders radius and l is its length. Using this formula write a C+
function named surfarea() that accepts the radius and length of a cylinder and
returns its surface. Use a cout statement to display the value returned.
data-types& reference-name
float& num1;
char& key
&
Function header for newval : void newval (float& num1, float& num2)
Function prototype :
Sample Program47 :
#include <iostream>
int main()
{
float firstnum, secnum;
cout << Enter two numbers: ;
cin >> firstnum >.secnum;
cout << The value in firstnum is : << firstnum;
cout << The value in secnum is : << secnum << \n\n;
newval (firstnum, secnum);
secnum
one value is stored
ynum
Sample Output :
Enter two numbers : 22.5 33.0
The value in firstnum is : 22.5
The value in secnum is : 33
The value in xnum is : 22.5
The value in ynum is : 33
The value in firstnum is now: 89.5
The value in secnum is now: 99.5
The values initially displayed for the parameters xnum and ynum are the same as those
displayed for the arguments firstnum and secnum.
Since xnum and ynum are reference parameters, however,newval () now has direct
access to the arguments firstnum and secnum.
Thus any change to xnum and ynum within newval () directly alters the value for firstnum
and secnum in main( )
Sample Program48 :
#include <iostream>
// function call
secnum
thirdnum
2.5
6.0
sum
product
18.5
150.0
total
product
10.0
main()
A value is passed
calc( )
2.5
6.0
10.0
num1
num2
num3
The desired exchange of main ( )s variables by swap ( ) can only be obtained by giving
swap () access to mains variables, by reference parameters.
Exchanging values in two variables is accomplished using three-step exchange
algorithm:
1. Store the first parameters value in a temporary location
temp
num1
num2
num1
num2
num1
num2
}
Sample Program49:
#include <iostream>
int main()
{
float firstnum = 20.5 , secnum = 6.25 ;
cout << The value stored in firstnum is : << firstsum;
cout << The value stored in secnum is : << secnum << \n\n ;
swap ( firstnum, secnum);
Arrays As Arguments
Individual arrays elements are passed to a called function in the same manner as
individual scalar variables; they are simply included as subscripted variables when the
function call is made.
Example:
find_min(volts[2], volts[6] );
Duplication of copies of array for each function call would be wasteful of memory storage
and would frustrate the effort to return multiple element changes made by the called
program.(recall that a function returns at most one direct value). To avoid these
problems, the called function is given direct access to the original array.
Example :
int nums[5];
char keys [256];
double volts[500], current [500];
for these arrays, the following function calls can be made :
find_max(nums);
find_ch(keys);
calc_tot(nums, volts, current);
on the receiving side, the called function must be alerted that an array is being made
available.
Example : suitable function header lines
Sample Program50:
#include <iostream>
using namespace std;
const int MAXELS = 5;
int find_max(int [MAXELS] );
// function prototype
int main ( )
{
int nums[MAXELS] = { 2, 18, 1, 27, 16};
cout << The maximum value is << find_max(nums) << endl;
return 0;
}
// find the maximum value
int find_max( int vals[MAXELS] )
{
int i, max = vals[0];
for ( i = 1; i < MAXELS; i++)
if (max < vals[i] ) max = vals[i];
return max;
}
All the find_max( ) must know is that the parameter vals references an array of integers.
Since the array has been created in main ( ) and no additional storage spaces is needed
in find_max ( ), the declarations for vals can omit the size of the array.
int find_max (int vals [ ] )
Since only the starting address of vals is passed to find_max, the number of elements in
the aaray need not be included in the declaration for vals.
Sample Program51:
#include <iostream>
// function prototype
int main ( )
{
const int MAXELS = 5;
int nums[MAXELS] = { 2, 18, 1, 27, 16};
cout << The maximum value is
<< find_max(nums, MAXELS) << endl;
return 0;
}
// find the maximum value
int find_max( int vals[ ], int num_els)
{
int i, max = vals[0];
for ( i = 1; i < num_els; i++)
if (max < vals[i] ) max = vals[i];
return max;
}
Passing two-dimensional arrays into a function is a process identical to passing singledimensional arrays. The called function receives access to the entire array.
Example :
int test [7][9];
float factors [26][10];
double thrusts [256][52];
then the following function calls are valid :
find_max (test);
obtain (factors);
average (thrusts);
on the receiving side :
int find_max(int nums[7][9] )
int obtain(float values [26][10] )
int average (double vals[256][52] )
Sample program52: Passing Two-Dimensional array into a function that displays the
array values.
#include<iostream>
#include<iomanip>
//function prototype
int main ( )
{
int val [ROWS][COLS] = { 8, 16, 9, 52,
3, 15, 27, 6,
14, 25, 2, 10 };
display (val);
return 0;
}
void display (int nums[ROWS][COLS] )
{
int row_num, col_num;
for (row_num = 0; row_num < ROWS; row_num++)
{
for (col_num = 0; col_num < COLS; col_num++)
cout << setw(4) << nums[row_num][col_num];
cout << endl;
}
return;
}
Exercise :
1. Write a program that has a declaration in main ( ) to store the following numbers into
an array named temps: 6.5, 7.2, 7.5, 8.3, 8.6, 9.4, 9.6, 9.8, 10.0. There should be a
function call to show ( ) that accepts the temps array as a parameter named temps and
then displays the numbers in the array.