Book C++ Internet
Book C++ Internet
Definition
Example : ADD 1, 2
MUL 2, 3
Low level - language that uses instructions that are directly tied to one type of
computer.
High level – uses instructions that resemble written languages, such as English
and can be run on a variety of computer types.
Example : C++, Basic, Pascal, Fortran
Programming Languages
Software Development
development
and design
Steps :
testing
coding
design
analysis
Time
1. Analyze the problem
- required to ensure that the problem is clearly defined and
understood (understanding of how the inputs can be
used to produce the desired output)
what the system or program must do
what outputs must be produced
what inputs are required to create the desired outputs
2. Develop a solution
- select the exact set of steps, called an algorithm, that you will
use to solve the problem
- the solution is typically obtained by a series of refinements,
starting with the initial algorithm found in the analysis step until
an acceptable and complete algorithm is obtained.
Example :
Inventory
Control First level structure
program
Data
Entry Calculation Report
Section Sect ion Section
Inventory
Control First level structure
program
Data
Entry Calculation Report
Section Sect ion Section
Phase II : Documentation
- documenting your work is the most important step in solving a
problem
1. program description
2. algorithm development and changes
3. well-commented program listing
4. sample test runs
5. 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
Exercises :
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++
Was invented by Bjarne Stroustrup in 1979 at Bell Laboratories
Begins with C
Built upon the foundation of C
Supports object oriented programming
Extended library routines were the added features
Has undergone three major revisions, 1985, 1990, during the
standardization process
In 1994 the standard was created, we have now the ANSI/ISO C++
ANSI (American National Standards Institute)
ISO (International Standards Organization)
Module 1
Module 2 Module 3
It can be :
1. Function – a small machine that transforms the data it receives into a finish
product
a x b
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.
Structure
Sample program1 :
return 0;
}
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)
Exercises :
Example :
1.625e3
6.3421e4
7.31e-3
6.25e-4
Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Modulus Division %
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;
}
All integer, floating point and other values used in a computer program are stored
and retrieved from the computer’s memory.
Example : To store the integer values 45 and 12 in the memory locations 1652
and 2548 respectively .
45 12
1652 2548
Memory addresses
Variables
- symbolic names in place of actual memory addresses
- a name given by the programmer that is used to refer to
computer storage locations.
- it used in programs because the value stored in the variable
can change.
Rules :
1. variable name must begin with a letter or underscore
2. variable name cannot be a keyword
3. variable name cannot consist for more than 31
characters
variable names
num 1 num 2 total
45 12 57
1652 2548 45
Memory Addresses
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.
Declaration Statements
- naming a variable and specifying the data type that can be
stored in it
#include <iostream>
using namespace std;
int main( )
{
declaration statements :
other statements ;
return 0;
}
Sample Program4 :
#include <iostream>
using namespace std;
int main( )
{
float grade1;
float grade2;
float total;
float average;
grade1 = 85.5 ;
grade2 = 97.0;
total = grade1 + grade2;
average = total /2.0;
return 0;
}
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.
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.
Declaration statements can also be used to store an initial value into declared variables.
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
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 0.20
76 0.30
96 0.35
87 0.25 Then get the total test score.
Assignment Operators
Example :
factor = 1.06;
weight = 155.0;
totalWeight = factor * weight;
Sample Program7 :
#include <iostream>
using namespace std;
int main( )
{
float radius, height, volume;
radius = 2.5 ;
height = 16.0;
volume = 3.1416 * radius * radius * height;
return 0;
}
Accumulating
These expressions are required in accumulating subtotals when data is
entered one number at a time.
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
++ increment operator
Expression Alternative
i=i+1 i ++ or ++ i
n=n+1 n++ or ++n
count = count + 1 count++ or ++count
Example : k = ++n does two things in one expression; the value of n is incremented by 1
and then the new value of n is assigned to the variable k
Equivalent to n = n + 1;
k = n;
k = n++ first assigns the current value of n to k and then increment the value of n by one
Equivalent to k = n;
n = n + 1;
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
Manipulator Action
width (n) - cout.width set the field width to n
precision (n) - cout.precision Set the floating-point precision to n places
Setf (flags) - cout.setf(ios: :showpos) Set the format flags
Dec Set output for decimal display
Hex Set output for hexadecimal display
Oct Set output for octal display
Field manipulators are useful in printing columns of numbers so that the numbers in
each column are align correctly.
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.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).
Mathematical Functions
sqrt ( ) function determines the square root of its argument and returns the result
as a double.
sqrt (number)
#include <cmath>
abs(-7.362) 7.362000
abs(-3) 3
pow(2.0, 5.0) 32.00000
pow(10, 3) 1000
log(18.69) 2.92863
log10(18.697) 1.271772
exp(-3.2) 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;
}
1. Write a program that calculates and returns the 4th root of the number 81.0, which
is 3.
# 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 ;
Exercises :
1. Write a program that will convert a number entered in Celsius to degrees Fahrenheit.
3. Write a program that enter the weight of a person in kilograms and output it in pounds.
( 1 kilogram = 2.2 pounds)
4. Write a program that will enter the name, year level, school course and age of a user
and display in the order :
Name :
Year Level :
Course :
School
Age :
5. Write a program that calculates and prints a paycheck of an employee. The net pay is
calculated after taking the following deductions.
Income tax = 15%
Social Security tax = 10%
Health Insurance = 1.5%
Pension plan = 5%
SELECTION STRUCTURES
Selection Criteria
Pseudocode syntax :
if ( condition)
statement is executed if condition is “true” ;
else
statement is executed if condition is “false” ;
relational operator
operand operand
watts < 15.2
Numerical operands
Example :
3 < 2 true = 1
2.0 > 3.0 false = 0
Logical Operators
1. AND (symbol &&) – the condition is true only if both individual expression are
true themselves
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 Associativity
! unary - ++ -- 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 no (else part)
true ?
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
Example ;
int a = 25;
int b = 17;
float a = 46.25;
int c = 10;
One-Way Selection
- is only executed if the expression has a nonzero value (true
condition)
if (expression)
statement;
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
float radius;
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
{
char temp_type;
float temp, fahren, celsius;
{
celsius = (5.0 / 9.0) * (temp – 32.0 );
cout << “\nThe equivalent Celsius temperature is : “ << celsius;
else
{
fahren = (9.0 / 5.0) * temp + 32.0;
cout << “\nThe equivalent Fahrenheit temperature is : “ << fahren;
}
return 0;
#include <iostream>
using namespace std;
int main ( )
{
const float LIMIT = 3000.0;
int id_num;
float miles;
cout << “ Car” << id_num << “ is over the limit. \n” ;
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”;
is no (else part)
expression-1
true
yes
is no (else part)
expression-2
true
yes
if (expression_1)
statement1;
else
if (expression_2)
statement 2;
else
statement 3;
is no (else part)
expression-1
true
yes
statement-1
is no (else part)
expression-2
true
yes
statement 3
statement 2
Sample Program19: if-else chain
#include <iostream>
using namespace std;
int main( )
{
char 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:
#include <iostream>
using namespace std;
int main( )
{
int digout;
float 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;
return 0;
}
Exercises :
Using this information, write a C++ program that accepts the number of
credits a student has completed, determines the student’s grade level, and
displays the grade level
Using this information, write a C++ program that accepts a student’s 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.
The Switch Statement
- provides an alternative to the if-else chain for cases that
compare the value of an integer expression to a specific value
General form :
switch (expression)
{ // start of compound statement
case value_1:
statement1;
statement2;
:
:
break;
case value_2:
statementm;
statementn;
:
:
break;
:
case value_n:
statementw;
statementx;
:
:
break;
default :
statementaa;
statementbb;
Example :
switch (number)
{
case 1 :
cout << “Have a Good afternoon\n” ;
break;
case 2 :
cout << “Have a Happy Day\n” ;
break;
case 3:
case 4 :
case 5 :
cout << “Have a Nice Evening\n” ;
}
Sample Program21:
#include <iostream>
using namespace std;
int main( )
{
int opselect;
double fnum, snum;
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
Using this information, write a C++ program that accepts a student’s numerical
grade, converts the numerical grade to an equivalent letter grade, and displays
the letter grade.
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.
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
a. while structure
b. for structure
c. do while structure
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.
1. Pretest Loop - condition is tested before any statements within the loop
are executed.
- if condition is true, the executable statements within the
loop are executed, if initial value of the condition is false,
the executable statements within the loop are never
executed and control transfers to the first statement after
the loop
- also referred to as entrance-controlled loops.
- Example : while and for loop
previous
statement
is
the condition yes loop
true ? statement
No
next
statement
previous
statement
loop
statement
is Yes
the condition
true ?
No
next
statement
1. Fixed count loop - the condition is used to keep track of how many repetitions
have occurred
- fixed number of calculations is performed or a fixed
- number of lines are printed, at which point the repeating
section of code is exited
2. Variable condition loop - the tested condition does not depend on a count
being reached, but rather on a variable that can
change interactively with each pass through the
loop. When a specified value is encountered,
regardless of how many iterations have occurred
repetitions stop.
while Loops
expression
evaluates
to zero
test
the expression exit the
(step 1) ( a false condition) while statement
expression
evaluates
to a nonzero
number
( a true condition)
Comparison :
# include <iostream>
using namespace std;
int main ( )
{
int count;
count = 1;
while (count <=10)
{
return 0;
}
Sample program23 :
# include <iostream>
using namespace std;
int main ( )
{
int i ;
i = 1;
while (i >=10)
{
return 0;
}
Sample program24 : Printing a table of numbers 1 to 10
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
int num;
num = 1;
while (num < 11)
{
cout << setw(3) <<num << “ “
<< setw(3) <<num * num << “ “
<< setw(3) <<num * num * num ;
num++;
}
return 0;
}
Sample Program25 : Fixed-count loop where counter is not incremented by 1
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
int celsius ;
float fahren;
celsius = START_VAL;
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.
Sample Program26 :
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
return 0;
}
Exercises:
print a
message
set count
equal to 1
is
count less no
than or equal stop end of program
to 4 condition is false
yes
(condition is true)
print the
message
enter a
number :
Loop
print value
of number
add 1 to
count
Flow of control diagram Sample program5.5
new
number
new number
goes in here
num
the variable total total
new total +
total = total + sum
Start
set count
to one
set total
to zero
is
count no
print total
yes
add num
to total
add 1 to
count Accumulation flow of control
Sample Program27 :
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
count = 1;
total = 0;
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 - data values used to signal either the start or end of a data
series.
- must be selected so as not to conflict with legitimate data
values
Sample program28 :
#include <iostream>
using namespace std;
int main()
{
const int HIGHGRADE = 100;
float grade, total;
grade = 0;
total = 0;
{
total = total + grade;
cout << “Enter a grade: “ ;
cin >> grade;
// value higher than 100 is entered, the loop is exited. Sum is displayed.
1. break – forces an immediate break, or exit from switch, while, for and do
while statements
else
cout << “Keep on trucking!\n”;
count++
}
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.
Null Statement
All statements must be terminated by a semi-colon. A semi-colon with nothing
preceding it is also a valid statement, called a null statement.
For Loop
Syntax :
Example :
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 i’s
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;
return 0;
}
Output :
#include <iostream>
using namespace std;
int main ( )
{
int count;
return 0;
}
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 << “ “, count = count +2);
return 0;
}
enter the
for statement
initializing
statement
expression’s value
evaluate is zero
the tested exit the
expression false condition for statement
expression’s value
is nonzero
( true condition)
execute the
statement
Loop after the
parentheses
execute the
altering
list
enter for
statement
expression’s value
is nonzero
for exit for
expression (false condition) statement
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
const int MAXNUMS = 10;
int num;
return 0;
}
Exercises :
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.
#include <iostream>
using namespace std;
int main ( )
{
const int MAXCOUNT = 4;
int count;
float num, total,average;
return 0;
}
#include <iostream>
using namespace std;
int main ( )
{
const int MAXNUMS = 5;
int i ;
float usenum, postot, negtot;
postot = 0;
negtot = 0;
{
cout << “Enter a number [positive or negative] : “;
cin >> usenum;
if (usenum > 0)
postot = postot + usenum;
else
negtot = negtot + usenum;
}
return 0;
}
Sample program 33: Evaluating Functions of One Variable
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main ( )
{
int x, y ;
return 0;
}
Sample Program34:
// any equation with one unknown can be evaluated using a single for or an
equivalent while loop, using an integer.
// specifying a noninteger increment, solutions for fractional values
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main ( )
{
float x, y ;
return 0;
}
Values used to control a loop may be set using variables rather than constant
values.
i = 5;
j = 10;
k = 1;
Sample Program35:
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
int num, final;
return 0;
}
Exercises :
y = 3x5 – 2x3 + x
for x between 5 and 10 in increments of 0.2
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
Example :
Output :
a is now 1
j=1 j=2 j=3 j=4
a is now 2
j=1 j=2 j=3 j=4
a is now 3
j=1 j=2 j=3 j=4
a is now 4
j=1 j=2 j=3 j=4
a is now 5
j=1 j=2 j=3 j=4
Sample Program36
#include <iostream>
using namespace std;
int main ( )
{
const int MAXA = 5;
const int MAXJ = 4;
int a, j;
Sample Program37
#include <iostream>
using namespace std;
int main ( )
{
const int NUMGRADES = 4;
const int NUMSTUDENTS = 20;
int x , y ;
float grade, total, average;
{
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 :
1st generator : 122.5 122.7 123.0 4th generator : 122.9 123.8 126.7
2nd generator : 120.2 127.0 125.1 5th generator : 121.5 124.7 122.6
3rd generator : 121.7 124.9 126.0
do while Loops
previous
statement
do loop
statement
is Yes
the condition
true ?
No
next
statement
do while structure
General form :
do
statement ;
while (expression) ;
Sample Program35:
#include<iostream>
#include <iomanip.h>
using namespace std;
int main ( )
{
int count;
count = 0;
do
{
count = count + 1;
cout << count << endl;
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;
return 0;
}
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
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;
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. If – else
2. Switch
3. For
4. While
5. 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.
3. Displays an item’s specification corresponding to a letter input. The following
letter codes are used :
4. Print a positive number and then print the successive values where each value is 0.5
less than the previous value. The list should continue as long as values to be printed is
positive.
Temperature
95.75
83.0
97.625
72.5
86.25
All temperature in a list are floating-point numbers, however the list can be
declared as a single unit and stored under a common variable name called the array
name
Examples:
const int NUMELS = 6; each array is allocated sufficient
int volts [NUMELS]; memory to hold the number of
data items given in the declaration
const int ARRAYSIZE = 4; statement; thus the array named
char code [ARRAYSIZE]; volts has storage reserved for 6 int
Illustrated Storage reserved :
volts an an an an an an
array integer integer integer integer integer 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
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)
Statements like : sum = temp [0] + temp [1] + temp [2] + temp [3] + temp [4]; is
unnecessary.
for loop is advantageous to sequence through an array when working with larger arrays.
Example : Assume that we want to locate the maximum value in an array of 1000
elements
const int NUMELS = 1000;
Individual array elements can be assigned values interactively using a cin stream object.
Examples :
cin >> temp [0]; // single value will be read and stored in temp [0] variable
cin >> temp [1] >> temp[2] >> temp[3];
cin >> temp [4] >> volts [6];
Using the for loop to cycle through the array for interactive data :
Caution for storing data in an array : C++ does not check the value of the index being
used ( called bounds check).
Example : If an array has been declared consisting of 10 elements and you use 12
index which is outside the bounds of an array, C++ will notify the error
when the program is compiled.
int main( )
{
const int MAXTEMPS = 5;
int x, temp [MAXTEMPS];
return 0;
}
#include <iostream>
using namespace std;
int main( )
{
const int MAXTEMPS = 5;
int x, temp [MAXTEMPS] , total = 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 :
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.
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};
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]
s a m p l e \0
#include <iostream>
using namespace std;
int main( )
{
const int MAXELS = 5;
int x, max, nums [MAXELS] = {2, 18, 1, 27, 16} ;
Exercises :
1. Write a program that uses an array declaration statement to initialize the following
numbers in an array named slope : 17.24, 25.63, 5.94, 33.92, 3.71, 32.84, 35.93, 18.24,
6.92. Your program should locate and display both the maximum and minimum values of
the array.
2. Write a declaration to store the string “This is a test” into an array named strtest.
Include the declaration in a program to display the message using the following loop:
for ( x = 0; x < NUMDISPLAY; x++)
cout << strtest [x];
Two-dimensional array
- sometimes referred to as a table, consists of both rows and column of
elements.
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 int val [3][4];
Sample declarations :
Row 0 8 16 9 52
Row 1 3 15 2 6 val [1] [3]
Row 2 14 25 2 10
Row Column
position position
Examples :
watts = val [2] [3];
val [0] [0] = 62;
newnum = 4 * (val [1] [0] – 5 );
sumRow0 = val[0][0] + val [0][1] + val [0][2] + val [0][3];
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 : int val [3][4] = { 8, 16, 9, 52, 3, 15, 27, 6, 14, 25, 2, 10 };
This is equally valid but does not illustrate to the programmer where one row ends and
another begins.
#include <iostream>
#include <iomanip>
using namespace std;
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 };
return 0;
}
** each pass through the outer loop corresponds to a single row, with the inner loop
supplying the appropriate column elements.**
Sample Program42 : Nested for loop used to multiply each element in the val array by
the scalar number 10 and display the resulting value.
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
return 0;
}
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.
Three dimensional can be viewed as a book of data tables. The first index can be thought
of as the location of the desired row in a table; second index as the desired column; and
the third index, which is often called the rank, as the page number of the selected table.
Exercises :
1. Write a C++ program that adds the values of all elements in the val array used in
sample program13 and displays the total.
2. Write a C++ program that adds equivalent elements of the two dimensional arrays
named First and Second. Both arrays should have two rows and three columns. For
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.
First Second
16 18 23 24 52 77
54 91 11 16 19 59
Example :
mathematical functions – a function is called, or used, by giving the function’s name and
passing any data to it, as arguments, in the parentheses.
The called function must be able to accept the data passed to it by the function
doing the calling
Only after the called function successfully receives the data can the data be
manipulated to produce a useful result
Sample Program43:
#include <iostream>
using namespace std;
int main ( )
{
int firstnum, secnum;
cout << “\n Enter a numer: “;
cin >> firstnum;
cout << “great ! Please enter a second number: “;
cin >> secnum;
return 0;
}
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.
fmax ( ) declares that this function expects to receive two integer arguments and
will formally return an integer value
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.
Calling a function
- 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.
Arguments - are items enclosed within the parentheses.
ststored in firstnum
the variable
get the value
a value firstnum
stored in secnum
a value the variable
secnum
get the value
Defining a Function
{
constant and
variable declarations; Function body
any other C++ statements;
}
Example :
void FindMax ( int x, int y) no semicolon [header line]
The first part of the call procedure executed by the computer involves going to the
variables firstnum and secnum and retrieving the stored values. These values are then
passed to FindMax ( ) and ultimately stored in the parameter x and y.
FindMax ( )
the the
parameter parameter
named x named y
Sample Program44 :
#include <iostream>
using namespace std;
{
int firstnum, secnum;
return 0;
}
// following is the function FindMax ()
return;
} // end of function body and end of function
Sample Output :
Enter a number : 25
Great! Please enter a second number : 5
Placement Statements
preprocessor directives
function prototypes
int main ( )
named constants
variable declarations
function definitions
Function Stubs
Stub - is the beginning of a final function that can be used as a placeholder for
the final unit until the unit is completed
- “fake” function.
Sample Program44a :
#include <iostream>
using namespace std;
int main ( )
{
int firstnum, secnum;
return 0;
}
The function prototype for such function requires either writing the keyword void
or nothing at all between the parentheses following the function’s name.
Example : int display ();
Default Arguments
- convenient feature of C++ is its flexibility of providing default arguments in
a function call
- primary use is to extend the parameter list of existing functions without
requiring any change in the calling argument lists already in place within a
program.
- Are listed in the function prototype and are automatically transmitted to
the called function when the corresponding arguments are omitted from
the function call.
Sample Program45 :
Write a function named sqr_it () that computes the square of the value passed to it and
displays the result. The function should be capable of squaring numbers with decimal
points.
#include <iostream>
using namespace std;
void sqr_it(double);
int main()
double first;
return 0;
}
cout << “The square of “ << num << “ is ” << (num * num) ;
return ;
}
Exercises :
Using the method of passing data into a function, the called function only receives
copies of the values contained in the arguments at the time of the call, the passed
argument is referred to as passed by value and is a distinct advantage of C++. Since
the called function does not have direct access to the variables used as arguments by
the calling function, it cannot inadvertently alter the value stored in one of these
variables.
As with the calling function, directly returning a value requires that the interface between
the called and calling functions be handled correctly. The called function must provide
the following items :
To return a value, a function must use a return statement which is in the form
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.
Example :
Sample Program45 :
#include <iostream>
using namespace std;
return 0;
}
// following is the function FindMax ()
Sample Program46 :
#include <iostream>
using namespace std;
int main()
{
cout << “\nEnter a Fahrenheit temperature: “;
cin >> fahren;
cout << “The Celsius equivalent is “
<< tempvert (fahren);
}
return 0;
}
Exercises :
S = 2πrl
where r is the cylinder’s 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.
Returning Multiple Values
There are times, when it is necessary for the called function to have direct access to the
variables of its calling function. This allows one function, which is the called function, to
use and change the value of the variables that has been defined in the calling function.
To do this requires that the address of the variable be passed to the called function.
Once the called function has the variable’s address, it “knows where the variable lives”,
and can access and change the value stored there directly.
In exchanging data between two functions we must be concerned with both the sending
and receiving sides;
Sending Side : calling a function and passing an address as an argument that will be
accepted as a reference parameter is exactly the same as calling a function and passing
a value; the called function is summoned into action by giving its name and a list of
arguments.
Example : newval (firstnum, secnum); both calls the function named newval
and passes two arguments to it.
int& secnum
char& key
& - symbol used within a declaration it refers to “the address of” the
preceding data type
Function header for newval : void newval (float& num1, float& num2)
Sample Program47 :
#include <iostream>
using namespace std;
int main()
return 0;
}
xnum = 89.5;
ynum = 99.5;
return;
}
The Equivalence of arguments and parameters
Firstnum secnum
xnum ynum
Sample Output :
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>
using namespace std;
int main()
{
return 0;
}
void calc ( float num1, float num2, float num3, float& total, float& product)
{
total = num1 + num2 + num3;
product = num1 * num2 * num3;
return;
}
main()
A value is passed 18.5 150.0
calc( )
The desired exchange of main ( )’s variables by swap ( ) can only be obtained by giving
swap () access to main’s variables, by reference parameters.
#include <iostream>
using namespace std;
int main()
{
return 0;
}
float temp;
return;
}
Output :
The value stored in firstnum is : 20.5
The value stored in secnum is : 6.25
1. reference arguments must be variables (that is, they cannot be used to change
constants)
2. a function call itself gives no indication that the called function will be using
reference arguments
Exercises :
1. Write a function named time ( ) that has an integer parameter named seconds
and three integer reference parameters named hours, min and sec. The function
is to convert the passed number of seconds into an equivalent number of hours,
minutes, and seconds. Using the references function should directly alter the
respective arguments in the calling function.
2. Write a function named change ( ) that has integer parameter and six integer
reference parameters named hundreds, fifties, twenties, tens, fives and ones
respectively. The function is to consider the passed integer value as a dollar
amount and convert the value into the fewest number of equivalent bills. Using
references the function should directly alter the respective arguments in the
calling function.
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:
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];
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.
Sample Program50:
#include <iostream>
using namespace std;
int main ( )
{
return 0;
}
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.
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.
// 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;
}
Sample Program51:
#include <iostream>
using namespace std;
int main ( )
{
const int MAXELS = 5;
int nums[MAXELS] = { 2, 18, 1, 27, 16};
return 0;
}
return max;
}
Example :
int test [7][9];
float factors [26][10];
double thrusts [256][52];
Sample program52: Passing Two-Dimensional array into a function that displays the
array values.
#include<iostream>
#include<iomanip>
using namespace std;
int main ( )
{
int val [ROWS][COLS] = { 8, 16, 9, 52,
3, 15, 27, 6,
14, 25, 2, 10 };
display (val);
return 0;
}
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.