Repetition Structures: Programming Fundamentals 1
Repetition Structures: Programming Fundamentals 1
Repetition Structures: Programming Fundamentals 1
REPETITION STRUCTURES
Programming Fundamentals 1
Chapter 5
n while loops
n Interactive while loops
n for loops
n Nested loops
n do-while Loops
n Structured programming with C++
n Arrays
n Structures
Programming Fundamentals 2
Overview
n C++ provides three different forms of repetition structures:
1. while structure
2. for structure
3. do-while structure
n If the test is at the end of the loop, the type of loop is a post-
test loop.
Programming Fundamentals 3
Fixed count loop and variable condition loop
n In addition to where the condition is tested, repeating sections
of code are also classified.
n In a fixed count loop, the condition is used to keep track of how
many repetitions have occurred. In this kind of loops, a fixed
number of repetitions are performed, at which point the
repeating section of code is exited.
Programming Fundamentals 4
while loops
The while statement is used
for repeating a statement or
series of statements as long
as a given conditional Enter the while statement
expression is evaluated to
true.
false
test the
condition ?
The syntax for the while true
statement:
Execute the
statement (s)
Programming Fundamentals 5
Example 5.2.1
1 2 3 4 5 6 7 8 9 10
Programming Fundamentals 6
In the above program, the loop incurs a counter-controlled
repetition. Counter-controlled repetition requires:
1) the name of a control variable (the variable count )
2) the initial value of the control variable ( count is
initialized
to 1 in this case
3) the condition that tests for the final value of the control
variable (i.e., whether looping should continue) ;
4) the increment (or decrement) by which the control
variable
is modified each time through the loop.
Programming Fundamentals 7
INTERACTIVE while LOOP
n Combining interactive data entry with the while statement
produces very adaptable and powerful programs.
Example 5.3.1
#include <iostream.h>
int main(){
int total, // sum of grades
gradeCounter, // number of grades entered
grade, // one grade
average; // average of grades
total = 0;
gradeCounter = 1; // prepare to loop
while ( gradeCounter <= 10 ) { // loop 10 times
cout << "Enter grade: "; // prompt for input
cin >> grade; // input grade
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
}
Programming Fundamentals 8
// termination phase
average = total / 10; // integer division
cout << "Class average is " << average <<
endl;
return 0;
} The output of the above program:
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Programming Fundamentals 9
Sentinels
n In programming, data values used to indicate either the
start or end of a data series are called sentinels.
n The sentinels must be selected so as not to conflict with
legitimate data values.
Example 5.3.2
#include <iostream.h>
const int HIGHGRADE = 100; // sentinel value
int main()
{
float grade, total;
grade = 0;
total = 0;
cout << "\nTo stop entering grades, type in any number"
<< " greater than 100.\n\n";
Programming Fundamentals 10
cout << "Enter a grade: ";
cin >> grade;
while (grade <= HIGHGRADE)
{
total = total + grade;
cout << "Enter a grade: ";
cin >> grade;
}
cout << "\nThe total of the grades is " << total << endl;
return 0;
}
n In the above program, the sentinel is the value 100 for the entered
grade.
Programming Fundamentals 11
break statement
n The break statement causes an exit from the innermost
enclosing loop.
Example:
while( count <= 10)
{
cout << “Enter a number: “; cin >> num;
if (num > 76){
cout << “you lose!\n”;
break;
}
else
cout << “Keep on trucking!\n”;
count++;
}
//break jumps to here
Programming Fundamentals 12
continue Statements
n The continue statement halts a looping statement and restarts
the loop with a new iteration.
Programming Fundamentals 13
The null statement
n All statements must be terminated by a semicolon. A semicolon
with nothing preceding it is also a valid statement, called the
null statement. Thus, the statement
;
is a null statement.
n Example:
if (a > 0)
b = 7;
else ;
Programming Fundamentals 14
for LOOPS
n The for statement is used for repeating a statement or series of
statements as long as a given conditional expression evaluates
to true.
Programming Fundamentals 15
Enter the for statement
Initialization expression
false
test the
condition ?
true
Execute the
statement (s)
Programming Fundamentals 16
Example 5.4.1
// This program prints the even number from 2 to 20
#include <iostream.h>
int main()
{
int count;
for (count = 2; count <= 20; count = count + 2)
cout << count << " ";
return 0;
}
2 4 6 8 12 14 16 18 20
Programming Fundamentals 17
Example 5.4.2 In this example, we have to solve the problem:
A person invests $1000.00 in a saving account with 5 percent
interest. Assuming that all interest is left on deposit in the
account, calculate and print the amount of money in the account
at the end of each year for 10 years. Use the following formula
for determining these amounts:
a = p(1 + r)n
where p is the original amount invested, r is the annual interest rate
and n is the number of years and a is the amount on deposit at
the end of the nth year.
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
int main()
{
double amount,
principal = 1000.0, rate = 0.05;
cout << "Year” << setw(21)
<< "Amount on deposit" << endl;
Programming Fundamentals 18
cout << setiosflags(ios::fixed | ios::showpoint) <<
setprecision(2);
for (int year = 1; year <= 10; year++)
{
amount = principal*pow(1.0 + rate, year);
cout << setw(4) << year << setw(21) << amount << endl;
}
return 0; The output of the above program:
}
Year Amount on deposit
1 1050.00
2 1102.50
3 1157.62
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89
Programming Fundamentals 19
NESTED LOOPS
n In many situations, it is convenient to use a loop contained
within another loop. Such loops are called nested loops.
n Example 5.4.1
#include <iostream.h>
int main()
{
const int MAXI = 5;
const int MAXJ = 4;
int i, j;
for(i = 1; i <= MAXI; i++) // start of outer loop
{
cout << "\ni is now " << i << endl;
for(j = 1; j <= MAXJ; j++) // start of inner loop
cout << " j = " << j; // end of inner loop
} // end of outer loop
Programming Fundamentals 20
cout << endl;
return 0;
}
i is now 1
j=1 j=2 j=3 j=4
i is now 2
j=1 j=2 j=3 j=4
i is now 3
j=1 j=2 j=3 j=4
i is now 4
j=1 j=2 j=3 j=4
i is now 5
j=1 j=2 j=3 j=4
Programming Fundamentals 21
do-while LOOPS Enter the do-while
statement
Execute the
statement (s)
false
test the
condition ?
true
Programming Fundamentals 22
Example of do while loop
do {
cout<< “\nEnter an identification number:”;
cin >> idNum;
} while (idNum < 1000 | | idNum> 1999);
Programming Fundamentals 23
n A refined version of the above program:
do {
cout<< “\nEnter an identification number:”;
cin >> idNum;
if (idNum < 1000 || idNum > 1999)
{
cout << “An invalid number was just entered\n”;
cout << “Please reenter an ID number /n”;
}
else break;
} while (true);
Programming Fundamentals 24
STRUCTURED PROGRAMMING WITH C++
n The goto Statement
n Example:
n Note: The goto statement
start: // label can lead to programs that
if (cout > 10) go to end; are more difficult to debug,
… maintain, and modify.
…
go to start;
end: cout << endl;
Programming Fundamentals 25
Structured Programming
n During the 1960s, it became clear that the
indiscriminate use of transfers of control through
goto statements was the root of much difficulty
experienced by programmer groups.
n The notion of so-called structured programming
became almost synonymous with “goto elimination.”
Programming Fundamentals 26
statement 1
A sequence structure
statement 2
Programming Fundamentals 27
n C++ provides three types of selection structures:
- if statement (single-selection structure)
- if-else statement (double-selection structure)
- switch statement. (multiple-selection structure)
Programming Fundamentals 28
Building programs in good style
n Each C++ program is formed by combining as many of each
type of control structures as appropriate for the algorithm the
program implements.
n We will see that each control structure has only one entry point
and one exit point. These single-entry/single-exit control
structures make it easy to build programs.
Programming Fundamentals 29
Indentation
n Consistent applying reasonable indentation
conventions throughout your programs greatly
improves program readability. We suggest a fixed-
size tab of about ¼ inch or three blanks per indent.
Programming Fundamentals 30
Top-down Stepwise Refinement
n Using good control structures to build programs is
one of the main principles of structured
programming. Another principle of structured
programming is top-down, stepwise refinement.
n Example: Consider the following problem:
Develop a class-averaging program that will process
an arbitrary number of grades each time the program
is run.
Programming Fundamentals 31
First Refinement
First Refinement:
Initialize variables
Input, sum and count the exam grades
Calculate and print the class average.
Programming Fundamentals 32
Second Refinement
n To proceed to the next level of refinement, we need
some variables and a repetition structure.
n We need a running total of the numbers, a count of
how many numbers have been processed, a variable
to receive each grade as it is input and a variable to
hold the average.
n We need a loop to calculate the total of the grades
before deriving the average.
n Because we do not know in advance how many
grades are to be processed, we will use sentinel-
controlled repetition.
n The program will test for the sentinel value after
each grade is input and terminate the loop when the
sentinel value is entered by the user.
Programming Fundamentals 33
n Now we come to the pseudo-code of the second
refinement.
Second Refinement:
Input the first grade(possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade(possibly the sentinel)
Calculate and print the class average
Programming Fundamentals 34
Third refinement
n The pseudocode statement
Calculate and print the class average
can be refined as follows:
If the counter is not equal to zero
set the average to the total divided by the counter
print the average
else
Print “No grades were entered”.
n Notice that we are being careful here to test for the
possibility of division by zero.
Programming Fundamentals 35
n Now we come to the pseudocode of the third refinement
Third Refinement:
Initialize total to zero
Initialize counter to zero
Input the first grade
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade
If the counter is not equal to zero
set the average to the total divided by the counter
print the average
else
Print “No grades were entered”.
Programming Fundamentals 36
The final C++ program
n Final step: After coding, we come to the following C++ program.
#include <iostream.h>
#include <iomanip.h>
int main()
{
int total, gradeCounter, grade;
double average; // number with decimal point for average
// initialization phase
total = 0;
gradeCounter = 0;
// processing phase
cout << "Enter grade, -1 to end: ";
cin >> grade;
Programming Fundamentals 37
while ( grade != -1 ) {
total = total + grade;
gradeCounter = gradeCounter + 1;
cout << "Enter grade, -1 to end: ";
cin >> grade;
}
// termination phase
if ( gradeCounter != 0 ) {
average = double ( total ) / gradeCounter;
cout << "Class average is " << setprecision( 2 )
<< setiosflags( ios::fixed | ios::showpoint )
<< average << endl;
}
else
cout << "No grades were entered" << endl;
return 0;
}
Programming Fundamentals 38
ARRAYS
§ An array is an advanced data type that contains a set
of data represented by a single variable name.
§ An element is an individual piece of data contained in
an array.
§ The following figure shows an integer array called c.
c[0] = 4; c[1] = 4, c[2] = 8, etc.
4 4 8
Programming Fundamentals 39
Array Declaration
n The syntax for declaring an array is
type name[elements];
n Example:
int arMyArray[3];
char arStudentGrade[5];
Programming Fundamentals 40
Subscript
n The numbering of elements within an array starts with an index
number of 0.
n Example:
Programming Fundamentals 41
A example of array
Example 5.8.1
#include <iostream.h>
int main(){
char arStudentGrade[5]= {‘A’, ‘B’, ‘C’, ‘D’, ‘F’};
for (int i = 0; i <5; i++)
cout << arStudentGrade[i];
return 0;
}
Programming Fundamentals 42
Example 5.8.2
// Compute the sum of the elements of the array
#include <iostream.h>
int main()
{
const int arraySize = 12;
int a[ arraySize ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 };
int total = 0;
for ( int i = 0; i < arraySize; i++ )
total += a[ i ];
cout << "Total of array element values is " << total << endl;
return 0 ;
}
Programming Fundamentals 43
Multi-Dimensional Arrays
n C++ allows arrays of any type, including arrays of arrays. With
two bracket pairs we obtain a two-dimensional array.
n The idea can be iterated to obtain arrays of higher dimension.
With each bracket pair we add another dimension.
Programming Fundamentals 44
A two-dimensional array
n Starting at the base address of the array, all the array
elements are stored contiguously in memory.
n For the array b, we can think of the array elements
arranged as follows:
Programming Fundamentals 45
Example 5.8.3 This program checks if a matrix is symmetric or not.
Programming Fundamentals 46
Strings and String Built-in Functions
n In C++ we often use character arrays to represent strings. A
string is an array of characters ending in a null character (‘\0’).
n A string may be assigned in a declaration to a character array.
The declaration
Programming Fundamentals 47
n C++ does not provide built-in operations for strings. In C++, you
must use a string built-in functions to manipulate char variables.
Some commonly used string functions are listed in Table 5.1.
Function Description
-----------------------------------------------------------------------------------------------
strcat() Append one string to another
strchr() Find the first occurrence of a specified character in a
string
strcmp() Compare two strings
strcpy() Replaces the contents of one string with the
contents of another
strlen() Returns the length of a string
Programming Fundamentals 48
n The strcpy() function copies a literal string or the contents of a
char variable into another char variable using the syntax:
strcpy(destination, source);
strcat(destination, source);
Programming Fundamentals 49
Example:
char FirstName[25];
char LastName[25];
char FullName[50];
strcpy(FirstName, “Mike”);
strcpy(LastName, “Thomson”);
strcpy(FullName, FirstName);
strcat(FullName, “ “);
strcat(FullName, LastName);
Programming Fundamentals 50
Example 5.8.4
#include<iostream.h>
#include<string.h>
int main()
{
char FirstName[25];
char LastName[25];
char FullName[50];
strcpy(FirstName, "Mike");
strcpy(LastName, "Thomson");
strcpy(FullName, FirstName);
strcat(FullName, " ");
strcat(FullName, LastName);
cout << FullName << endl;
int n;
n = strcmp(FirstName, LastName);
if(n<0)
cout<< FirstName << " is less than "<< LastName<<endl;
Programming Fundamentals 51
else if(n ==0)
cout<< FirstName << " is equal to “
<< LastName<<endl;
else
cout<< FirstName << " is greater than “
<< LastName<<endl;
return 0;
}
Mike Thomson
Mike is less than Thomson
Programming Fundamentals 52
STRUCTURES
n A structure, or struct, is an advanced, user-defined data type
that uses a single variable name to store multiple pieces of
related information.
struct struct_name{
data_type field_name;
data_type field_name;
……..
} variable_name;
Programming Fundamentals 53
To access a field inside a structure
n Example:
struct emloyee{
char firstname[25];
char lastname[25];
long salary;
};
variable.field;
Programming Fundamentals 54
Example 5.9.1
#include <iostream.h>
struct Date // this is a global declaration
{
int month;
int day;
int year;
};
int main(){
Date birth; // birth is a variable belonging to Date type
birth.month = 12;
birth.day = 28;
birth.year = 1982;
cout << "\nMy birth date is "
<< birth.month << '/‘ << birth.day << '/'
<< birth.year % 100 << endl;
return 0;
}
Programming Fundamentals 55
Arrays of Structures
n The real power of structures is realized when the same
structure is used for lists of data.
n Example 5.9.2:
The following program uses array of employee records. Each of
employee record is a structure named PayRecord. The program
displays the first five employee records.
#include <iostream.h>
#include <iomanip.h>
const int MAXNAME = 20; // maximum characters in a name
Programming Fundamentals 56
struct PayRecord // this is a global declaration
{
long id;
char name[MAXNAME];
float rate;
};
int main()
{
const int NUMRECS = 5; // maximum number of records
int i;
PayRecord employee[NUMRECS] = {
{ 32479, "Abrams, B.", 6.72 },
{ 33623, "Bohm, P.", 7.54},
{ 34145, "Donaldson, S.", 5.56},
{ 35987, "Ernst, T.", 5.43 },
{ 36203, "Gwodz, K.", 8.72 } };
cout << endl; // start on a new line
Programming Fundamentals 57
cout << setiosflags(ios::left);
// left justify the output
for ( i = 0; i < NUMRECS; i++)
cout << setw(7) << employee[i].id
<< setw(15) << employee[i].name
<< setw(6) << employee[i].rate << endl;
return 0;
}