0% found this document useful (0 votes)
85 views105 pages

Array Function String

The document discusses using parallel one-dimensional arrays to store related data. It describes using multiple arrays to store part numbers, descriptions, quantities, and prices, with the elements in the same position across arrays corresponding to the same part. It also provides an example of using two parallel arrays to store membership types and associated fees for a motorcycle club program. Parallel arrays have their elements related by position to efficiently associate related data stored in separate arrays.

Uploaded by

buyt kuyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views105 pages

Array Function String

The document discusses using parallel one-dimensional arrays to store related data. It describes using multiple arrays to store part numbers, descriptions, quantities, and prices, with the elements in the same position across arrays corresponding to the same part. It also provides an example of using two parallel arrays to store membership types and associated fees for a motorcycle club program. Parallel arrays have their elements related by position to efficiently associate related data stored in separate arrays.

Uploaded by

buyt kuyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 105

Parallel One Dimensional

Array

1
2

Design Problem
 Consider the task of
keeping track of data
about parts for
manufacture
» part number,
description, qty
needed, unit price
3

Parallel Array
 Use “Parallel” arrays
 One array each for part
num, descrip, qty, price partid desc qty price
 nth item in any one of
A100 xxx 5 1.23 0
the arrays associated
with same nth item of all
B25 yyy 23 8.95 1
the arrays
» string partid[]
» string desc[] 2
» int qty[]
» double price[]
Parallel One-Dimensional Arrays
 Program for a motorcycle club displays annual fee
associated with membership type entered by user
 Program uses two parallel one-dimensional arrays
» char array named types: stores the five
membership types
» int array named fees: stores annual fee associated
with each type
 Two arrays are referred to as parallel arrays if their
elements are related by their position in the arrays

4
Parallel One-Dimensional Arrays (cont’d.)

5
Parallel One-Dimensional Arrays (cont’d.)

6
Parallel One-Dimensional Arrays (cont’d.)

7
Parallel One-Dimensional Arrays (cont’d.)

8
Parallel One-Dimensional Arrays (cont’d.)

9
Parallel One-Dimensional Arrays (cont’d.)

10
Parallel One-Dimensional Arrays (cont’d.)

Sample run of the club membership program

11
Passing Array to Function

Chapter 9

12
Passing Arrays to Functions

Just as you can pass single values to a


function, you can also pass an entire
array to a function.

13
14

Arrays as Parameters
 This is one task that CAN be done to the
WHOLE array
 C++ always passes arrays by reference
Passing Size along with Array

Normally when you pass an array to a


function, you should also pass its size in
another argument. So the function knows
how many elements are in the array.
Otherwise, you will have to hard code this
into the function or declare it in a global
variable. Neither is flexible or robust.

15
Pass-by-Reference

Passing an array variable means that the


starting address of the array is passed to
the formal parameter. The parameter inside
the function references to the same array
that is passed to the function. No new
arrays are created. This is pass-by-
reference.

16
Base Address of an Array and Array 17

in Computer Memory

 The base address of an array is the address,


or memory location of the first array
component
 If myList is a one-dimensional array, its base
address is the address of myList[0]
 When we pass an array as a parameter, the
base address of the actual array is passed to
the formal parameter
Base Address of an Array and Array in 18

Computer Memory (cont’d.)


Example: PassArrayDemo

#include <iostream>
using namespace std;
void printArray(int list[], int arraySize); // function prototype

int main()
{ 1 list[0]
int myList[5] = {1, 4, 3, 6, 8};
printArray(myList, 5);
return 0;
4 list[1]
}
3 list[2]
void printArray(int list[], int arraySize)
{ 6 list[3]
for (int i = 0; i < arraySize; i++)
{ 8 list[4]
cout << list[i] << " ";
}
}
20

Arrays as Parameters
 The name of the array is a pointer
constant
 The address of the array is passed to
the function
 Size of the
array also
passed to
control loop
21

Arrays as Parameters
 Note the empty brackets in parameter
list
» A number can be placed here but it
will be ignored
22

Sub-array Processing
 Note we specified an array size of 100
» but we don’t anticipate that many scores
 Array always declared larger than needed
 Must keep track of how many have been
used
» this is our limit when doing other things
to the array
Example: PassByReferenceDemo

#include <iostream> void m(int number, int numbers[])


using namespace std; {
void m(int, int []); number = 1001;
// Assign a new value to number
int main() numbers[0] = 5555;
{ // Assign a new value to numbers[0]
int x = 1; // x -an int value }
int y[10]; // y -an array of int values
y[0] = 1; // Initialize y[0]
m(x, y); // Invoke m with arg x , y
cout << "x is " << x << endl;
cout << "y[0] is " << y[0] << endl;
return 0; }
const Parameters

Passing arrays by reference makes sense for performance


reasons. If an array is passed by value, all its elements must
be copied into a new array.
For large arrays, it could take some time and additional
memory space.
However, passing arrays by reference could lead to errors if
your function changes the array accidentally.
To prevent it from happening, you can put the const keyword
before the array parameter to tell the compiler that the array
cannot be changed.
The compiler will report errors if the code in the function
attempts to modify the array.

24
Example: ConstArrayDemo
#include <iostream>
using namespace std;

void p(int const list[], int arraySize)


{
// Modify array accidentally
list[0] = 100; // Compile error!
}

int main()
{
int numbers[5] = {1, 4, 3, 6, 8};
p(numbers, 5);

return 0;
}
26

Functions Cannot Return a Value of the Type Array

 C++ does not allow functions to return a


value of the type array
Returning an Array from a Function

Can you return an array from a function using a


similar syntax? For example, you may attempt to
declare a function that returns a new array that is a
reversal of an array as follows:

// Return the reversal of list

X
int[] reverse(const int list[], int size)

This is not allowed in C++.

27
Modifying Arrays in Functions, cont.

However, you can circumvent this restriction by


passing two array arguments in the function, as
follows:
// newList is the reversal of list
void reverse(const int list[], int newList[], int size)

list

newList

28
Example: ReverseArray

#include <iostream> int main()


using namespace std; {
int size = 6;
// newList is the reversal of list int list1[] = {1, 2, 3, 4, 5, 6};
void reverse(const int list[], int newList[], int list2[6] = {0};
int size)
{ reverse(list1, list2, size);
for (int i = 0, j = size - 1; i < size; i++, j--) cout << "The original array: ";
newList[j] = list[i]; printArray(list1, 6);
} cout << endl;
cout << "The reversed array: ";
void printArray(const int list[], int size) printArray(list2, 6);
{ cout << endl;
for (int i = 0; i < size; i++) return 0;
cout << list[i] << " "; }
}
Trace the reverse Function
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);
void reverse(const int list[], int newList[], int size)
{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

30
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);
i = 0 and j = 5
void reverse(const int list[], int newList[], int size)
{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 0

31
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);
i (= 0) is less than 6

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}
list 1 2 3 4 5 6

newList 0 0 0 0 0 0

32
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 0 and j = 5
} Assign list[0] to newList[5]
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

33
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; After this, i becomes 1 and
} j becomes 4
}

list 1 2 3 4 5 6

newList 0 0 0 0 0 1

34
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);
i (=1) is less than 6
void reverse(const int list[], int newList[], int size)
{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
}
}
list 1 2 3 4 5 6

newList 0 0 0 0 0 1

35
Trace the reverse Method, cont.

int list1[] = {1, 2, 3, 4, 5, 6};


reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i = 1 and j = 4
Assign list[1] to newList[4]
}
list 1 2 3 4 5 6

newList 0 0 0 0 2 1

36
Trace the reverse Method, cont.

int list1[] = {1, 2, 3, 4, 5, 6};


reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; After this, i becomes 2
} and j becomes 3

}
list 1 2 3 4 5 6

newList 0 0 0 0 2 1

37
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
i (=2) is still less than 6
newList[j] = list[i];
}
}

list 1 2 3 4 5 6

newList 0 0 0 0 2 1

38
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 2 and j = 3
} Assign list[2] to newList[3]

}
list 1 2 3 4 5 6

newList 0 0 0 3 2 1

39
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; After this, i becomes 3
} and j becomes 2

list 1 2 3 4 5 6

newList 0 0 0 3 2 1

40
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=3) is still less than 6

}
list 1 2 3 4 5 6

newList 0 0 0 3 2 1

41
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 3 and j = 2
} Assign list[3] to newList[2]
}

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

42
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 4
} and j becomes 1

list 1 2 3 4 5 6

newList 0 0 4 3 2 1

43
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=4) is still less than 6

}
list 1 2 3 4 5 6

newList 0 0 4 3 2 1

44
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 4 and j = 1
Assign list[4] to newList[1]
}
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

45
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 5
and j becomes 0
}

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

46
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} i (=5) is still less than 6

list 1 2 3 4 5 6

newList 0 5 4 3 2 1

47
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i = 5 and j = 0
} Assign list[6] to newList[0]
}

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

48
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i];
} After this, i becomes 6
and j becomes -1
}

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

49
Trace the reverse Method, cont.
int list1[] = {1, 2, 3, 4, 5, 6};
reverse(list1, list2);

void reverse(const int list[], int newList[], int size)


{
for (int i = 0, j = size - 1; i < size; i++, j--)
{
newList[j] = list[i]; i (=6) < 6 is false. So exit
} the loop.

list 1 2 3 4 5 6

newList 6 5 4 3 2 1

50
Case Study: Production Graph

 Problem Definition:
» We are writing a program for the Apex Plastic
Spoon Company
» The program will display a bar graph showing the
production of each of four plants for a week
» Each plant has separate records for each
department
» Input is entered plant by plant
» Output shows one asterisk for each 1000 units,
and production is rounded to the nearest 1,000
units
Analysis of The Problem
 Use an array named production to hold
total production of each plant
» Production for plant n is stored in production[n-1]

 Program must scale production to nearest


1,000 units to display asterisks in the bar
Production Graph Sub-Tasks
 Analysis leads to the following sub-tasks
» input_data :
Read input for each plant
Set production [plant_number -1] to the total
production for plant number n
» Scale :
For each plant, change
production[plant_number] to the correct number
of asterisks
» Graph : Output the bar graph
More Analysis Details

 The entire array will be an argument for the


functions we write to perform the subtasks
» We will also include a formal parameter for the size
» The size of the array is equal to the number of
plants
» We will use a constant for the number of plants
Algorithm Design: input_data
 We must read all departments' data for each
plant and add them to produce a plant's total
» Algorithm for input_data:
for plant_number is 1, 2, …, last_plant_number

do the following
Read all the data for plant number plant_number
Sum the numbers
Set production[plant_number – 1] to the total
Coding input_data
 The algorithm can be translated to C++ as:

void input_data(int a [ ], int last_plant_number)


{
using namespace std;

for (int plant_number = 1; plant_number <= last_plant_number;


plant_number++)
{
cout << endl << "Enter production for plant"
<< plant_number << endl;
get_total( a[plant_number -1] );
}
}
Testing input_data

 Each function should be tested in a program in


which it is the only untested function
 Because input_data calls get_total, get_total is
tested first
 Once tested, get_total can be used to test
input_data
Test Data for input_data
 Remember that input_data should be tested
» With a plant that contains no production figures
» With a plant having only one production figure
» With a plant having more than one figure
» With zero and non-zero production figures
Algorithm for scale
 scale changes the value of the indexed variable
to show the whole number of asterisks to print
» Scale is called using
scale (production, NUMBER_OF_PLANTS);
and its algorithm is
for (int index = 0; index < size; index++)
Divide the value of a[index] by 1,000 and
round the result to the nearest integer
Coding scale
 The code for scale, below, uses a function
named
round that must be defined as well
» void scale(int a[ ], int size)
{
for (int index = 0; index < size; index++)
a[index] = round (a[index] / 1000.0);
}
Why not 1000?
Function floor
 Function round, called by scale, uses the floor
function from the cmath library
» The floor function returns the first whole
number less than its argument:
floor (3.4) returns 3
floor (3.9) returns 3
» Adding 0.5 to the argument for floor is how
round performs its task
floor (3.4 + 0.5) returns 3
floor (3.9 + 0.5) returns 4
Testing scale
 To test scale
» First test round
» Scale should be tested with
arguments that
–Are 0
–Round up
–Round down
73

C-Strings or Character Arrays


 We have learned that the elements of an
array can be just about anything
 Consider an array whose elements are
all characters
» Called a C-String
» Has a collection of special routines
» Treated differently for I/O than other
types of arrays
74

Declaration of C-Strings
 Similar to declaration of any array
char name[30];
// no initialization
char title [20] = "Le Grande Fromage";
// initialized at declaration
// with a string
char chList [10] = {'a', 'b', 'c', 'd'};
// initialized with list of char
// values
75

Working with Character Strings


 String => a collection of characters interpreted as a
single item
» a structured data item
» in C++ a null-terminated sequence of characters
stored in a char array
 All strings in C++ are terminated by the null character
» character 0, ‘\0’
76

Initializing Strings
 When a character array is declared, it is legal
to use the assignment operator to initialize

 Note : use of the = operator only legal for char


array initialization
 But : aggregate array assignment is NOT

greeting = “don’t do it”;


77

String Output
 Strings (character arrays) are handled
differently than other types of arrays
 This would NOT be allowed
int num_list [100];
. . .
cout << num_list;
 This is legal:
char name [30] = “Snidly Q. Fizbane”;
. . .
cout << name;
78

String Input
 Declare strings 1
element bigger than
planned size to
allow for ‘\0’

 When input takes place, C++ automatically


places the ‘\0’ in memory at the end of the
characters typed in
79

Problems with >> for String Input

 Cannot be used to input a string with


imbedded blanks
 >> stops reading as
soon as it
encounters first
whitespace
character
80

Problems with >> for String Input


 Solve problem by using getline ( … )

Quits reading after 15 characters


or when it hits a newline,
whichever comes first.

Includes all characters


including spaces, tabs, etc
(whitespace characters)
81

Problems with >> for String Input


 If declared string is too small >> keeps
putting characters in memory PAST that
area in memory
s2 contents extend
into the memory
area of s3
82

Using Strings
 Instead of “hard coding” file name for the open (
… ) command,
» use a string variable,
» use keyboard entry with cin.getline(…)
» program more flexible, good for different files

ifstream inFile;
char fname[31];
cout << “Enter file name -> “;
cin.getline (fname, 30, ‘\n’);
inFile.open (fname);
83

String Library Routines


 Recall that we could not use the aggregate
assignment of one string to another
 C++ provides some string handling functions to
do this (and other similar tasks)
 Found in
<string.h>
or
<cstring>
84

Contrast/Compare Strings and C-Strings

 Assignment is OK  Assignment is illegal


string s; char cs[30];
s = "hi mom"; cs = "don't do it";
 Comparison OK  Comparisons not allowed
if (s < "geek") …
 I/O allowed much the
 I/O allowed
cin >> s; same way
cin.getline(s,'\n');
cout << s;
85

Working with C-Strings

 Functions provided in #include <cstring>

Used instead of assignment

Used for comparisons


Problem: Counting Occurrence of Each Letter

 Generate 100 lowercase chars[0] f counts[0] 2


letters randomly and chars[1] a counts[1] 1
assign to an array of … j
… … 0

characters. a :
… … … …
: :
 Count the occurrence of chars[98] r counts[24] 3
each letter in the array. chars[99] b counts[25] 4
 Need 2 arrays
» Array of character
generated (100
lowercase letters)
» Array of count (no of
occurrence for each
letter) 86
87

Function prototypes
#include <iostream>
#include <ctime>
using namespace std;
const int NUMBER_OF_RANDOM_LETTERS = 100;
void createArray(char []);
void displayArray(const char []);
void countLetters(const char [], int []);
void displayCounts(const int []);
88

Main function
int main()
{
char chars[NUMBER_OF_RANDOM_LETTERS]; //declare array
// Initialize the array with random lowercase letters
createArray(chars);
// Display the array
cout << "The lowercase letters are: " << endl;
displayArray(chars);
// Count the occurrences of each letter
int counts[26];
countLetters(chars, counts);
// Display counts
cout << "\nThe occurrences of each letter are: " << endl;
displayCounts(counts);
return 0;
}
89

// Create an array of characters

void createArray(char chars[])


{
// Create lowercase letters randomly and assign
// them to the array
srand(time(0));
for (int i = 0; i < NUMBER_OF_RANDOM_LETTERS; i++)
chars[i] = rand() % ('z' - 'a' + 1) + 'a';
}
90

// Display the array of characters

void displayArray(const char chars[])


{
// Display the characters in the array 20 on each line
for (int i = 0; i < NUMBER_OF_RANDOM_LETTERS; i++)
{
if ((i + 1) % 20 == 0)
cout << chars[i] << " " << endl;
else
cout << chars[i] << " ";
}
}
91

// Count the occurrences of each letter

void countLetters(const char chars[], int counts[])


{
// Initialize the array
for (int i = 0; i < 26; i++)
counts[i] = 0;

// For each lowercase letter in the array, count it


for (int i = 0; i < NUMBER_OF_RANDOM_LETTERS; i++)
counts[chars[i] - 'a'] ++;
}
92

// Display counts
void displayCounts(const int counts[])
{
for (int i = 0; i < 26; i++)
{
if ((i + 1) % 10 == 0)
cout << counts[i] << " " << static_cast<char>(i + 'a')
<< endl;
else
cout << counts[i] << " " << static_cast<char>(i + 'a')
<< " ";
} }
93

Use of parallel array


You are given a list of students’ names and their test
scores. Write a C++ program that does the following
using an array and function (use two arrays – an array of
string for students’ name and array of double for test
score) :
 Calculates the average test scores.
 Determines and prints the names of all the students
whose test scores are below the average test score.
 Determines the highest test score.
 Prints the names of all the students whose test scores
are the same as the highest test score.
94

Specification Requirements
 Need to process a students’ result :
–Calculate average test scores
–Determines and prints the names of all the
students whose test scores are below the
average test score.
–find the highest test score.
–Prints the names of all the students whose
test scores are the same as the highest
test score.
95

Problem analysis
 Input - a list of students’ names and their test scores
 Output :–
» average test scores
» list of student names whose test scores < average test score
» highest test score
» list of student names whose test scores are the same as the
highest score
 Process / calculation :
» average test score = (sum of test scores)/ number of students
» print student names whose test scores < average test score
» find highest test score
» print student names whose test scores == highest test score
96

Algorithm (flow chart or pseudocode)

 Suppose averageTestScore denotes the average test


score, highestScore denotes the highest test score,
testScore denotes a test score, sum denote the sum
of all the test scores, and count denotes the number
of students in class, and studentName denotes the
name of a student.
 First you design an algorithm to find the average test
score. To find the average test score, first you need to
count the number of students in the class and add the
test score of each student. You then divide the sum
by count to find the average test score.
97

average test score


1. Set sum and count to 0.
2. Repeat the following for each student in class.
i. Get testScore for each student
ii. Increment count and update the value of sum by
adding the current testScore to sum.
3. Use the following formula to find the average test score.
if (count is 0)
averageTestScore = 0
otherwise
averageTestScore = sum / count
98

Test Score below average


 The following algorithm determines and prints the
names of all the students whose test score is below
the average test score.
1. Repeat the following for each student in class:
i. Get studentName and testScore
ii. if (testScore is less than averageTestScore)
print studentName
99

Highest test score


 The following algorithm determines and highest test
score
1. Get first student’s test score and call it
highestTestScore.
2. Repeat the following for each of the remaining
students in class
i. Get testScore
ii. if (testScore is greater than highestTestScore)
highestTestScore = testScore
100

Test score same as highest test score

 To print the names of all the students whose test


score is the same as the highest test score, compare
the test score of each student with the highest test
score and if they are equal print the name. The
following algorithm accomplishes this
1. Repeat the following for each student in class:
i. Get studentName and testScore
ii. if (testScore is equal to highestTestScore)
print studentName
101

Testing and Debugging Hints


 Range of legal index values is 0 to array_size - 1
 Individual elements of the array are of the
component type
 No aggregate operations in arrays
» you must write the code to do this
 If array parameter is incoming, specify formal
parameter as const
» prevents function from modifying
102

Testing and Debugging Hints


 Omitting array size in declaration
» when array declared formal parameter
» when array initialized at declaration
 Don’t pass component when function expects
entire array
 Declare array size as max ever needed
» process only part of array which is used
 Pass array name and length to functions which
process array or sub array
103

Testing and Debugging


 Be sure to account for null character when
you manipulate characters individually in a
string
 Remember proper use of the =
» correct for initialization at declarationtime
» INCORRECT for aggregate assignment
 Aggregate input/output allowed for strings but
NOT for other array types
104

Testing and Debugging


 If you use the >> for string input, make sure
» string is declared large enough
» string will have no white spaces
 The >> operator stops at, but does not consume
the first trailing white space
» such as ‘\n’ or a space
 The cin.getline (whatever, 30, ‘\n’ ) function
» stops when reading the ‘\n’
» consumes the ‘\n’
» has problems when ‘\n’ is still in the input stream
105

Testing and Debugging


 When using the strcpy ( ), make sure
that the destination array is declared long
enough
 Choose test data carefully for string handling
programs
» include strings that are too large
» include strings with whitespace

You might also like