carme.cs.trinity.educarme.cs.trinity.edu/thicks/ctextbook/chap07-arrays.doc  · web viewnote that...

88
Defining Data Introduction to Computer Science With C: Programming, Problem Solving, & Data Structures Thomas E. Hicks Douglas W. Nance Thomas L. Naps Copyright Pending for West Publishing Co.

Upload: others

Post on 03-May-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

Defining Data

Introduction to Computer Science With C:

Programming, Problem Solving,& Data Structures

Thomas E. HicksDouglas W. NanceThomas L. Naps

Copyright Pending for West Publishing Co.

Page 2: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [2]

They may say what they like, everything is organized matter. Napoleon Bonaparte

One-Dimensional Arrays & Character Strings

This chapter begins a significant new stage of programming. Prior to now, we have been unable to manipulate and store large amounts of data in a convenient way. For example, if we wanted to work with a long list of numbers or names, we had to declare a separate variable for each number or name. Fortunately, C (and most other programming languages) provides several structured variables to facilitate solving problems that require working with large amounts of data. Simply put, an array is a structure that uses one identifier to reserve a large amount of memory. This memory is capable of holding several individual values. Structured variables included in this text are arrays, records, files, and sets.

Arrays, the topic of this chapter, are designed to handle large amounts of data of the same type in an organized manner. Using arrays permits us to set aside a group of memory locations that we can then manipulate as a single entity or have direct access to any component. Some very standard applications for array variables include creating tabular output (tables), alphabetizing a list of names, analyzing a list of test scores, manipulating character data, and keeping an inventory.

Section 7.1 introduces both character and numeric arrays; they will be filled with a variety random numbers, assigned values, and sequences. Section 7.2 examines the filling of arrays from keyboard and potential overflow problems. Section 7.3 introduces sorting with special emphasis on the selection sort. Section 7.4 studies the passing of arrays to subprograms and pointer arithmetic. Section 7.5 examines searching with special emphasis on sequential and binary techniques. Section 7.6 returns us to string processing.

7.1Basic Idea and Notation

Declaration of Arrays and Array Assignments

As previously mentioned, there are many instances in which several variables of the same data type are required. Let us at this point work with a list of five integers: 18, 17, 21, 18, and 19. Prior to this chapter, we would have declared five variables--A, B, C, D, and E--and assigned them appropriate values. This would have produced five values in memory each accessed by a separate identifier.

If the list was very long, this would be an inefficient way to work with these data; an alternative is to use an array. In C, we declare a variable as an integer array with 5 elements by

int Data [5];

The five individual portions of the array are referred to as cells or components or elements of the array. When Age is declared as an integer, the contents of the two bytes of memory assigned by the memory manager are unknown. When

Page 3: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [3]

Data is declared as an array of five integers, ten bytes (5 elements * 2 bytes/int) of contiguous memory are allocated; the contents of the ten bytes of memory are unknown. Subscripts of 0-4 are used to index the five individual cells within array Data.

The individual elements of the array could be filled by

Data [0] = 18;Data [1] = 17;Data [2] = 21;Data [3] = 18;Data [4] = 19;

The statements above can be arranged in any order. If the individual elements of the array were printed by

printf ("%d ", Data [0] );printf ("%d ", Data [1] );printf ("%d ", Data [2] );printf ("%d ", Data [3] );printf ("%d ", Data [4] );

the output would be

18 17 21 18 19

Using Loops To Fill and Display Arrays

Initializing or printing 1000 items within an array, element by element as above, would require a lot of inefficient coding. A lot of the power of the array structure is related to efficient combinations of loops. Let us place the first five even numbers into an array, called EvenNos, and verify the assignments with an appropriate print loop.

Example 7.1int EvenNos [5];

After the declaration above, we have five integer variables with which to work. The compiler has allocated 10 bytes (5 * 2 bytes per int) of contiguous memory for the array EvenNos. Since EvenNos is the symbolic name for a contiguous chunk of memory, its base address may be referenced by combining the symbolic name and the address indicator. Either of the following lines of code may be used to print the base address of array EvenNos:

printf ("EvenNos = &%lu\n", EvenNos);printf ("EvenNos = &%lu\n", &EvenNos);

Output:

EvenNos = &2753454EvenNos = &2753454

The contiguous block of memory to house array EvenNos is assigned by the memory manager; if you run the code fragment above, both lines will display the

Page 4: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [4]

same address, but it is unlikely that your memory manager will select address &2753454 to store the array.

The individual elements of the array could be filled by

EvenNos [0] = 0;EvenNos [1] = 2;EvenNos [2] = 4;EvenNos [3] = 6;EvenNos [4] = 8;

or more efficiently by

for (Index = 0; Index < 10; Index ++)EvenNos[Index] = Index* 2;

To verify that our assignment statements (either of the two program fragments above) had completed their tasks properly, we could the code fragment

printf ("%d\n", EvenNos [4] );printf ("%d\n", EvenNos [3] );printf ("%d\n", EvenNos [2] );printf ("%d\n", EvenNos [1] );printf ("%d\n", EvenNos [0] );

or (more efficiently) by

for (Index = 4; Index >=0; Index = Index --)printf ("%d\n", EvenNos[Index] );

Either of the two program fragments above will produce the following output:

86420

A good method of visualizing these variables is to assume that memory locations are aligned in a column on top of each other and the name of the column is EvenNos. The contents of the array EvenNos and the addresses associated with each of the elements may be printed by

printf (" |--------|\n");printf ("4 : EvenNos [4] => %lu | %3i |\n",&EvenNos[4],EvenNos[4]);printf (" |--------|\n");printf ("3 : EvenNos [3] => %lu | %3i |\n",&EvenNos[3],EvenNos[3]);printf (" |--------|\n");printf ("2 : EvenNos [2] => %lu | %3i |\n",&EvenNos[2],EvenNos[2]);printf (" |--------|\n");printf ("1 : EvenNos [1] => %lu | %3i |\n",&EvenNos[1],EvenNos[1]);printf (" |--------|\n");printf ("0 : EvenNos [0] => %lu | %3i |\n",&EvenNos[0],EvenNos[0]);printf (" |--------|\n");

or more efficiently by

Page 5: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [5]

for (Index = 4; Index >= 0; Index --){ printf (" |--------|\n"); printf ("%d : EvenNos [%d] => %lu | %3i |\n",Index, Index, &EvenNos[Index],EvenNos[Index]);}

printf (" |--------|\n");

Either of the two program fragments above will produce the following output:

|--------|4 : EvenNos [4] => &2753462 | 8 | |--------|3 : EvenNos [3] => &2753460 | 6 | |--------|2 : EvenNos [2] => &2753458 | 4 | |--------|1 : EvenNos [1] => &2753456 | 2 | |--------|0 : EvenNos [0] => &2753454 | 0 | |--------|

Notice that the address associated with EvenNos[0] is the same address associated with EvenNos and &EvenNos. We have three ways in which we can address the ten bytes of contiguous memory (bytes &2753454 – &2753463) assigned to array EvenNos.

The components of an array are referred to by their relative position in the array. This relative position is called the index or subscript of the array . It is important to remember that each array component is a variable and can be treated exactly as any other declared variable of that data type; this means that EvenNos[1], or any other component of array EvenNos, may be treated like any other integer. The subscript of an array may be an integer constant, an integer variable, or an integer expression. The sizeof function can be used (inside the subprogram declaring the local array) to display the number of bytes in the array. The line

printf ("The size of EvenNos = %lu bytes\n", sizeof (EvenNos));

produces

The size of EvenNos = 10 bytes

Let us now examine this declaration more closely. Several comments are in order. Assume that an array has been declared by

int List [5]; /* 10 bytes */

1. "List" can be any valid identifier. As always, it is good practice to use descriptive names to enhance readability.

2. An array can be declared involving any valid data type; each of the following will allocate five blocks of contiguous blocks of memory in accordance with their respective data types:

long int A [5]; /* 5 * 4 byte long = 20 bytes */

Page 6: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [6]

float B [5]; /* 5 * 4 byte float = 20 bytes */double C [5]; /* 5 * 12 byte double = 60 bytes */char D [5]; /* 5 * 1 byte char = 5 bytes */long int * E[5]; /* 20 bytes – all pointers are 4 bytes */double *F [5]; /* 20 bytes – all pointers are 4 bytes */boolean

G [5]; /* 10 bytes */

3. "[5]" is the syntax that indicates the array consists of five memory components accessed by specifying each of the subscripts {0, 1, 2, 3, and 4}. We frequently say the array is of length five. The information inside the brackets is the index and is used to reference individual components of an array. This index is of integer type and must be in the range 0–4. Assignments to array elements outside the range 0 – 4 will not produce a compilation error, but are likely to destroy other variables in your program or crash the system. Only advanced computer scientists generally know enough about memory management to justify using an index beyond the declared boundaries of an array. Take every precaution to be sure that your array index is within normal boundaries.

4. Use the define statement for the MAX_NOS so that it is easier to change the size of your arrays as programs grow.

# define MAX_NOS 100int EvenNos[MAX_NOS];

for (Index = 0; Index < MAX_NOS; Index ++)printf ("%d\n", EvenNos[Index] );

for (Index = MAX_NOS - 1; Index >= 0; Index --){printf (" |--------|\n");

printf ("%d : EvenNos [ %2i ] => %lu | %3i |\n",Index, Index,&EvenNos[Index],EvenNos[Index]);

} printf (" |--------|\n");

It is easier to change one globally defined constant than to change each and every loop in every subprogram which manipulates the arrays. Each C compiler will have a maximum number of bytes for a declared array such as the one above; common limits are 16 K and 32 K. If the compiler limit is 16K, then the maximum number of bytes for one array is32767. When you need a single structure greater than the limit, use dynamic memory allocation.

Example 7.2A die has sides numbers 1–6. Let us write a program that will display the

number of times each of the numbers 1–6 are generated with 6000 randomized rolls of a die. We shall declare an array called DiceDistribution to hold the number of 1's, the number of 2's, etc. that have been rolled.

If the array were declared to contain 6 integer values, then one could place the number of 1's in element 0, the number of 2's in element 1, etc.; although this does utilize space efficiently, it sacrifices logical representation. It makes

Page 7: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [7]

more sense to place the number of 1's in element 1, the number of 2's in element 2, etc. The array below is declared to contain 7 integer values. Element 0 of the array will not be used.

Some high–level languages allow computer scientists to declare an array whose valid subscript range of elements is [2..12] or [1..6]; C, however, does not permit such a subrange of elements. In the program below, the first element of array DiceDistribution (DiceDistribtion[0]) simply will not be used in the program.

#include <stdlib.h>#include <stdio.h># define MAX_ROLLS 6000

main (int argc, char argv[]){int Index, Die, DiceDistribution [7] = {0,0,0,0,0,0,0}; /* Initialize the counters to 0 */

/* DiceDistribution[5] = No 5's */for (Index = 1; Index <= MAX_ROLLS; Index ++){ /* If the Die rolled is a 5 */Die = (int) (rand()/32768.0 * 6 + 1); /* DiceDistribution[5]++ */DiceDistribution[Die] ++;

} for (Index = 6; Index >= 1; Index --){

printf (" |--------|\n"); printf ("DiceDistribution [ %2i ] => &%lu | %4i |\n", Index, &DiceDistribution[Index],DiceDistribution[Index]);}

printf (" |--------|\n");}

]The output from the program fragment above is

|--------|DiceDistribution [ 6 ] => &2943160 | 1018 | |--------|DiceDistribution [ 5 ] => &2943158 | 995 | |--------|DiceDistribution [ 4 ] => &2943156 | 1000 | |--------|DiceDistribution [ 3 ] => &2943154 | 989 | |--------|DiceDistribution [ 2 ] => &2943152 | 986 | |--------|DiceDistribution [ 1 ] => &2943150 | 1012 | |--------|

Notice that the numbers selected by the random number generator were pretty close to 1000 (+/– 18). Perhaps we will wish to examine the distributions of other random numbers within other positive ranges. Using appropriate defines, we can make the program fragment above more generic. Suppose we wanted to generate 9000 random numbers in the range 5 - 13.

# define MAX_EVENTS 9000# define HIGH_NO 13

Page 8: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [8]

# define LOW_NO 5

main (int argc, char argv[]){int Index, Array [HIGH_NO+1];

for (Index = LOW_NO; Index <= HIGH_NO; Index ++) /* Initialize counters to 0 */Array[Index] =0;

for (Index = 1; Index <= MAX_ROLLS; Index ++) /* Roll & increment */Array[((int)(rand()/32768.0 * (HIGH_NO-LOW_NO+1) + LOW_NO))] ++;

for (Index = HIGH_NO; Index >= LOW_NO; Index --){

printf (" |--------|\n"); printf ("Array [ %2i ] => &%lu | %4i |\n", Index, &Array[Index],Array[Index]);}

printf (" |--------|\n");}

Array was declared to contain HIGH_NO + 1 elements in order to store the number of 5's in element 5, the number of 6's in element 6, etc. Elements 0 - 4 of this array are not used in the program above. At some point the computer scientist would decide that the amount of memory wasted would justify a different solution. The output from the code fragment above would be

|--------|Array [ 13 ] => &2943154 | 998 | |--------|Array [ 12 ] => &2943152 | 1011 | |--------|Array [ 11 ] => &2943150 | 1000 | |--------|Array [ 10 ] => &2943148 | 1005 | |--------|Array [ 9 ] => &2943146 | 988 | |--------|Array [ 8 ] => &2943144 | 1000 | |--------|Array [ 7 ] => &2943142 | 996 | |--------|Array [ 6 ] => &2943140 | 1022 | |--------|Array [ 5 ] => &2943138 | 980 | |--------|

Some subprogramss and program fragments are going to be so specific to a particular problem that it is a waste of time to consider generic solutions to families of problems. Other subprograms and program fragments will be needed in many similar applications. As you gain more programming experience, you will become more proficient in determining the usability of code. Keep the generic programming issue in mind as you design and implement new code.

Example 7.3

Page 9: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [9]

Each die has numbers 1–6. The sums for a Pair of Dice will be in the range 2 – 12. Let us write a program that will display the number of times each of the valid Sums are generated with 600 randomized rolls of a pair of dice. The first solution to the problem is

#include <stdio.h>#include <stdlib.h>

# define MAX_ROLLS 600

main (int argc, char argv[]){int Index, Die1, Die2, Sum, DiceSum [13] = {0,0,0,0,0,0,0,0,0,0,0,0,0}; /* Initialize Sum Counters */

for (Index = 1; Index <= MAX_ROLLS; Index ++) /* Roll Dice, Calculate Sum, & */{ /* Increment Sum Counter */Die1 = (int) (rand()/32768.0 * 6 + 1);Die2 = (int) (rand()/32768.0 * 6 + 1);Sum = Die1 + Die2;DiceSum[Sum] = DiceSum[Sum]+1;

} for (Index = 12; Index >= 2; Index --){

printf (" |--------|\n"); printf ("DiceSum [ %2i ] => &%lu | %3i |\n", Index, &DiceSum[Index],DiceSum[Index]);}

printf (" |--------|\n");}

Although the logic may not be as obvious, the next code fragment (below) performs identically to the previous program. Notice that three local variables (Die1, Die2, and Sum) have been eliminated; this solution saves six bytes of memory (for these three integers) and saves a very small amount of time with fewer assignment statements. The second solution is more memory efficient, but the logic is less obvious. The computer scientist must often choose between readability and efficiency. When the computer scientist is designing operating systems, compilers, or real time systems, he/she often strives toward efficiency; for most applications that must be maintained, readability is often more important than a few bytes of memory. Many of today's compilers have compiler optimization options which produce more time efficient and space efficient code; these help the computer scientist to greater efficiency while maintaining readability. As you get into higher level computer science courses, consult your compiler manual(s) and try the optimization options if they exist.

int Index, DiceSum [13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};

for (Index = 1; Index <= MAX_ROLLS; Index ++)DiceSum[((int)(rand(void)/32768.0 * 6 + 1))+

((int)(rand(void)/32768.0 * 6 + 1))] ++;

Page 10: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [10]

Solution one and solution two both allocated memory for a DiceSum[0] and DiceSum[1]. This was a waste of four bytes of memory. For completeness, let us provide a third solution (below) which allocates only 11 elements for array DiceSum; although this solution is more space efficient, it is also less readable than either of the other solutions.

int Index, DiceSum [11] = {0,0,0,0,0,0,0,0,0,0,0};

for (Index = 1; Index <= MAX_ROLLS; Index ++)DiceSum[((int)(rand(void)/32768.0 * 6 + 1))+

((int)(rand(void)/32768.0 * 6 + 1))-2] ++;

The following program fragment could be used with to display the array contents and addresses for either of the first two solutions.

for (Index = 12; Index >= 2; Index --){ printf (" |--------|\n"); printf ("%2i : DiceSum [ %2i ] => &%lu | %3i |\n",

Index, Index, &DiceSum[Index],DiceSum[Index]);}

printf (" |--------|\n");

The output from the program fragment above is

|--------|DiceSum [ 12 ] => &2723354 | 16 | |--------|DiceSum [ 11 ] => &2723352 | 41 | |--------|DiceSum [ 10 ] => &2723350 | 58 | |--------|DiceSum [ 9 ] => &2723348 | 62 | |--------|DiceSum [ 8 ] => &2723346 | 83 | |--------|DiceSum [ 7 ] => &2723344 | 103 | |--------|DiceSum [ 6 ] => &2723342 | 70 | |--------|DiceSum [ 5 ] => &2723340 | 64 | |--------|DiceSum [ 4 ] => &2723338 | 50 | |--------|DiceSum [ 3 ] => &2723336 | 37 | |--------|DiceSum [ 2 ] => &2723334 | 16 | |--------|

Each compiler selects their preferred formula to simulate random distribution. Remember that the numbers generated by your random number function may be different than those generated in the examples above. If you have used the srand function to alter the seed of the random number generator, you can get different sets of numbers almost every time..

Example 7.4

Page 11: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [11]

The declaration

char Alpha [5];

will reserve five one-character components (1 byte each) , which can be depicted as

Each component is a character variable. The elements could be filled with assignment statements such as

Alpha [0] = 'G';Alpha [1] = 'O';Alpha [2] = 'O';Alpha [3] = 'D';Alpha [4] = '\0';

The last assignment statement above places the End-Of-String marker at the end of the string "GOOD". The End-Of-String marker has an ASCII value of 0. The End-Of-String marker is essential if the string is to be printed with a puts or a printf statement.

A character string array is the only array that can be printed all at once. Either of the following statements

puts (Alpha);printf ("%s",Alpha);

will print

Good

In order to store the End-Of-String marker, the programmer will declare the character array at least one larger than the actual number of characters. The character array can be declared and initialized with

charAlpha [5] = {'G','O','O','D','\0'};

The last significant character in a character string will generally be the End-Of-String marker; this End-Of-String marker has an ASCII value of 0. Character string declarations, like all others, contain unknown garbage when declared. When Name is declared to be a ten-character string,

charName [10];

it's contents might look like

Functions puts and printf will start with Name[0] and continue printing characters until an end-of-string marker (ASCII 0) is found.

printf ("#%s#\n", Name);

Page 12: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [12]

would print

#DA a1=*([H...#

The three dots (. . .) in the printout above represent the unknown information that would be printed in the search for an end-of-string marker. When strcpy is ued to place the name "SUE" in the string

strcpy (Name, "SUE");

the contents would look like

When functions puts and printf will start with Name[0] and continue printing characters until an end-of-string marker (ASCII 0) is found, they terminate the string printing with Name[3]. The output from

printf ("#%s#\n", Name);

would print

#SUE#

Be sure to include the library <string.h> when using strcpy.The computer scientist must make sure that the character array has been

declared large enough to hold the desired string plus the End-Of-String marker. The strcpy function does not check the string length; it can destroy the contents of other memory if the array (Alpha) is not declared large enough; this error can also cause a system crash. See section 7.6 for more information about character string arrays.

Example 7.5The declaration

char Alphabet [27];

will reserve twenty-seven character components (1 byte each) . Let us fill the elements could be filled with the capital letters of our alphabet. Although they could be filled one at a time (as in Example 7.5), it is more efficient to fill them with a loop. Among the solutions would be

for (Index = 0; Index < 26; Index ++)Alphabet [Index] = Index + 65;

Alphabet [26] = 0; /* Insert EOS Marker */

or

Letter = 'A';for (Index = 0; Index < 26; Index ++)Alphabet [Index] = Letter++;

Alphabet [26] = 0; /* Insert EOS Marker */

The call to puts

puts (Alphabet);

Page 13: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [13]

would print

ABCDEFGHIJKLMNOPQRSTUVWXYZExample 7.6

Let us fill a ten-component boolean array with alternating True/False values. The declaration

# define MAX_FLAGS 10boolean Flag [MAX_FLAGS];

will reserve ten boolean components. If the boolean data type is created with the typedef statement, True and False are integer constants with 1 and 0 respectively associated. If these contants were short integers, they would be at least one byte in size. If these constants were integers, they would be at least two bytes in size. One of your responsibilities is to find out the size of boolean array Flag. Hint : Use sizeof!

We offer three possible solutions to the task at hand..

Flag [0] = True;Flag [1] = False;Flag [2] = True;Flag [3] = False;Flag [4] = True;Flag [5] = False;Flag [6] = True;Flag [7] = False;Flag [8] = True;Flag [9] = False;

or

for (Index = 0; Index < MAX_FLAGS; Index += 2){Flag [Index] = True;Flag [Index + 1] = False;

}

or

for (Index = 0; Index < MAX_FLAGS; Index += 2)Flag [Index] = True;

for (Index = 1; Index < MAX_FLAGS; Index += 2)Flag [Index] = True;

Exercises 7.11. Using descriptive names, and declare an array variable for each of the

following:

a. A list of 35 test scoresb. The prices of 20 automobilesc. The answers to 50 True or False questionsd. A list of letter grades for the classes you are taking this semester

2. Write a test program in which you declare an array of three components, read real values into each component, sum the components, and print out the sum and value of each component.

Page 14: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [14]

3. Find all errors in the following declarations of array variables.

a. intTime (20)

b. intScores [5];

c. booleanFlag[10] = True, False, True, False, True, False,

True, False, True, False;

d. intScores [5] = 3,4,2,1,6;

e. intNos [5] = {5,4,3,2,1,0};

f. floatData [4] = {3.5 4.2 7.6 8.1};

g. booleanAnswer [10] = {True, False, True, False, True, False,

True, False};4. Assume the array A is declared as

int A[8];

Write a segment of code to initialize all components to zero without a loop.

5. Assume the array A is declared as

int B[418];

Write a segment of code that uses a loop to initialize all components to zero.

6. Assume the array A is declared as

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

Write a segment of code to display the contents of all of the components without a loop.

7. Assume the array A is declared as

int C[50];for (I = 0; I < 50; I ++)C[I] = 50 - I;

Write a segment of code to display the contents of all of the components without a loop.

Page 15: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [15]

8. Assume the address assigned to Info (by the memory manager) is 235760. What output is generated from

#define MAX_INFO 5intIndex,Info [MAX_INFO] = {3,4,2,1,6};

for (Index = MAX_INFO-1; Index >= 0; Index --){

printf (" |--------|\n"); printf ("Info [ %2i ] => &%lu | %3i |\n",

Index, &Info[Index],Info [Index]);}

printf (" |--------|\n");printf ("sizeof(Info) = %ld\n", sizeof(Info));

9. Assume the address assigned to Info (by the memory manager) is 670100. What output is generated from

#define MAX_RATES 4intIndex;

floatTaxRates [MAX_RATES] = {.075, .22, 31.5, 6.33};

for (Index = MAX_RATES-1; Index >= 0; Index --){

printf (" |-----------|\n"); printf ("TaxRates [ %2i ] => &%lu | %6.3f |\n",

Index, &TaxRates[Index], TaxRates[Index]);}

printf (" |-----------|\n");printf ("sizeof(TaxRates) = %ld\n", sizeof(TaxRates));

10. Assume the address assigned to Characters (by the memory manager) is 750500. What output is generated from

#define MAX_CHARS 14intIndex;

charCharacters [MAX_CHARS];

for (Index = 0; Index < MAX_CHARS; Index ++)if (Index % 2 == 0)Characters[Index] = Index + 65;

elseCharacters[Index] = 32;

for (Index = MAX_CHARS-1; Index >= 0; Index --){

printf (" |-----------|\n"); printf ("Characters [ %2i ] => &%lu | %6c |\n",

Index, &Characters[Index], Characters[Index]);}

printf (" |-----------|\n");

Page 16: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [16]

printf ("sizeof(Characters) = %ld\n", sizeof(Characters));

11. Assume the address assigned to Flag (by the memory manager) is 820500. What output is generated from

#define False 0#define True 1typedef int boolean;

#define MAX_FLAGS 12intIndex;

booleanFlag [MAX_FLAGS];

for (Index = 0; Index < MAX_FLAGS; Index +=4){Flag[Index] = True;Flag[Index+1] = False;Flag[Index+2] = !True;Flag[Index+3] = !False;

}

for (Index = MAX_FLAGS-1; Index >= 0; Index --){

printf (" |-----------|\n"); printf ("Flag [ %2i ] => %lu | %6i |\n",

Index, &Flag[Index], Flag[Index]);}

printf (" |-----------|\n");printf ("sizeof(Flag) = %ld\n", sizeof(Flag));

}

12. Let the array Money be declared by

floatMoney[3] = {19.26, 10.04, 17.32};

Assuming Money contains the values initialized (above) before each segment is executed, indicate what the array would contain after each section of code.

a. Temp = 173.21;X = Temp + Money[2];Money[1] = X;

b. if ( Money[2] < Money[1]) { Temp = Money[2]; Money[2] = Money[1]; Money[1] = Temp }

c. Money[3] = 20 – Money[3];

d. for (Index = 0; Index < 3; Index ++)

Page 17: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [17]

Money[Index] = Money[Index++] + 4.1;

A NOTE OF INTEREST Monolithic Idea: Invention of the Integrated Circuit

One of the most significant breakthroughs in the history of technology occurred in the late 1950s. Prior to 1958, computer circuitry was limited because transistors, diodes, resistors and capacitors were separate units that had to be wired together and soldered by hand. Although designers could design intricate computer super circuits using 500,000 transistors, they were almost impossible to build because of the extensive handwork involved. For example, a circuit with 100,000 components could require over 1,000,000 soldered connections. It was virtually impossible to assemble that many components without human error. Thus, the electronics industry was faced with an apparently insurmountable limit.

About this time, Jack St. Clair Kilby developed what has come to be known as the Monolithic Idea. He decided you could put the components of an entire circuit in a monolithic block of silicon. The idea, together with Robert Noyce's work on interconnecting circuits, allowed electronics engineers to overcome the obstacle presented by separate components. Kilby and Noyce's work resulted in the integrated circuit, the most important new product in the history of electronics. For their efforts, both men were awarded the National Medal of Science.

7.2InteractivelyFilling an Array

Filling Arrays With Scanf

Example 7.7Let us interactively place an unknown number of exam scores into an integer

array called Scores; we wish to place the first score in cell 1, the second score in cell 2, etc. The maximum number of exam scores shall be 200. Report the High Score, the Low Score, and the Average. Use a sentinel of –999. Valid exam scores are 1-100. This example shall use the GetInteger1 function written in chapter 6.

# define MAX_SCORES 200# define False 0# define True !False

intIndex,TempNo,Low,High,Sum,ActNoScores = 0,Scores[MAX_SCORES+1];

floatAverage;

booleanValidNo;

ActNoScores is a counter representing the actual number of valid scores that have been successfully placed into the array. The following program fragment will use GetInteger1 to place values directly into integer array Scores, Array Overflow is an attempt to place too much information into the array structure; note the care taken to prevent the array overflow.

/* Fill Scores from keyboard */do{ValidNo = GetInteger1 ("Enter Exam Score",&TempNo,0,100,

Page 18: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [18]

-999);if (ValidNo){ActNoScores++;Scores[ActNoScores]= TempNo;

}}

while ((ValidNo) && (ActNoScores < MAX_SCORES));

The following program fragment will place the lowest number in an array (containing at least one element) into integer variable Low.

Low = Scores[1];for (Index = 2; Index <= ActNoScores; Index++)if (Scores[Index] < Low)Low = Scores[Index];

The following program fragment will place the highest number in an array (containing at least one element) into integer variable High.

High = Scores[2];for (Index = 2; Index <= ActNoScores; Index++)if (Scores[Index] > High)High = Scores[Index];

The following program fragment will place the average of the numbers in an array (containing at least one element) into float variable average.

Sum = 0;for (Index = 1; Index <= ActNoScores; Index++)Sum = Sum + Scores[Index];

Average = (float) Sum/ActNoScores;

The following program fragment could be used to display all relative information.

printf ("\nLow = %d High = %d Average = %f\n",Low, High, Average);

for (Index = ActNoScores; Index >= 1; Index --){

printf (" |--------|\n");printf ("Scores [ %2d ] => &%lu | %3d |\n",Index,

&Scores[Index],Scores[Index]);}

printf (" |--------|\n");printf ("ActNoScores = %d\n",ActNoScores);

The output for the program fragments above might be

Enter Exam Score <-999 - to Quit> : 83Enter Exam Score <-999 - to Quit> : 92Enter Exam Score <-999 - to Quit> : 88Enter Exam Score <-999 - to Quit> : 200***ERROR*** Invalid Number - Try Again!

Enter Exam Score <-999 - to Quit> : 100Enter Exam Score <-999 - to Quit> : 95

Page 19: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [19]

Enter Exam Score <-999 - to Quit> : -999

Low = 83 High = 100 Average = 91.599998

|--------|Scores [ 5 ] => &3841700 | 95 | |--------|Scores [ 4 ] => &3841698 | 100 | |--------|Scores [ 3 ] => &3841696 | 88 | |--------|Scores [ 2 ] => &3841694 | 92 | |--------|Scores [ 1 ] => &3841692 | 83 | |--------|ActNoScores = 5

As is often the case, there are many ways to solve a problem. Another solution to the problem is to initialize Sum, Average, High, and Low in the declaration and replace the first four loops above with the following:

do{ValidNo = GetInteger1 ("Enter Exam Score",&TempNo,0,100,

-999);if (ValidNo){ActNoScores++;Scores[ActNoScores]= TempNo;if (Scores[ActNoScores] < Low)Low = Scores[ActNoScores];

if (Scores[ActNoScores] > High)High = Scores[ActNoScores];

Sum = Sum + Scores[ActNoScores];}

}while ((ValidNo) && (ActNoScores < MAX_SCORES));Average = (float) Sum/ActNoScores;

This solution to the exam scores problem does not effectively use Scores[0], but the solution above is quite readable and logical. Note that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages such as Fortran and BASIC, this technique is often used to bundle the actual number counter within the array; structured languages, such as C, pascal, and PL/1, have more convenient bundling techniques (chapter 10).

Exercises 7.21. What is meant by array overflow?

2. Assume the array List is declared asintList [5] = {3,4,2,1,6};

and that all other variables have been appropriately declared. Label the following as valid or invalid; consider all subscript errors invalid. Include an explanation for any that are invalid.

a. scanf ("%d",&List(3));

Page 20: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [20]

b. scanf ("%d",List);c. A = List[3] – List[4];d. List[3] ++;e. List[3] += List[4];f. rintf ("%d%d%d%d%d",List);g. printf ("%d",List);h. List[10] = 3;i. Max = List[5];j. Average = (List[1] – List[8]) * 2;k. printf ("%d%d%d%d",List[25, 50, 75, 100]);l. for ( J = 1; J <= 5; J++)

GetInteger1 ("Enter No", &List[J], 1, 10,-999);m. if (List[3] = 10)

GetInteger1 ("Enter No", &List[3], 1, 10,-999);n. Scores[47] = 92;o. List[40] = List[41] / 2;m. if (List[3] == 122)

GetFloat1 ("Enter No", &List[3], 1.5, 8.5,-999);

3. Assume the following array declarations.

int List[5], Score [5];boolean Answer[10];char Name[20];

Indicate the contents of the arrays after each segment of code.

a. for ( J = 0; J <= 4; J++) List[J] = J / 3;

b. for ( J = 2; J <= 6; J++) { List[J–1] = J – 3; Score[J=1] = List[J–1] / 3; }

c. for ( J = 0; J <= 9; J++) if (J % 2 == 0) Answer[J] = True; else Answer[J] = False;

d. for ( J = 0; J <= 19; J++) Name[J] = J + 64;

4. Write a demo program using the code fragment below to

a. display all relevant memory in a form similar to that of Example 7.8b. assign 65 to Test[–1]c. display all relevant memory in a form similar to that of Example 7.8d. assign 65 to Test[6]e. display all relevant memory in a form similar to that of Example 7.8

# define MAX 6

Page 21: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [21]

charA = 'a',B = 'b',C = 'c';

intTest [MAX] = {0,1,2,3,4,5};

charD = 'd',E = 'e',F = 'f';

5. Let the array Best be declared by

intBest[30];

and assume that test scores have been read into Best. What does the following section of code do?

Count = 0;for (J = 1; J < 30; J++) if Best[J] > 90 Count = Count + 1;

6. Write a short program to

a. Fill an array with 1000 random test scores in the range 45 – 100.b. Display the number of As - [90 - 100].c. Display the number of Bs - [80 - 89.d. Display the number of Cs - [70 - 79].e. Display the number of Ds - [60 - 69].f. Display the number of Fs - [0 - 59].g. Display the High Score.h. Display the Low Score.

7. An teacher needs some statistical information about a recent exam (No more than 200 students). Write a short program which will

a. Interactively solicit the instructor for the number of exams and the corresponding number of valid (0-100) exam scores (Use GetAnInteger)

b. Display the number of As - [90 - 100].c. Display the number of Bs - [80 - 89.d. Display the number of Cs - [70 - 79].e. Display the number of Ds - [60 - 69].f. Display the number of Fs - [0 - 59].g. Display the High Score.h. Display the Low Score.

Test your program with the following set (25) of scores: 98 78 65 40 99 77 85 102 66 92 33 50 100 33 79 99 77 85 102 66 92 33 65 40 99

8. Let the array N be declared as

char String [10]= {'J','0','H','N',' ','S','M','I','T','H'};

Page 22: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [22]

What output is produced by the following?

a. for (J = 0; J < 10; J++ ) printf ("%c",N[J]);

b. for (J = 0; J < 5; J++ )printf ("%c",N[J+5]);

printf ("\n");for (J = 0; J < 5; J++ )

printf ("%c",N[J]);

c. for (J = 9; J >=0; J-- ) printf ("%c\n",N[J]);

7.3Sorting

Alphabetizing lists and ordering numerical data is absolutely essential in today's world of high volume. Think of the problems you would encounter looking up a friend's phone number in the Chicago phone book if there were no order to the names.

A significant portion of all computer time is still spent sorting. There are more than thirty different sorting algorithims; we will examine only a few in this text. Some of these algorithms are very easy to code and understand; others are quite complicated. Each sort has it's own strengths and weaknesses; there is no one sort that is best for all situations. This section will introduce the selection sort and implement it with numeric arrays. The selection sort is one of the easier sorts to understand and implement. It is certainly not the best sort for all types of data.

Chapter 11 will extend sorting to direct-access record files. Sorting files can literally take days. Chapter 12 will examine some of the theory of sorting. This section presents the first, of many, opportunities to order data.

Selection Sort

In order to sort and search arrays, it is essential to have some actual counter which tells the actual number of valid items to process. Let us consider array A that contains 25 in the first component and 12 in the second component. One could fill the array from index zero and represent the array as follows:

Unfortunately all loops would have to go from

for (Index = 0; Index < ActNo; Index++)

The fact that the ActNo counter (2) is not the subscript of the last filled element in A would make the sorts and searches a bit more difficult to understand. Throughout the remainder of the chapter we shall declare our arrays like

# define MAX 10

int A[MAX+1];

and shall begin filling and searching our arrays at component 1.

Page 23: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [23]

As previously mentioned, the actual number of valid elements in an array can be stored in the index[0] component of the array. To illustrate, we could declare array A with

# define MAX 10# define ACT_NO 0int A[MAX+1];

and initialize it with

A[ACT_NO] = 0; /* To Initialize the Actual Number Counter */

In order to add items, the actual number has to be incremented and the new item has to be inserted at index actual number of the array. The numbers 25 and 12 may be placed into the array with

A[++A[ACT_NO]] = 25; /* To Insert 25 into component 1 */A[++A[ACT_NO]] = 12; /* To Insert 12 into component 2 */

to produce

Problem 18 (chapter 5) illustrates how difficult it is to sort just five numbers without the array structure. It is significantly more difficult to sort thousands of items. Let us begin the selection sort.

Suppose we have an array A of five integers that we wish to sort from smallest to largest. The values currently in A are as depicted on the left; we wish to end up with values as on the right.

The basic algorithm of a selection sort is

1. Find the smallest number in the array and exchange it with A[1].2. Find the smallest number among A[2] through A[5] and exchange it with A[2].3. Continue this process until the array is sorted.

The second, third, and fourth steps produce

Notice that in the second step, since the second smallest number was already in place, we do not exchange anything. Before writing the algorithm for this sorting function, note the following:

1. If the array A is of length N, we need N – 1 steps.2. We must be able to find the smallest number.3. We need to exchange appropriate array components.

If two or more values in the list are equal, an exchange would not be made when finding the smallest number. Thus, rather than find the smallest numbers, we must be able to find one of the remaining smallest numbers.

Page 24: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [24]

When the code is written for this sort, note that strict inequality (<) rather than weak inequality (<=) is used when looking for the smallest remaining value. The algorithm to sort by selection is

1. for (J =1 ; J <= N – 1; J++)1.1 find the smallest value among A[J], A[J+1], ... A[N]1.2 store the index of the smallest value in Index1.3 exchange the values of A[J] and A[Index]

We wish to find the index of the smallest value of array A. With suitable changes, we will incorporate this in the segment of code for a selection sort.

Index = 1;for (J = 2; J <= N; J++ ) if ( A[J] < A[Index] ) Index = J;

Let A be an array of length N and assume all variables have been appropriately declared. Then the following will sort A from low to high.

for (J = 1; J <= N–1; J++ ) /* Find the minimum N–1 times */ { Index = J; for (K = J + 1; K <= N; K++ ) if (A[K] < A[Index]) Index = K; /* Find index of smallest number */ Temp = A[Index]; A[Index] = A[J]; /* Exchange smallest number */ A[J] = Temp; } /* End of one pass */

Let us now partially trace this sort for the five integers in the array we sorted in the beginning of this section.

Array A ===> 6 4 8 10 1

Outer loop : (J = 1; J <= 4; J++ ) Index = J = 1Inner loop : (K = 2; K <= 5; K++ )

N Index K A[K] A[Index] A[K] < A[Index] J- ----- - ---- -------- --------------- -

Pass 1 5 1 2 4 6 True 1Pass 2 5 2 3 8 4 False 1Pass 3 5 2 4 10 4 False 1Pass 4 5 2 5 1 4 True 1End 5 5

The statements

Temp = A[Index];A[Index] = A[J];A[J] = Temp;

produce the completely sorted array

Array A ===> 1 4 8 10 6

Index = J = 2Inner loop : (K = 3; K <= 5; K++ )

Page 25: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [25]

N Index K A[K] A[Index] A[K] < A[Index] J- ----- - ---- -------- --------------- -

Pass 1 5 2 3 8 4 False 2Pass 2 5 2 4 10 4 False 2Pass 3 5 2 5 6 4 False 2End 5 2

The statements

Temp = A[Index];A[Index] = A[J];A[J] = Temp;

produce the completely sorted array

Array A ===> 1 4 8 10 6

Index = J = 3Inner loop : (K = 4; K <= 5; K++ )

N Index K A[K] A[Index] A[K] < A[Index] J- ----- - ---- -------- --------------- -

Pass 1 5 3 4 10 8 False 3Pass 2 5 3 5 6 8 True 3End 5 5

The statements

Temp = A[Index];A[Index] = A[J];A[J] = Temp;

produce the completely sorted array

Array A ===> 1 4 6 10 8

Index = J = 4Inner loop : (K = 5; K <= 5; K++ )

N Index K A[K] A[Index] A[K] < A[Index] J- ----- - ---- -------- --------------- -

Pass 2 5 4 5 8 10 True 4End 5 5

The statements

Temp = A[Index];A[Index] = A[J];A[J] = Temp;

produce the completely sorted array

Array A ===> 1 4 6 8 10

A NOTE OF INTEREST Transition to a Computer System

Many individuals and businesses acquire a computer to take over some aspect of their lives or their activities. They "computerize" something. And as soon as the computer is up and running, they abandon--often irrevocably abandon--the old technology, the old method.

Don't.I believe that it is absolutely essential not only to keep the technology of the old method as

long as possible--but actually to continue using the old method, alongside the new--for a minimum of three months.

Page 26: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [26]

As soon as the computer does its first little thing correctly, there is an overwhelming, almost irresistible tendency to embrace it totally, to switch everything over onto the computer as quickly as possible.

Untold grief has been experienced by individuals and businesses that have fallen into this trap. The new computer works wonderfully for a few hours, a few days, even a few weeks. So out with the old horse–and–buggy methods and machinery. Throw out the kerosene lamps when the electric power arrives (and break your neck stumbling in the dark with the first power failure). Dispose of your wind–up watch when you get your digital model (and find yourself trying to meet a tight schedule in a distant city when your battery dies and you can't find a store that sells your size). Put all your addresses and phone numbers into a home record–keeping program, and toss out your dog–eared address book. (And then here comes Christmas, and you can't find your main disk, and your back–up disk was sitting on the refrigerator and got erased by magnetism).

Keeping the old and the new going side by side can be trivial in some cases--storing the kerosene lamps, keeping a wind–up watch in your luggage, hanging onto the old address book--or it can be extremely complicated and expensive. Even when it is the latter, it is still well worth doing.To paraphrase Pascal talking about belief in God, if you do keep the back–up system going and never need it, you've spent a little extra time and money, but haven't really suffered. But if you don't keep the old system going, and you do need it, you're in big, big trouble.

Example 7.8Our concluding example

1. Inputs real numbers from keyboard.2. Echo prints the numbers in a column of width six with two places to the

right of the decimal.3. Sorts the array from low to high.4. Prints the sorted array using the same output format.

An expanded pseudocode development for this is

1. Print header--prints a suitable explanation of the program and includes a heading for the unsorted list

2. Get data (echo print)-uses a for loop to read the data and print it in the same order in which it is read

3. Sort list-uses the selection sort to sort the array from low to high4. Output sorted list-uses a for loop to output the sorted list

PROGRAMSortFloat.c

/********************************************************************************* Program: SortFloat.c **** Purpose: This program illustrates the use of a selection sorting **** with an array of float. Output includes data in both an **** unsorted and a sorted list. The data are formatted and **** numbered to enhance readability. **** Modules Required: ClearScreen, PrintHeading, GetFloat1 *********************************************************************************/# include <stdio.h># include <console.h># define True 1# define False 0# define SUCCESSFUL 1# define UNSUCCESSFUL 0# define LIST_MAX 20

Page 27: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [27]

typedef int boolean;void ClearScreen(void);boolean GetFloat1 (char Prompt[], float * Newfloat, float Low, float High, float Sentinel);void PrintHeading(void);

main (){floatTempFloat,List[LIST_MAX+1];

intActNoItems,Index,IndexSmallestNo, Pass, Subscript;

booleanDone;

charPrompt [20];

PrintHeading();

/* Fill the Array from Keyboard */ActNoItems = 0;do{ /* sprintf - print to string - fills Prompt with Enter List [1] */sprintf (Prompt,"Enter List [%d]",ActNoItems+1); if (GetFloat1 (Prompt, &List[ActNoItems+1], 0, 50000, -1) )ActNoItems++;

elseDone = True;

}while ((ActNoItems < LIST_MAX) && (!Done));

/* Display the UnSorted Array */printf ("\nThe unsorted list is as follows:\n\n");for (Index = ActNoItems; Index >= 1; Index-- )printf ("List[%2i] = %8.3f\n",Index,List[Index]);

/* Selection Sort the Array */for (Pass = 1; Pass <= ActNoItems-1; Pass++ )

{IndexSmallestNo = Pass;for (Subscript = Pass + 1;Subscript <= ActNoItems;Subscript++)if (List[Subscript] < List[IndexSmallestNo]) IndexSmallestNo = Subscript; /* Find IndexSmallestNo */

TempFloat = List[IndexSmallestNo];List[IndexSmallestNo] = List[Pass]; /* Exchange SmallestNo */List[Pass] = TempFloat;

} /* Display the Sorted Array */

printf ("\nThe sorted list is as follows:\n\n");

Page 28: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [28]

for (Index = ActNoItems; Index >= 1; Index-- )printf ("List[%2i] = %8.3f\n",Index,List[Index]);

} /********************************************************************************* Purpose: Print a heading **** Modules Required: ClearScreen **** Headers Required: stdio.h **** Globals Required: None **** Defines Required: None *********************************************************************************/void PrintHeading(void){ClearScreen();printf (" This sample program does the following:\n\n");printf (" <1> Inputs reals from keyboard.\n");printf (" <2> Prints the unsorted list of data.\n");printf (" <3> Sorts the data from low to high.\n");printf (" <4> Prints the sorted list of data.\n\n");

}

This sample program does the following:

<1> Inputs reals from keyboard. <2> Prints the unsorted list of data. <3> Sorts the data from low to high. <4> Prints the sorted list of data.

Enter List [1] < -1.000000 to Exit> : 10Enter List [2] < -1.000000 to Exit> : 8Enter List [3] < -1.000000 to Exit> : 6Enter List [4] < -1.000000 to Exit> : 1Enter List [5] < -1.000000 to Exit> : 9Enter List [6] < -1.000000 to Exit> : 3Enter List [7] < -1.000000 to Exit> : 4Enter List [8] < -1.000000 to Exit> : -1

The unsorted list is as follows:

List[ 7] = 4.000List[ 6] = 3.000List[ 5] = 9.000List[ 4] = 1.000List[ 3] = 6.000List[ 2] = 8.000List[ 1] = 10.000

The sorted list is as follows:

List[ 7] = 10.000List[ 6] = 9.000List[ 5] = 8.000List[ 4] = 6.000List[ 3] = 4.000List[ 2] = 3.000List[ 1] = 1.000

Page 29: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [29]

Program Sortfloat.c does perform the tasks specified. The program could be improved greatly with better modularization. Modules such as SelectSortFloat and DisplayArrayFloat would be useful in other programs. This will be left as an exercise.

A NOTE OF INTEREST Sorting

The computers of the world spend a great deal of their time sorting business records of one kind or another. Sorting involves putting things in order, whether by number, by date, or by some other kind of sort key. Sorting consumes computer resources.

The secret of implementing a successful sorting operation is to decide which resource--time, memory, disk space, programming effort--a system can spare, and which is limited; then to pick a sorting algorithm to strike an optimal balance of these factors. The selection sort presented in this chapter is just one of many algorithms. We will continue our study of sorting algorithms in Chapters 13.

Exercises 7.31. Assume the array Column is to be sorted from low to high using the selection sort.

a. Sketch the contents of the array after each of the first pass.b. Sketch the contents of the array after each of the second pass.c. Sketch the contents of the array after each of the third pass.d. How many passes are necessary to sort array Column?e. How many exchanges are made during the sort?

2. Write a test program that prints the partially sorted arrays after each pass during a selection sort. Run this program on array Column from problem # 1.

3. Change the code for the selection sort so it sorts an array in descending order (from high to low). Run this program on array Column from problem # 1.

4. Write a complete program toa. Read as many as 300 real numbers into an array from keyboard.b. If the first real number is positive in the array is positive, sort the array

from high to low; if it is negative, sort the array from low to high.c. Print the sorted array across the page in 8.2f format.

7.4Passing Arrays toFunctions

Array Indexing

Subprograms should be used with arrays to maintain the structured design philosophy. Before we look at specific examples, let us examine the method and syntax necessary for passing an array to a function. We have previously passed as pointers only those items that a subprogram is designed to change. Recall that when an item is passed by value, memory for a local copy of the parameter is created and filled to match the original argument; changes to this copy, either accidental or intentional, have no effect on the original argument.

Many languages, such as PL1 and Pascal, will pass the simple array structure either by value or by reference. Since arrays may consist of thousands of bytes,

Page 30: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [30]

the C language decided that it is not very efficient to allocate and fill large amounts of memory for the array data type. The array data type is passed to subprograms as a pointer.

In order to write generic utilities for the array concept, we shall form integer array sets that contain (1) the array, (2) the actual number of elements in the array at this instant in time, and (3) a maximum number of items that may be placed in this array. The code fragment below shall be used in the next few examples; refer to it as needed. The first array set is formed by Nos1, ActNo1, and MAX_NOS_1. The second array set is formed by Nos2, ActNo2, and MAX_NOS_2. The third array set is formed by Nos3, ActNo3, and MAX_NOS_3.

# include <stdio.h># include <stdlib.h>

# define MAX_NOS1 5# define MAX_NOS2 8# define MAX_NOS3 21

void ClearScreen(void);void HitReturnKeyToContinue(void);void DisplayIntegerArray (char ArrayTitle[], int Array[], int NoToDisplay, int ActNo, int Max);void QuickDisplay (int Array[], int NoToDisplay,int ActNo);void SelectionSort (int Array[], int ActNo);void FillArrayRandom100 (int Array[], int NoToFill, int *ActNo, int Max);int SumArray1 (int Array[], int ActNo);int SumArray2 (int Array[], int ActNo);

main (int argc, char * argv[]){intNos1[MAX_NOS1+1], ActNo1 = 0, Nos2[MAX_NOS2+1], ActNo2 = 0, Nos3[MAX_NOS3+1], ActNo3 = 0;

We are choosing not to use element 0 of the array at this time. We shall place first number placed into cell 1 of the array and adjust the ActNo to 1. We shall place second number placed into cell 2 of the array and adjust the ActNo to 2. We shall place third number placed into cell 3 of the array and adjust the ActNo to 3.

Observe that the three arrays are of different sizes; Nos1 has room for 5 elements and Nos2 s 8 elements and Nos3 contains 21 elements.

Note that ActNo1, ActNo2, and ActNo3 have been initialized to 0; each of the three arrays are empty at this instant in time. The test (ActNo == 0) can be used to determine if an array is empty. Since the array is defined with MAX + 1 elements, the test (ActNo == MAX) can be used to determine if an array is full and thus avoid array overflow. C does not initialize each array element to a specific value; the contents of the individual cells are unknown.

A memory map of main would look like :

Example 7.9Subprogram DisplayIntegerArray shall provide a graphical view of the

integer array set. If the NoToDisplay is greater than max or less than two, it shall be set equal to the max.

Page 31: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [31]

void DisplayIntegerArray (char ArrayTitle[], int Array[], int NoToDisplay, int ActNo, int Max){int Index;

if ((NoToDisplay > Max) || (NoToDisplay < 2) )NoToDisplay = Max;

ClearScreen();printf ("\nArray : %s => & %lu\n\n",ArrayTitle,Array);for (Index = NoToDisplay; Index >= 1; Index --){

if (Index == 2) {printf (" |--------|");printf (" |-------|\n");

printf ("%10s [ %2d ] => %lu | %6d | |%6d | Max\n", ArrayTitle,Index, &Array[Index], Array[Index], Max);

} else if (Index == 1)

{printf (" |--------|");printf (" |-------|\n");

printf ("%10s [ %2d ] => %lu | %6d | |%6d | ActNo\n", ArrayTitle,Index, &Array[Index], Array[Index], ActNo);

}else

{ printf (" |--------|\n"); printf ("%10s [ %2d ] => %lu | %6d |\n", ArrayTitle,Index, &Array[Index], Array[Index]); } }printf (" |--------|");printf (" |-------|\n");

HitReturnKeyToContinue();}

Let us examine the type of code that might be included in main (above) to test DisplayIntegerArray. In order to check the transfer of information to the subprogram, it is essential to place some known information into the array. Below, the first three cells of Nos1 have been filled with multiples of 5 and the first five cells of Nos2 have been filled with multiples of eleven. ActNo1 and ActNo2 have been properly adjusted.

Nos1[1] = 5;Nos1[2] = 10;Nos1[3] = 15;ActNo1 = 3;

Nos2[1] = 11;Nos2[2] = 22;Nos2[3] = 33;Nos2[4] = 44;Nos2[5] = 55;

Page 32: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [32]

ActNo2 = 5;

DisplayIntegerArray ("Nos1", Nos1, ActNo1, ActNo1, MAX_NOS1);DisplayIntegerArray ("Nos2", Nos2, ActNo2, ActNo2, MAX_NOS2);

DisplayIntegerArray ("Nos2", Nos2, 15, ActNo2, MAX_NOS2);DisplayIntegerArray ("Nos1", Nos1, 6, ActNo1, MAX_NOS1);DisplayIntegerArray ("Nos1", Nos1, 0, ActNo1, MAX_NOS1);DisplayIntegerArray ("Nos2", Nos2, 2, ActNo2, MAX_NOS2);

The output from the first call to DisplayIntegerArray, below, indicates that the Title, pointer to the array, ActNo, and Max has been properly transferred. Notice that the address indicator (&) was not placed on the integer array Nos1 in the function call.

Array : Nos1 => & 4382402 |--------| Nos1 [ 3 ] => 4382408 | 15 | |--------| |-------| Nos1 [ 2 ] => 4382406 | 10 | | 5 | Max |--------| |-------| Nos1 [ 1 ] => 4382404 | 5 | | 3 | ActNo |--------| |-------|

<Hit Return Key To Continue>

The second call to function DisplayIntegerArray indicates tells us that the subprogram is successful in displaying arrays of different sizes. See below.

Array : Nos2 => & 4382382 |--------| Nos2 [ 5 ] => 4382392 | 55 | |--------| Nos2 [ 4 ] => 4382390 | 44 | |--------| Nos2 [ 3 ] => 4382388 | 33 | |--------| |-------| Nos2 [ 2 ] => 4382386 | 22 | | 8 | Max |--------| |-------| Nos2 [ 1 ] => 4382384 | 11 | | 5 | ActNo |--------| |-------|

<Hit Return Key To Continue>

The third call to function DisplayIntegerArray indicates illustrates the unknown garbage data in cells 6,7, and 8; we did not place information in these cells. This call also tested to make sure that the display never displays more that the Max (8) elements even if the programmer makes a mistake and requests 15. The following output is generated from the second call to this display function. See below.

Array : Nos2 => & 4382382

|--------| Nos2 [ 8 ] => 4382398 | 12216 | |--------|

Page 33: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [33]

Nos2 [ 7 ] => 4382396 | -3211 | |--------| Nos2 [ 6 ] => 4382394 | -22114 | |--------| Nos2 [ 5 ] => 4382392 | 55 | |--------| Nos2 [ 4 ] => 4382390 | 44 | |--------| Nos2 [ 3 ] => 4382388 | 33 | |--------| |-------| Nos2 [ 2 ] => 4382386 | 22 | | 8 | Max |--------| |-------| Nos2 [ 1 ] => 4382384 | 11 | | 5 | ActNo |--------| |-------|

<Hit Return Key To Continue>

Function DisplayIntegerArray is generic. It may be used to the key components of any integer array set. It could be used for an array set involving an array of Bowling Scores, a one dimensional matrix from mathematics, an array of Exam Scores, a Vector from Physics or engineering, an array of random numbers, etc. This subprogram will be quite helpful to computer scientists during the testing phase of a program.

Example 7.10Subprogram QuickDisplay generates a list of integers in the array. The

integers are separated by a space. It is possible to display forty or more numbers on a single line. This is sometimes more desirable than the dump.

void QuickDisplay (int Array[], int NoToDisplay,int ActNo){intIndex;

charTempString[25];

if ((NoToDisplay > ActNo) || (NoToDisplay <= 0))NoToDisplay = ActNo;

for (Index = 1; Index <= NoToDisplay; Index ++){

printf ("%6d ",Array[Index]); if ( Index % 10 == 0) /* Skip a line if Index Mod 10 == 0 */ printf ("\n"); }

printf ("\n\n");}

The following code, placed in the main,

for (ActNo1 = 0; ActNo1 < 3; )Nos1[ActNo1] = ++ActNo1 * 5;

for (ActNo2 = 0; ActNo2 < 5; )Nos2[ActNo2] = ++ActNo2 * 11;

for (ActNo3 = 0; ActNo3 < 21; )Nos3[ActNo3] = ++ActNo3 * 1;

QuickDisplay (Nos1, ActNo1, ActNo1);

Page 34: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [34]

QuickDisplay (Nos2, ActNo2, ActNo2);QuickDisplay (Nos3, ActNo3, ActNo3);

generates the following output:

5 10 15

11 22 33 44 55

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

Example 7.11Neither of the previous two subprograms altered the data in the original

array. The purpose of subprogram FillArrayRandom100 is to place random integers (1-100) into elements 1,2,3,...,NoToFill of the array. The MAX is passed into this function to make sure that there is no array overflow. The ActNo must be adjusted to reflect the contents of the array.

void FillArrayRandom100 (int Array[], int NoToFill, int *ActNo, int Max){intIndex;

if ((NoToFill > Max) || (NoToFill <= 0))NoToFill = Max;

for (Index = 1 ; Index<= NoToFill; Index++)Array[Index] = (int) rand() /32767.1 * 100 + 1;

*(ActNo) = NoToFill;}

In order to test the FillArrayRandom100 subprogram, one might include the following code into main.

FillArrayRandom100 (Nos1, 25, &ActNo1,MAX_NOS1);QuickDisplay (Nos1, ActNo1, ActNo1);

FillArrayRandom100 (Nos2, -25, &ActNo2,MAX_NOS2);QuickDisplay (Nos2, ActNo2, ActNo2);

FillArrayRandom100 (Nos3, 5, &ActNo3,MAX_NOS3);QuickDisplay (Nos3, ActNo3, ActNo3);

FillArrayRandom100 (Nos3, 15, &ActNo3,MAX_NOS3);QuickDisplay (Nos3, ActNo3, ActNo3);

FillArrayRandom100 (Nos3, MAX_NOS3, &ActNo3,MAX_NOS3);QuickDisplay (Nos3, ActNo3, ActNo3);

The following output indicates that the overflow test in function FillArrayRandom100 is working, but does little to assure that random numbers are in the range 1-100 because there is such a small population of data. One should also test this module with a much larger array.

52 18 31 54 95

Page 35: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [35]

18 71 23 50 13 9 39 28

37 99 54 77 65

77 79 83 16 63 32 35 92 52 41 61 79 94 87 87

68 76 59 39 36 21 83 42 47 98 13 22 96 74 41 79 76 96 3 32 76

The test data above indicates that the FillArrayRandom100 works with at least two different sized integer arrays.

Example 7.12Subprogram SelectionSort uses sorts the array with the same logic found in

program SortFloat.c. Placing the generic code into a module makes it possible to sort a variety of different sized one dimensional integer arrays with a single function.

void SelectionSort (int Array[], int ActNo){

intIndexSmallestNo,TempInt, Pass, Subscript;

for (Pass = 1; Pass <= ActNo-1; Pass++ )

{IndexSmallestNo = Pass;for (Subscript = Pass + 1;Subscript <= ActNo;Subscript++)if (Array[Subscript] < Array[IndexSmallestNo]) IndexSmallestNo = Subscript;

TempInt = Array[IndexSmallestNo];Array[IndexSmallestNo] = Array[Pass]; Array[Pass] = TempInt;

} }

When the following code

FillArrayRandom100 (Nos1, 4, &ActNo1,MAX_NOS1);QuickDisplay (Nos1, ActNo1, ActNo1);SelectionSort (Nos1, ActNo1);QuickDisplay (Nos1, ActNo1, ActNo1);

FillArrayRandom100 (Nos2, -5, &ActNo2,MAX_NOS2);QuickDisplay (Nos2, ActNo2, ActNo2);SelectionSort (Nos2, ActNo2);QuickDisplay (Nos2, ActNo2, ActNo2);

FillArrayRandom100 (Nos3, 25, &ActNo3,MAX_NOS3);QuickDisplay (Nos3, ActNo3, ActNo3);

Page 36: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [36]

SelectionSort (Nos3, ActNo3);QuickDisplay (Nos3, ActNo3, ActNo3);

is placed into the main function to test SelectSort, the output might appear as follows:

52 18 31 54

18 31 52 54

95 18 71 23 50 13 9 39

9 13 18 23 39 50 71 95

28 37 99 54 77 65 77 79 83 16 63 32 35 92 52 41 61 79 94 87 87

16 28 32 35 37 41 52 54 61 63 65 77 77 79 79 83 87 87 92 94 99

The test data above indicates that the sort will work correctly on different sized arrays.

Example 7.13Function SumArray1 explicitly returns the sum of all elements 1+2+3+...

+ActNo. A message is printed and zero returned for an empty array.

int SumArray1 (int Array[], int ActNo){intSubscript,Sum = 0;

if (ActNo <= 0 )printf ("\n The Array is Empty in Function SumArray1 \n");

for (Subscript = 1; Subscript <= ActNo; Subscript++)Sum = Sum + Array[Subscript];

return (Sum);}

When the following code

ActNo2 = 0;printf ("The Sum1 = %d\n\n",SumArray1(Nos2,ActNo2));

FillArrayRandom100 (Nos2, 3, &ActNo2,MAX_NOS2);QuickDisplay (Nos2, ActNo2, ActNo2);printf ("The Sum1 = %d\n\n",SumArray1(Nos2,ActNo2));

FillArrayRandom100 (Nos2, 1, &ActNo2,MAX_NOS2);QuickDisplay (Nos2, ActNo2, ActNo2);TempInt = SumArray1(Nos2,ActNo2);printf ("The Sum1 = %d\n\n",TempInt);

FillArrayRandom100 (Nos3, 13, &ActNo3,MAX_NOS3);QuickDisplay (Nos3, ActNo3, ActNo3);

Page 37: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [37]

printf ("The Sum1 = %d\n\n",SumArray1(Nos3,ActNo3));

is placed into the main function to test SelectSort, the output might appear as follows:

The Array is Empty in Function SumArray1The Sum1 = 0

52 18 31

The Sum1 = 101

54

The Sum1 = 54

95 18 71 23 50 13 9 39 28 37 99 54 77

The Sum1 = 613

The test data above indicates that the sum function will work correctly on at least two different sized arrays. The testing includes arrays that contain 0, 1, and Max.

Pointer Arithmetic

Pointer Arithmetic allow pointers to be incremented or decremented. Let us assume that the value stored in an integer pointer Ptr is &2753456. One form of pointer arithmetic is pointer incrementation (Ptr++); pointer incrementation increments the address stored in the pointer by the sizeof the data type. An integer is two bytes.

intPtr;

Ptr++;

Ptr++;

Another form of pointer arithmetic is pointer decrementation (Ptr--); pointer decrementation decrements the address stored in the pointer by the sizeof the data type. An float is four bytes.

floatPtr;

Ptr––;

Ptr––; Example 7.14

All of the previous subprograms have used array indexing to work with the individual cells within an array. Function SumArray2 uses pointer arithmetic to explicitly return the sum of all elements.

Page 38: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [38]

A message is printed and zero returned for an empty array. In Function SumArray2, the address of element 1 of the array is passed to the function. Within the function, the pointer will be incremented to calculate the sum.

int SumArray2 (int *Ptr, int ActNo){intCounter,Sum = 0;

if (ActNo <= 0 )printf ("\n The Array is Empty in Function SumArray2 \n");

for (Counter = 1; Counter <= ActNo; Counter++){Sum = Sum + (*Ptr);Ptr++;

}return (Sum);

}

When the following code

ActNo2 = 0;printf ("The Sum2 = %d\n\n",SumArray2(&Nos2[1],ActNo2));

FillArrayRandom100 (Nos2, 3, &ActNo2,MAX_NOS2);QuickDisplay (Nos2, ActNo2, ActNo2);printf ("The Sum2 = %d\n\n",SumArray2(&Nos2[1],ActNo2));

FillArrayRandom100 (Nos2, 1, &ActNo2,MAX_NOS2);QuickDisplay (Nos2, ActNo2, ActNo2);TempInt = SumArray2(&Nos2[1],ActNo2);printf ("The Sum2 = %d\n\n",TempInt);

FillArrayRandom100 (Nos3, 13, &ActNo3,MAX_NOS3);QuickDisplay (Nos3, ActNo3, ActNo3);printf ("The Sum2 = %d\n\n",SumArray2(&Nos3[1],ActNo3));

is placed into the main function to test SumArray2 the output might appear as follows:

The Array is Empty in Function SumArray2The Sum2 = 0

31 54 95

The Sum2 = 180

18

The Sum2 = 18

71 23 50 13 9 39 28 37 99 54 77 65

The Sum2 = 565

Page 39: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [39]

If one wanted to include element 0 in the sum, the function call would simply pass &Nos3[0]. Let us examine the logic behind SumArray2 more in depth. FillArrayRandom100 has placed three random numbers into Nos2

-------------------------------------------------------------------------------------------------------------------

-------------------

--------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------

-------------------

--------------------------------------------------------------------------------------------------------------------------------------

Exercises 7.4

1. Assume the following declarations have been made in function main:

intList1[100], List2[100], ActNo1=0, ActNo2=0, High, Low;

floatScores [30], Average;

char Ch;booleanValid, Error;

Indicate which of the following are valid subprogram headers. Write an appropriate line of code that will call each of those that are valid. Include an explanation for those that are invalid.

a. void NewList (int List);b. void NewList (int List[], ActNo);c. void NewList (int List[], int * ActNo);d. void InitializeList (int * List, int * ActNo);e. void InitializeList (List, &ActNo);f. int HighValue (int List[]);g. int LowValue (int * PtrList);h. float Average (float Data[]);i. void Average (float Data[], float * Avr);j. void Average (float * PtrData, float * Avr);

2. Complete the following C program:

FillListWithRandomIntegers1 (List1,&ActNo1,MAX1,20,1,100);Void-function FillListWithRandomIntegers1 shall place 20 random integers

[range 1-100] into array List1. Do not place more than MAX1 integers into array. Do not use element 0.DisplayList ( List1, ActNo1);

Void-function DisplayList shall display the memory associated with the

Page 40: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [40]

appropriate array in the same form as that illustrated in the DiceDistribution of Example 7.3. Do not display element 0. Display and label ActNo.

# define MAX1 25# define MAX2 8

main(int argc, char *argv[]){intList1[MAX1+1], List2[MAX2+1], ActNo1=0, ActNo2=0;

FillListWithRandomIntegers1 (List1,&ActNo1,MAX1,20,1,100);DisplayList ( List1, ActNo1);FillListWithRandomIntegers1 (List2,&ActNo2,MAX2,20,50,100);DisplayList1 ( List2, ActNo2);

3. Complete the following C program:

FillListWithRandomIntegers2 (&List1,&ActNo1,MAX1,20,1,100);Void-function FillListWithRandomIntegers shall place 20 random integers

[range 1- 100] into array List1. Do not place more than MAX1 integers into array. Do not use element 0.DisplayList ( List1, ActNo1);

Void-function DisplayList shall display the memory associated with the appropriate array in the same form as that illustrated in the

DiceDistribution of Example 7.3. Do not display element 0. Display and label ActNo.

# define MAX1 25# define MAX2 8

main(int argc, char *argv[]){intList1[MAX1+1], List2[MAX2+1], ActNo1=0, ActNo2=0;

FillListWithRandomIntegers2 (&List1,&ActNo1,MAX1,15,60,100);DisplayList ( List1, ActNo1);FillListWithRandomIntegers1 (&List2,&ActNo2,MAX2,20,-5,+5);DisplayList1 ( List2, ActNo2);

4. Complete the following C program:

FillListWithRandomIntegers (List1,&ActNo1,MAX1,20,1,100);Void-function FillListWithRandomIntegers shall place 20 random integers [range 1- 100] into array List1. Do not place more than MAX1 integers

into array. Do not use element 0.DisplayList ( List1, ActNo1);

Void-function DisplayList shall display the memory associated with the appropriate array in the same form as that illustrated in the

DiceDistribution of Example 7.3. Do not display element 0. Display and label ActNo.High (List1, ActNo1);

Explicit-function High shall explicitly return the highest integer in the List.

Page 41: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [41]

Low (List1, ActNo1);Explicit-function Low shall explicitly return the lowest integer in the List.

# define MAX1 25# define MAX2 8

main(int argc, char *argv[]){intList1[MAX1+1], List2[MAX2+1], ActNo1=0, ActNo2=0,LowNum;

FillListWithRandomIntegers (List1,&ActNo1,MAX1,20,1,100);DisplayList ( List1, ActNo1);printf ("The High Value = %d\n",High (List1, ActNo1);printf ("The Low Value = %d\n",Low (List1, ActNo1);FillListWithRandomIntegers (&List2,&ActNo2,MAX2,20,1,1000);DisplayList1 ( List2, ActNo2);printf ("The High Value = %d\n",High (List2, ActNo2));LowNum = Low (List2, ActNo2);printf ("The Low Value = %d\n",LowNum);

5. Complete the following C program:

InitializeList (&List1,&ActNo1);Function InitializeList shall place -1 in all elements of the list and set the ActNo to 0.

InteractivelyAppendList (&List1,&ActNo1,MAX1);Function InteractivelyAppendList shall allow the user to enter valid

integers into the array while there is available room; the user will exit the module by entering the Exit value. Valid Integers are in the range 0-100. The Exit shall be -1. The prompt shall display the index and the range in the form:

Enter Value for List [1] <Enter -1 to Exit> : __If the score is Valid, place it into the array and increment the actual

number counter. Do not ever overflow an array! If this function is evoked with a full array, display an "Array Overflow" message. Place the first integer in element 1.DisplayList ( List1, ActNo1);

Function DisplayList shall display the memory associated with the appropriate array in the same form as that illustrated in the

DiceDistribution of Example 7.3. Do not display element 0. Display and label ActNo.

# define MAX1 25# define MAX2 8

main(int argc, char *argv[]){intList1[MAX1+1], List2[MAX2+1], ActNo1=0, ActNo2=0;

InitializeList (&List1,&ActNo1,);InteractivelyAppendIntegers (&List1,&ActNo1,MAX1);DisplayList ( List1, &ActNo1);InitializeList (&List2,&ActNo2,);

Page 42: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [42]

InteractivelyAppendIntegers (&List2,&ActNo2,MAX2);DisplayList ( List2, ActNo2);InteractivelyAppendIntegers (&List2,&ActNo2,MAX2);DisplayList ( List2, ActNo2);InteractivelyAppendIntegers (&List2,&ActNo2,MAX2);DisplayList ( List2, ActNo2);

Test Data:On the first call to InteractivelyAppendIntegers try to input the sequence:80 90 70 -1On the second call to InteractivelyAppendIntegers try to input the

sequence:80 90 70 80 90 70 -1On the third call to InteractivelyAppendIntegers try to input the sequence:100 50 -1On the fourth call to InteractivelyAppendIntegers try to input the

sequence:100 50 -1

6. Complete the following C program:

FillListWithRandomIntegers (List1,&ActNo1,MAX1,20,1,100);Function FillListWithRandomIntegers shall place 20 random integers

[range 1- 100] into array List1. Do not place more than MAX1 integers into array. Do not use element 0.DisplayList ( List1, ActNo1);

Function DisplayList shall display the memory associated with the appropriate array in the same form as that illustrated in the

DiceDistribution of Example 7.3. Do not display element 0. Display and label ActNo.SelectionSortList (List1,&ActNo1);

Function SelectionSort shall sort the integers in ascending order.

# define MAX1 50# define MAX2 8

main(int argc, char *argv[]){intList1[MAX1+1], List2[MAX2+1], ActNo1=0, ActNo2=0;

FillListWithRandomIntegers (List1,&ActNo1,MAX1,40,1,1000);SelectionSortList (List1,&ActNo1);DisplayList ( List1, ActNo1);FillListWithRandomIntegers (&List2,&ActNo2,MAX2,8,1,100);SelectionSortList (List2,&ActNo2);DisplayList1 ( List2, ActNo2);

7. Consult your library to find other computer science textbooks which explain the logic behind the "Bubble Sort". Substitute the BubbleSort for the SelectionSort as you complete problem 6.

8. As you complete problem 6, insert a call to QuickDisplay (List, ActNo) after each pass within the SelectionSort.

Page 43: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [43]

9. As you complete problem 7, insert a call to QuickDisplay (List, ActNo) after each pass within theBubbleSort.

10. Random order shall be generated with the rand() function to be in the range 1-30,000. In Order shall be in ascending order. Cluster 95 shall have the first 95% of the array in ascending order and the last 5% in random order. Cluster 90 shall have the first 90% of the array in ascending order and the last 10% in random order. Cluster 80 shall have the first 80% of the array in ascending order and the last 20% in random order. Cluster 70 shall have the first 70% of the array in ascending order and the last 30% in random order. Reverse Order shall be in descending order. Write the program necessary to produce and complete the following chart:

Internal Memory Sorting----------------------------------------

Sort Name : Selection Sort Computer Type : _____________________C Compiler : ________________________ Microprocessor Speed : _______________

a) ------------------------------------------------------------------------------------------------------------------------------------------

No Integers Sort Timein Array Distribution (in seconds)

------------------------------------------------------------------------------------------------------------------------------------------

50 Random xxxxxxx.xx 100 Random xxxxxxx.xx 200 Random xxxxxxx.xx 400 Random xxxxxxx.xx 800 Random xxxxxxx.xx 1600 Random xxxxxxx.xx 3200 Random xxxxxxx.xx 6400 Random xxxxxxx.xx 12800 Random xxxxxxx.xx

b) Repeat Table a using In Order distribution:

------------------------------------------------------------------------------------------------------------------------------------------

No Integers Sort Timein Array Distribution (in seconds)

------------------------------------------------------------------------------------------------------------------------------------------

50 In Order xxxxxxx.xx 100 In Order xxxxxxx.xx 200 In Order xxxxxxx.xx 400 In Order xxxxxxx.xx 800 In Order xxxxxxx.xx 1600 In Order xxxxxxx.xx 3200 In Order xxxxxxx.xx 6400 In Order xxxxxxx.xx 12800 In Order xxxxxxx.xx

c) Repeat Table a using Reverse Order distribution:d) Repeat Table a using Cluster 95 distribution:e) Repeat Table a using Cluster 90 distribution:

Page 44: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [44]

f) Repeat Table a using Cluster 80 distribution:g) Repeat Table a using Cluster 70 distribution:h) Use a spreadsheet to construct and print graphs for each of the tables (a-g

above). Let he Number of items be the x-coordinate and the time in seconds be the y-coordinate. Use the spreadsheet to label the graph; include the computer, compiler, processor speed, and sort name.

11. Repeat problem 10 with the Bubble Sort.

12. Rewrite DisplayIntegerArray using pointer arithmetic as opposed to array indexing.

void DisplayIntegerArray (char ArrayTitle[], int * Ptr, int NoToDisplay, int ActNo, int Max);

13. Rewrite QuickDisplay using pointer arithmetic as opposed to array indexing.

void QuickDisplay (int Array[], int NoToDisplay,int ActNo);

14. Rewrite FillArrayRandom100 using pointer arithmetic as opposed to array indexing.

void FillArrayRandom100 (int Array[], int NoToFill, int *ActNo, int Max);

A NOTE OF INTEREST Data Abstraction

In C, Arrays provide examples of structured data types. (As you'll see later, records, files, and sets are also structured data types.) In a structured data type, the relationship between the elements of the data type is as important as the individual components themselves. For instance, in a one–dimensional Array of integers, we completely define the structure by giving its values and by specifying the positions of these values relative to other elements in the list of integers. For example, we say that 19 is the first value in the list, 89 is the second, 12 is the third, and so on.

There are two implicit conclusions to be drawn from what we have just said. First, in a data structure such as a list, we specify the structure by defining the relationships between items as well as the values of individual items. Second, we can then implement that conceptually defined structure in our programs using a tool from C; for example, a C Array is used to implement the concept of a list. It is important to note the distinction between the conceptual data structure that we define and its implementation in C. In the case of a list, this distinction may seem relatively minor because C provides a one–dimensional Array as an obvious means of implementing a conceptual list. However, there is no guarantee that there will always be such a straightforward link between a conceptual data structure and its implementation in C.

Consider, for instance, the structure charts that we have used to specify the relationships between modules in a C program. Such a structure chart could itself be considered a data structure. As such, it is clearly a more complex structure than a list. In this data structure, the data items are the module names; their relationship is that Module 2 is directly subordinate to Module 1 if Module 1 calls Module 2 in performing its logic. The relationship between data items in this structure is hierarchical. This hierarchical relationship constitutes the basis for a conceptual data structure known as a tree. We will not study trees in detail here. For one reason, C provides no direct implementation for trees. The syntax of C does not include a structured type that completely reflects the hierarchical relationship between items in a tree.

Does this mean that one cannot write a C program that manipulates a tree data structure? No, the representation of trees is typically covered in a second course in computer science. However, the separation between the conceptual definition of a data structure and its eventual implementation in a particular computer language is an important one to keep in mind. This

Page 45: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [45]

separation, often called data abstraction, is a topic we shall study more rigorously in chapter 14. The value of data abstraction is that it allows us to think in terms of data structures without being shackled by the syntactical constraints of a programming language--similar to what pseudocode allows us to do in describing an algorithm's logic. Once the data structure and the algorithms that manipulate it are understood at this conceptual level, we can then turn our attention to ways of implementing the structure in C or other languages. Some newer languages, such as Ada or C++ or Modula–2, emphasize this data abstraction theme to a greater degree than C. They allow the programmer to write packages of routines with implementations for such abstract data types; these may then be called from any program that works with data of that abstract type. In effect, these languages allow the programmer to extend the data typing capacity of the language to emphasize the separation of the data structure's definition from its implementation. This approach to using and studying data structures seems certain to have a profound effect on computer science in the coming years.

7.5Searching Algorithms

The need to search an Array for a value is a common problem. For example, you might wish to replace a test score for a student, delete a name from a directory or mailing list, or upgrade the pay scale for certain employees. These and other problems require you to be able to examine elements in some list until the desired value is located. When it is found, some action is taken.

Sequential Search

The first searching algorithm we will examine is the most common method, a sequential search. This process is accomplished by examining the first element in some list and then proceeding to examine the elements in the order they appear until a match is found. Variations of this basic process include searching a sorted list for the first occurrence of a value, searching a sorted list for all occurrences of a value, and searching an unsorted list for the first occurrence of a value.

Example 7.15Unordered List ---> 20 15 12 8 5 9 3 2 5 18SoughtNum --------> 2

To illustrate a sequential search, suppose you have an array of integers, called List, and you want to find the first occurrence of some particular value (2), called SoughtNum. If the desired value is located, you want to print its position. If the value is not in the Array, let us print an appropriate message. The code for such a search is

Index = 1;while ( (SoughtNum != List[Index]) && (Index < ActNo) ) Index++;

if (SoughtNum == List[Index]) printf ("%d is in position %d of List\n",SoughtNum,Index);else printf ("%d is not in List\n",SoughtNum);

Example 7.16Sorted List -------> 2 3 5 5 8 9 12 15 18 20 SoughtNum ------> 4

Let's now consider some variations of this problem. Although the code in Example 7.15 works for both a sorted and an unsorted list, it is certainly not

Page 46: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [46]

efficient for searching a sorted (ordered) list. Why search the sorted list, above, beyond the third element (5) of the array? If it is sorted, all of the remaining values will also exceed the SoughtNo.

The code fragment below offers a much better solution for printing the location of the first occurrence of a SoughtNo within a sorted List.

Index = 1;while ( (SoughtNum < List[Index]) && (Index < ActNo) ) Index++;

if (SoughtNum == List[Index]) printf ("%d is in position %d of List\n",SoughtNum,Index);else printf ("%d is not in List\n",SoughtNum);

Example 7.17Unordered List ---> 20 15 12 8 5 9 3 2 5 18SoughtNum --------> 2

A relatively easy modification of the sequential search is to examine an unsorted (unordered) List for all occurrences of SoughtNo.

Count = 0;for (Index = 1; Index <= ActNo; Index ++ ){if (SoughtNum == List[Index])

{ Count ++; printf ("%d => is in position %d\n", SoughtNum, Index); }}

This code works for an unsorted list. A modification of the code for working with a sorted list is included as an exercise.

Binary Search

Searching relatively small lists sequentially does not require much computer time. However, sequentially searching longer sorted lists ( telephone directories and lists of credit card customers) is inefficient. In a sense, they correspond to looking up a word in the dictionary by starting at the first word and proceeding word–by–word until the desired word is found. Since extra computer time means extra expense for most companies where large amounts of data must be frequently searched, a more efficient way of searching is needed.

If the list to be searched has been sorted, it can be searched for a particular value by a method referred to as a binary search. Essentially, a binary search consists of examining a middle value of an Array to see which half contains the desired value. The middle value of this half is then examined to see which half of the half contains the value in question. This halving process is continued until the value is located or it is determined that the value is not in the list. (Remember, however, in order to use a binary search, the list must be sorted and the sorting process has its own costs which should be evaluated.)

The code for this process is relatively short. We shall search the sorted List for some SoughtNum. First and Last are integer variables.

First = 1;Last = ActNo;

Page 47: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [47]

Found = False;while ((!Found) && (First <= Last)){Mid = (First + Last) / 2;if (SoughtNum == List[Mid]) Found = True;

else if (SoughtNum > List[Mid]) First = Mid + 1;

elseLast = Mid – 1;

}

This loop checks to see if List[Mid] is the SoughtNum; if so set Found to True to exit loop. Since 10 is not the SoughtNum(13), the code determines if the SoughtNum is in the top half of the ordered list (subscripts 5-7) or the bottom half of the ordered list (subscripts 1-3) Since 13 is larger than 10, the new First is set to Mid + 1 (4) and the loop continues. Notice that half of the array will be eliminated in one look; elements 1-3 of the sorted array need not be examined any further.

This loop checks to see if List[Mid] is the SoughtNum; if so set Found to True to exit loop. Since 19 is not the SoughtNum(13), the code determines if the SoughtNum is in the top half of the ordered list (subscripts 7-7) or the bottom half of the ordered list (subscripts 5-5) Since 13 is smaller than 19, the new Last is set to Mid - 1 (5) and the loop continues. Notice that almost half of the this sub-array will be eliminated on the second look; elements 7-7 of the sorted array need not be examined any further.

This loop checks to see if List[Mid] is the SoughtNum; if so set Found to True to exit loop. Since 13 is the SoughtNum(13), Found is set to True and the loop terminates. The loop terminates either because the SoughtNum has been found in the sorted List or because it is not in the array. If the First is greater than the Last, the SoughtNum is not in the sorted List; otherwise Found has been set to True and Mid contains the subscript telling where the SoughtNum may be found.

Before continuing, let's walk through this search a second time to get a better understand how it works. Assume A is the array

4 7 19 25 36 37 50 100 101 205 220 271 306 321A[1] A[14]

with values as indicated. Furthermore, assume SoughtNum contains the value 25. Then initially, First, Last, and Num have the values

1 14 25First Last SoughtNum

A listing of values by each pass through the loop produces

First Last Mid A[Mid] Found

Page 48: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [48]

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Before loop 1 14 - - FalseAfter first pass 1 6 7 50 FalseAfter second pass 4 6 3 19 FalseAfter third pass 4 4 5 36 FalseAfter fourth pass 4 4 4 25 True

To illustrate what happens when the value being looked for is not in the Array, suppose SoughtNum contains 210. The listing of values then produces

First Last Mid A[Mid] Found------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Before loop 1 14 - - FalseAfter first pass 8 14 7 50 FalseAfter second pass 8 10 11 220 FalseAfter third pass 10 10 9 101 FalseAfter fourth pass 11 10 10 205 False

At this stage, First > Last and the loop is exited.

Relative Efficiency of Searches

Let's now examine briefly the efficiency of a binary search compared to a sequential search. For purposes of this discussion, assume a sequential search on a list of 15 items requires at most 15 microseconds. The nature of a sequential search is such that every time you double the list length, the maximum searching time is also doubled; Figure 7.1 illustrates this increase.

Figure 7.1Sequential Search

The logic of the binary search is more complex than that of the sequential search. Let us assume a list of 15 items requires a maximum of 60 microseconds when searched by a binary search. Since this process consists of successively halving the list, at most four passes will be required to locate the value. This means each pass uses 15 microseconds. When the list length is doubled, it requires only one more pass. Thus, a list of 30 items requires 75 microseconds and a list of 60 items requires 90 microseconds. This is shown graphically in Figure 7.2.

Figure 7.2Binary Search

Differences in computer hardware and compilers will cause the actual times for

each of these will vary. For very small sorted lists, the sequential search is more efficient than the binary search. At some point (to be determined by hardware, compiler, and code) the binary search is more efficient than the sequential search. This is best illustrated by showing the comparison of these two searches on the same graph; see Figure 7.3.

Figure 7.3Sequential Searchvs Binary Search

Subscript Errors

Page 49: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [49]

If Array has three elements, a reference to Score[3] or Score[-1] is generally considered to be a subscript error. Although subscript errors can cause an execution error, they will normally destroy other adjacent variables in your program or crash the system. We have stressed the importance of valid subscripts for four sections; it is time to illustrate the potential disastors awaiting subscript errors. Let us assume that the memory manager assigns the declarations

intA = 6,B = 5;

intArray [MAX] = {1,2,3};

charC = 'A',D = 'B';

the following contiguous memory:

|-------|A => &3200706 | 6 | |-------|B => &3200704 | 5 | |-------|Array [ 2] => &3200702 | 3 | |-------|Array [ 1] => &3200700 | 2 | |-------|Array [ 0] => &3200698 | 1 | |-------|C => &3200697 | A | |-------|D => &3200696 | B | |-------|

Let us assume that we wish to execute the following line of code:

Array[3] = 44;

There will be times when the advanced C programmer knows enough about a specific chunk of memory to effectively exceed the boundaries of an array, but we should make every effort to stay within acceptable bounds.

The base address of Array is &3200698. A reference to Array[3] is a reference to &3200698 + 3 * sizeof(int) = &3200704; when two bytes are written to this address, the assignment destroys the contents of integer variable B.

Our contiguous memory now looks like

|-------|A => &3200706 | 6 | |-------|B => &3200704 | 44 | |-------|Array [ 2] => &3200702 | 3 | |-------|Array [ 1] => &3200700 | 2 |

Page 50: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [50]

|-------|Array [ 0] => &3200698 | 1 | |-------|C => &3200697 | A | |-------|D => &3200696 | B | |-------|

Let us assume that we wish to execute the following line of code:

Array[-1] = 97;

The base address of Array is &3200698. A reference to Array [–1] is a reference to &3200698 + –1 * sizeof(int) = &3200696; when two bytes are written to this address, the assignment destroys both the contents of variable C and the contents of variable D.

Our contiguous memory now looks like

|-------|A => &3200706 | 6 | |-------|B => &3200704 | 44 | |-------|Array [ 2] => &3200702 | 3 | |-------|Array [ 1] => &3200700 | 2 | |-------|Array [ 0] => &3200698 | 1 | |-------|C => &3200697 | a | |-------|D => &3200696 | | |-------|

Part of the power of C is to quickly and effectively control all of the memory available to the user, but with the increased power is potential danger. Subscript errors on single-user microcomputer C environments can be very frustrating. Any of the following can happen when there is an attempt to change the wrong memory:

1. If the address calculated by the subscript error is part of the memory assigned to other local variables, the validity of these variables may destroy other logic, computations, or variables; this error is often hard to debug.

2. If the address calculated by the subscript error is part of the memory assigned to the stack, the returns to functions could be destroyed and cause very unpredictable errors.

3. If the address calculated by the subscript error is part of the memory assigned to the compiler, certain portions of the compiler and/or editor may be inoperative. The compiler application will often need to be terminated and restarted. This error will lock-up the entire system if the compiler-exit has been destroyed; the computer would have to be rebooted.

4. If the address calculated by the subscript error is part of the memory assigned to another application, portions or all of that application may be inoperative.

Page 51: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [51]

5. If the address calculated by the subscript error is part of the memory assigned to the operating system, certain portions of the operating system may be inoperative. You might not be able to copy files, format disks, etc. The computer would have to be rebooted. This error will sometimes lock-up the entire system.

6. If the address calculated by the subscript error is not within the limits of memory available to the system, the computer will sometimes lock-up and have to be rebooted.

7. If the address calculated by the subscript error is in a portion of memory that is not being used, there may be no disastrous results.

For an array declared

int Array [MAX];

make every effort to make sure that your subscripts are always within limits (between 0 and MAX-1).

Exercises 7.5

1. Modify the sequential search in the beginning of this section to locate and print all occurrences of the same value.

2. Complete the C program:FillListWithRandomIntegers (List1,&ActNo1,MAX1,20,1,100);

Function FillListWithRandomScores shall place 20 random integers [range 1- 100] into array List1. Do not place more than MAX1 integers into array. Do not use element 0.DisplayList ( List1, ActNo1);

Function DisplayList shall display the memory associated with the appropriate array in the same form as that illustrated in the

DiceDistribution of Example 7.3. Do not display element 0. Display and label ActNo.SequentialSearchList1 ( List1, ActNo1, SoughtNum);

Function SequentialSearchList1 shall search List1 for the first occurrence of the SoughtNum. If found, the function will explicitly return the array

subscript reflecting the location of SoughtNum within the array. The function will explicitly return 0 if not found.

# define MAX1 100# define MAX2 8

main(int argc, char *argv[]){intList1[MAX1+1], List2[MAX2+1], ActNo1=0, ActNo2=0, SoughtNum, Location;

SoughtNum = List1[29];FillListWithRandomIntegers (List1,&ActNo1,MAX1,50,1000,30000);SoughtNum = List1[29];DisplayList ( List1, ActNo1);Location = SequentialSearchList1 ( List1, ActNo1, SoughtNum);printf ("SoughtNum = %d Location = %d\n\n",SoughtNum,

Location);

SoughtNum = 100;

Page 52: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [52]

if (SequentialSearchList1 ( List1, ActNo1, SoughtNum))printf ("SoughtNum = %d Location = %d\n\n",

SoughtNum,Location);else

printf ("SoughtNum = %d Not Found! Location = %d\n\n",SoughtNum,Location);

SoughtNum = 31000;if (SequentialSearchList1 ( List1, ActNo1, SoughtNum))

printf ("SoughtNum = %d Location = %d\n\n",SoughtNum,Location);

elseprintf ("SoughtNum = %d Not Found! Location = %d\n\n",

SoughtNum,Location);

3. Complete the C program:FillListWithRandomIntegers (List1,&ActNo1,MAX1,20,1,100);

Function FillListWithRandomScores shall place 20 random integers [range 1- 100] into array List1. Do not place more than MAX1 integers into array. Do not use element 0.DisplayList ( List1, ActNo1);

Function DisplayList shall display the memory associated with the appropriate array in the same form as that illustrated in the

DiceDistribution of Example 7.3. Do not display element 0. Display and label ActNo.SequentialSearchList2 ( List1, ActNo1, SoughtNum, &NoSearches);

Function SequentialSearchList1 shall search List1 for the first occurrence of the SoughtNum. If found, the function will explicitly return the array

subscript reflecting the location of SoughtNum within the array. The function will explicitly return 0 if not found. NoSearches shall be the

number of elements that are examined.

# define MAX1 100# define MAX2 8

main(int argc, char *argv[]){intList1[MAX1+1], List2[MAX2+1], ActNo1=0, ActNo2=0, SoughtNum, Location, NoSearches;

SoughtNum = List1[29];FillListWithRandomIntegers (List1,&ActNo1,MAX1,50,1000,30000);SoughtNum = List1[29];DisplayList ( List1, ActNo1);Location = SequentialSearchList1 (List1, ctNo1, SoughtNum,

&NoSearches);printf ("SoughtNum = %d Location = %d NoSearches = %d\n\n",

SoughtNum,Location);

SoughtNum = 100;if (SequentialSearchList1 ( List1, ActNo1, SoughtNum, NoSearches)){puts ("Not Found");printf ("SoughtNum = %d Location = %d NoSearches = %d\n\n",

SoughtNum,Location);

Page 53: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [53]

}else{puts ("Found");printf ("SoughtNum = %d Location = %d NoSearches = %d\n\n",

SoughtNum,Location);}

SoughtNum = 31000;if (SequentialSearchList1 ( List1, ActNo1, SoughtNum, NoSearches)){puts ("Not Found");printf ("SoughtNum = %d Location = %d NoSearches = %d\n\n",

SoughtNum,Location);}

else{puts ("Found");printf ("SoughtNum = %d Location = %d NoSearches = %d\n\n",

SoughtNum,Location);}

4. Complete problem 3 substituting BinarySearchList ( List1, ActNo1, SoughtNum, NoSearches) for the SequentialSearchList.

5. Write a function to search a sorted list and remove all duplicates.RemoveDuplicatesWithinList ( List1, ActNo1);

6. When using the binary search algorithm, it requires a maximum of one search to find any given element in a list of one. It requires a maximum of two searches to find any given element in a list of two or three. It requires a maximum of three searches to find any given element in a list of four to seven. Complete the tables below:

----------------------------------------------------------------------------------------------------------------------------------------Searching Minimum

Maximum AverageAlgorithm # Items # Searches # Searches # Searches-------------------------------------------------------------------------------------------------------------------

---------------------Binary 1 1 1 1.00Binary 3 1 2 1.66Binary 7 1 3 2.43Binary 15 1 4Binary 31 1Binary 63

----------------------------------------------------------------------------------------------------------------------------------------Searching Minimum

Maximum AverageAlgorithm # Items # Searches # Searches # Searches-------------------------------------------------------------------------------------------------------------------

---------------------Sequential 1 1 1 1Sequential 3 1 3 2

Page 54: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [54]

Sequential 7 1 7 4Sequential 15 1 15Sequential 31 1Sequential 63

8. Using worst–case possibilities of 3 microseconds for a sequential search of a list of ten items and 25 microseconds for a binary search of the same list, use a spreadsheet program to construct/print a graph illustrating relative efficiency for these two methods applied to lists of longer lengths.

9. Modify the sequential search that you developed in Exercise 1 to list all occurrences of a value so that it can be used on a sorted list. That is, have it stop after the desired value has been passed in the list.

7.6 Character String Processing

At this point, we have sufficient skills to create our own versions of the string utilities found in string.h. User-friendly interactive programming provides many opportunities to do character manipulation.

Example 7.18Let us create a function StrCpy. Our version of the function will have no

explicit return. It will place the NewString in the String. We shall pass the size of the container to prevent overflow. We shall begin with a main program which declares a ten-character string variable called Name.

charName [10];

intIndex;

We plan to test our StrCpy function on Name. Since it currently contains garbage, let us fill the string with known information (Perhaps A,B,C,...).

for (Index = 0; Index < sizeof (Name); Index ++)Name[Index]=Index+65;

The following code fragment can be used

for (Index = 0; Index < sizeof (Name); Index ++)printf ("%2d -> %c [%3d]\n",Index,Name[Index],Name[Index]);

to display the contents of Name.

0 -> A [ 65] 1 -> B [ 66] 2 -> C [ 67] 3 -> D [ 68] 4 -> E [ 69] 5 -> F [ 70] 6 -> G [ 71] 7 -> H [ 72] 8 -> I [ 73] 9 -> J [ 74]

Page 55: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [55]

We have to remember to leave room for the end of string marker. The basic logic for StrCpy is

1. Set Pos to 02. While the next character to copy is not the end of string marker and

there are still more characters left in the original string2.1 Copy NewString[Pos] into String[Pos]2.2 Increment Pos

3. Put and end-of-string marker in String.

There are many solutions to this problem. One of the solutions is

void StrCpy1 (char String[], char NewString[],long int MaxChars){long intPos;

for (Pos = 0; NewString[Pos] && Pos < MaxChars -1 ; Pos ++)String[Pos] = NewString[Pos];

String[Pos]=0; }

Since the NewString contains only eight characters, there is no need to alter more than eight characters of the String. Name[9] still contains the original 'J'. Since printf and puts print only until the end-of-string marker is found, the 'J' is never printed.

If StrCpy1 were evoked with

StrCpy1 (Name, "Abe Linc", sizeof (Name));for (Index = 0; Index < sizeof (Name)+3; Index ++)printf ("%2d -> %c [%3d]\n",Index,Name[Index],Name[Index]);

then the following output could be generated.

0 -> A [ 65] 1 -> b [ 98] 2 -> e [101] 3 -> [ 32] 4 -> L [ 76] 5 -> i [105] 6 -> n [110] 7 -> k [107] 8 -> [ 0] 9 -> J [ 74]

Another working version is found in StrCpy2.

void StrCpy2 (char String[], char NewString[],long int MaxChars){long intPos = 0;

while ( ( Pos < MaxChars-1 ) && ( NewString[Pos] != 0 ) ){String[Pos] = NewString[Pos];Pos ++;

}

Page 56: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [56]

String[Pos]=0;}

Example 7.19Let us create a function StrLen. Our version of the function will explicitly

return a long integer indicating the number of characters in the original string. Once more we shall use the main program which declares a ten-character string variable called Name.

long int StrLen1 (char String[]){long intPos,Count;

for ( Pos = 0, Count = 0 ; String[Pos]; Pos ++, Count++);return (Count);

}

If StrLen1 and StrCpy1 were evoked with

StrCpy1 (Name, "", sizeof (Name));printf ("String [%s] has %lu characters\n",Name,StrLen1(Name)); StrCpy1 (Name, "Tex", sizeof (Name));printf ("String [%s] has %lu characters\n",Name,StrLen1(Name)); StrCpy1 (Name, "Texas Rangers", sizeof (Name));printf ("String [%s] has %lu characters\n",Name,StrLen1(Name));

then the following output could be generated.

String [] has 0 charactersString [Tex] has 3 charactersString [Texas Ran] has 9 characters

The code fragment above helps to thoroughly test both StrLen1 and StrLen1. Notice that first call passes the "Null String", sometimes called the empty string. The second call passes a string that can easily fit in a ten-character container. The third call passes a string which exceeds ten characters; note that our StrLen1 function has prevented the string overflow which can occur with the normal strcpy function. Many of the string function solutions can use pointer arithmetic; such an alternative StrLen2 function is found below.

long int StrLen2 (char *Ptr){long intCount = 0;

while ((*Ptr) != '\0'){Count++;Ptr++;

}return (Count);

}

If StrLen2 and StrCpy2 were evoked with

Page 57: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [57]

StrCpy2 (Name, "", sizeof (Name));printf ("String [%s] has %lu characters\n",Name,StrLen2(Name)); StrCpy2 (Name, "Tex", sizeof (Name));printf ("String [%s] has %lu characters\n",Name,StrLen2(Name)); StrCpy2 (Name, "Texas Rangers", sizeof (Name));printf ("String [%s] has %lu characters\n",Name,StrLen2(Name));

then the following output could be generated.

String [] has 0 charactersString [Tex] has 3 charactersString [Texas Ran] has 9 characters

Example 7.20There are times that we would like the user to fill a character string with a

collection of integers. Let us create a function IsIntString1 which explicitly returns True if (1) the string includes only the characters '0' - '9' and (2) the string is no more than four characters in length; otherwise return False.

boolean IsIntStr1 (char String[]){long intPos = 0;

if ((strlen (String) > 4) || (String[0] == '\0')) /* Empty String Not Valid */return (False); /* >4 Characters Not Valid */

while (String[Pos]){if ((String[Pos] < '0') || (String[Pos] > '9')) return (False);

elsePos++;

}

if (String[Pos]) /* If Last Character Examined Not The End-Of-String Marker */return (False); /* Then The String Is Not Valid */

elsereturn (True);

}

If IsIntStr1 were evoked with

do{printf ("Enter an Integer String <999 to Exit> : ");gets(NoString);if (IsIntStr1(NoString))printf ("--> %s - Valid Integer String\n\n",NoString);

elseprintf ("--> [%s] - Not Valid Integer String\n\n",NoString);

} while (strcmp (NoString, "999") != 0);

then the following output could be generated.

Page 58: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [58]

Enter an Integer String <999 to Exit> :--> [] - Not Valid Integer String

Enter an Integer String <999 to Exit> : 123l2--> [123l2] - Not Valid Integer String

Enter an Integer String <999 to Exit> : -12--> [-12] - Not Valid Integer String

Enter an Integer String <999 to Exit> : 12345--> [12345] - Not Valid Integer String

Enter an Integer String <999 to Exit> : 1--> 1 - Valid Integer String

Enter an Integer String <999 to Exit> : 32--> 32 - Valid Integer String

Enter an Integer String <999 to Exit> : 9876--> 9876 - Valid Integer String

Enter an Integer String <999 to Exit> : 999--> 999 - Valid Integer String

The first call, above, indicates that the Null string is not a valid integer string. In the second call, the user accidentally entered an 'l' instead of a '1'; this common typing error is correctly processed with our function. The number passed in the third call, 12312, is technically an integer, but in accordance with our specification, we reject all five digit integers. This is one of many ways that our IsIntStr function can be more robust; it shall be left as an exercise. The number passed in the fourth call, 12312, is also technically an integer, but in accordance with our specification, we reject all integers that begin with a plus or minus sign. This is another way that our IsIntStr function can be more robust; it too shall be left as an exercise. The last four calls reflect correct one, two, three and four digit integers.

Example 7.21Imagine the problems trying to match character data in a database. Suppose

the original name were entered "John DOe".

charName;

printf ("Enter Name : ");gets (Name); Enter Name : John DOe

Searches for "John Doe" or "JOHN DOE" or "john doe" would all prove unsuccessful.

printf ("Enter Sought Name : "); Enter Sought Name : John Doegets (SoughtName); Enter Sought Name : john doeif (strcmp(SoughtName, Name) == 0) Enter Sought Name : JOHN DOE

Page 59: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [59]

The user might have to try many combinations, before finding John. If we had a function, UpperCase, which would convert a string to all capital letters, it would be easier for the user to find matches.

printf ("Enter Name : ");gets (Name); Enter Name : John DOeUpperCase1 (Name);printf ("Enter Sought Name : "); gets (SoughtName); Enter Sought Name : John DoeUpperCase1 (SoughtName);printf ("%s - %s\n",Name, SoughtName); JOHN DOE - JOHN DOEif (strcmp(SoughtName, Name) == 0)

Let us write a subprogram, called UpperCase, which will change all lowercase letters in a string to uppercase letters.

void UpperCase1 (char String[]){intPos;

for (Pos = 0; String[Pos]; Pos++){if ((String[Pos] >= 'a') && (String[Pos] <= 'z'))String[Pos] = String[Pos] - 32;

}}

It is important to alter only the lowercase letters! If we test the function with

strcpy (TempString,"123ABCabc(*&^");puts(TempString);UpperCase1(TempString);puts(TempString);

then the following output would be generated.

123ABCabc(*&^123ABCABC(*&^

Example 7.22Let us write a code fragment which will continue to prompt the teacher for an

integer exam score, in the range 10 - 100, until the user enters a valid choice.The valid integer range is {-32768, -32767, ... , +32766, +32767}. We have

already discussed the importance of selecting data types of the proper size. The programmer has control and can avoid errors such as the one below.

int No;

No = 32768;printf ("No = %d\n",No); No = -32768

The programmer has little control when the user enters an invalid integer from keyboard in response to scanf.

int

Page 60: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [60]

No;

printf ("Enter No : ");scanf ("%d",&No); Enter No : 32768printf ("No = %d\n",No); No = -32768

The programmer has even less control when the user enters non digits from keyboard in response to scanf.

intNo;

printf ("Enter No : ");scanf ("%d",&No); Enter No : 32a68printf ("No = %d\n",No); No = 32 [a68 still in

buffer]

The stdlib.h contains a function to convert a character string to a valid integer value; this function is called atoi. With the proper include file, the code fragment

No = atoi ("234");printf ("[%d]\n", No);printf ("[%d]\n", atoi ("32767"));printf ("[%d]\n", atoi ("32768"));

would produce the output below.

[234][32767][32767]

Function atoi works correctly for valid integer strings. The last call above, atoi("32768"), is not processed correctly because "32768" is not a valid integer string.

Let us now return to the task at hand. Even though our IsIntStr1 is not as robust as we would like, we shall use it in our solution.

do{Exam = -999;printf ("Enter an Exam Score [10-100] : ");gets(ExamString);if (IsIntStr1(ExamString)){Exam = atoi(ExamString);if (Exam > 100)printf ("--> [%d] - Too Big!\n\n",Exam);

else if (Exam < 10)printf ("--> [%d] - Too Small!\n\n",Exam);

}elseprintf ("--> [%s] - Not a Valid Integer String\n\n",

ExamString);}

Page 61: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [61]

while ((Exam > 100) || (Exam < 10));

Output from the code fragment above might be :

Enter an Exam Score [10-100] : 5--> [5] - Too Small!

Enter an Exam Score [10-100] : 105--> [105] - Too Big!

Enter an Exam Score [10-100] :--> [] - Not a Valid Integer String

Enter an Exam Score [10-100] : 5a--> [5a] - Not a Valid Integer String

Enter an Exam Score [10-100] : a5--> [a5] - Not a Valid Integer String

Enter an Exam Score [10-100] : 1r1--> [1r1] - Not a Valid Integer String

Enter an Exam Score [10-100] : 95

All user-friendly systems

(1) read potential numeric responses in string format (NoString)(2) verify the correctness of the string (NoString)(3) convert the string (NoString) to numeric format (No)(4) verify the range of the response No <= HIGH and No >= Low(5) provide appropriate error responses

Can you imagine the amount of code necessary to process each and every input (thousands) on a large interactive system? The computer scientist would quickly begin to wonder if it were not time to modify GetAnInteger1 to simplify the coding and reduce the redundancy. The prototype for GetAnInteger1 is

boolean GetAnInteger1 (char Prompt[], int *NewInt, int Low, int High, int Sentinel);

With a more robust IsIntString function, a much more user-friendly GetAnInteger2 can be designed. This is left as an exercise.

––––––––––––––––––––––FOCUS ON PROGRAMMING––––––––––––––––––––––

The sample program for this chapter features the use of arrays and subprograms. Since sorting an array is a common practice, it has been included as part of the program. Specifically, suppose the Home Sales Realty Company, Inc. wants to print a list containing the amount of all sales for a month. Each sale amount is provided by the user and the number of homes sold is less than 20. Write a program to do the following:

1. Read the data from keyboard input.2. Print the data in the order in which it is read with a suitable header and

format.

Page 62: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [62]

3. Print a sorted list (high to low) of sales with a suitable header and format.4. Print the total number of sales for the month, the total amount of sales, the

average sale price, and the company commission (7 percent).

Sample input would be

65000562349510078200

10175056700

where each line represents the sale price of a home. Typical output would include an unsorted list of sales, a sorted list of sales, and appropriate summary data.

A first–level pseudocode development is

1. FillListFromKeyboard2. PrintList3. SelectionSortList4. PrintList5. Compute6. PrintResults

Notice that PrintList is called twice and PrintResults includes output for number of sales, total of sales, average sale price, and company commission. These are printed with suitable headings.

Figure 7.4Hierarchy StructureChart for Home SalesReality Company

Module specifications for the main modules are

1. FillListFromKeyboardData received: NoneInformation returned: Sales for a Month

Actual Number of SalesLogic: Use a while loop to read entries into an array.

2. DisplayList ModuleData received: Array of Sales

Actual Number of SalesInformation returned: NoneLogic: Use print statements to display a suitable heading for an unsorted list.

Use a for loop with the array length as a loop control variable to print the list of sales for a month.

3. SelectionSort ModuleData received: Actual Number of SalesInformation returned: Sorted Array of SalesLogic: Use a selection sort to sort the array.

4. Compute Module

Page 63: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [63]

Data received: Array of SalesActual Number of Sales

Information returned: Total Sales Average Sale Company Commission

Logic: Compute the total sales. Compute the average sale. Compute company commission by using a defined constant,

CommissionRate.

5. PrintResults ModuleData received: Total sales

Average sales Company commission

Information returned: NoneLogic: Use print statements to display a summary report.

This program illustrates the use of Arrays with functions. Note the use of both value and variable parameters. Also note that a function is used to sort the Array.

PROGRAMReality.c

/********************************************************************************* Purpose: This program illustrates the use arrays with procedures. **** It includes filling an array from keyboard, sorting the **** array, and calculating the sum of its elements and its **** average. **** Modules Required: ClearScreen, PrintHeading, GetAFloat *********************************************************************************/

# include <stdio.h># include <console.h>

# define COMPANY_COMMISSION 0.07# define MAX_SALES 20# define True 1# define False 0# define SUCCESSFUL 1# define UNSUCCESSFUL 0

typedef int boolean;

void FillListFromKeyboard (float List[], int *ActNo, int Max);void DisplayList (char Title[], float List[], int ActNo);void SelectionSort (float List[], int ActNo);void Compute (float List[], int ActNo, float *Sum, float *Average,

float *Commission );void PrintResults (float TotalSales, float AverageSale,

float CompanyCommission );boolean GetFloat1 (char Prompt[], float * Newfloat, float Low, float High,

float Sentinel);

main (){int

Page 64: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [64]

ActNoSales=0;floatSales [ MAX_SALES + 1],TotalSales, AverageSale, CompanyCommission;

FillListFromKeyboard (Sales, &ActNoSales, MAX_SALES);DisplayList (" Unsorted Sales For June",Sales, ActNoSales);SelectionSort (Sales, ActNoSales);DisplayList (" Sorted Sales For June",Sales, ActNoSales);Compute (Sales, ActNoSales, &TotalSales, &AverageSale, &CompanyCommission);PrintResults (TotalSales, AverageSale, CompanyCommission);

}

/********************************************************************************* Purpose: Fill a float array from keyboard and update the ActNo counter. **** Use Elements 1..Max **** Modules Required: None **** Headers Required: stdio.h **** Globals Required: None **** Defines Required: None *********************************************************************************/void FillListFromKeyboard (float List[], int *ActNo, int Max){booleanDone = False;

charPrompt[30];

*ActNo = 0;do{ /* sprintf - print to string - fills Prompt with Enter List [1] */sprintf (Prompt,"Enter List [%d]",(*ActNo)+1); if (GetFloat1 (Prompt, &List[(*ActNo)+1], 0, 500000, -1) )(*ActNo)++;

elseDone = True;

}while ((*ActNo < Max) && (!Done));

}

/********************************************************************************* Purpose: Display a title line and the contents of a float array. **** Modules Required: None **** Headers Required: stdio.h **** Globals Required: None **** Defines Required: None *********************************************************************************/void DisplayList (char Title[], float List[], int ActNo){intCounter;

printf ("\n\n%s\n\n", Title); for (Counter = 1; Counter <= ActNo; Counter++ )printf (" <%2i> $%8.2f\n", Counter, List[Counter]);

}

Page 65: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [65]

/********************************************************************************* Purpose: Selection Sort a float array in ascending order **** Modules Required: None **** Headers Required: stdio.h **** Globals Required: None **** Defines Required: None *********************************************************************************/void SelectionSort (float List[], int ActNo){intIndexSmallestNo,Pass, Subscript;

floatTempFloat;

for (Pass = 1; Pass <= ActNo-1; Pass++ )

{IndexSmallestNo = Pass;for (Subscript = Pass + 1;Subscript <= ActNo;Subscript++)if (List[Subscript] < List[IndexSmallestNo]) IndexSmallestNo = Subscript;

TempFloat = List[IndexSmallestNo];List[IndexSmallestNo] = List[Pass]; List[Pass] = TempFloat;

} }

/********************************************************************************* Purpose: Compute the sum, average, and commission for a float array. **** Modules Required: None **** Headers Required: stdio.h **** Globals Required: None **** Defines Required: COMPANY_COMMISSION *********************************************************************************/void Compute (float List[], int ActNo, float *Sum, float *Average,

float *Commission ){intIndex;

(*Sum) = 0;for (Index = 1; Index <= ActNo; Index++)(*Sum) = (*Sum) + List[Index];

(*Average) = (*Sum)/ActNo;(*Commission) = (*Sum) * COMPANY_COMMISSION;

}

/********************************************************************************* Purpose: Print the Total Sales, Average Sale, and Company Commission **** Modules Required: None **** Headers Required: stdio.h **** Globals Required: None **** Defines Required: None **

Page 66: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [66]

*******************************************************************************/void PrintResults (float TotalSales, float AverageSale,

float CompanyCommission ){printf ("\n\n Statistics\n ----------\n\n");printf (" Total Sales = $%10.2f\n\n", TotalSales);printf (" Average Sale = $%10.2f\n\n", AverageSale);printf (" Company Commission = $%10.2f\n\n", CompanyCommission);

}

The output from Reality.c is as follows:

Enter List [1] < -1.000000 to Exit> : 65000Enter List [2] < -1.000000 to Exit> : 56234Enter List [3] < -1.000000 to Exit> : 95100Enter List [4] < -1.000000 to Exit> : 78200Enter List [5] < -1.000000 to Exit> : 101750Enter List [6] < -1.000000 to Exit> : 56700Enter List [7] < -1.000000 to Exit> : -1

Unsorted Sales For June

< 1> $65000.00 < 2> $56234.00 < 3> $95100.00 < 4> $78200.00 < 5> $101750.00 < 6> $56700.00

Sorted Sales For June

< 1> $56234.00 < 2> $56700.00 < 3> $65000.00 < 4> $78200.00 < 5> $95100.00 < 6> $101750.00

Statistics ----------

Total Sales = $ 452984.00

Average Sale = $ 75497.34

Company Commission = $ 31708.88––––––––––––––––––––––RUNNING ANDDEBUGGING TIPS––––––––––––––––––––––

1. Do not attempt to use a subscript that is out of range. Suppose we have

Page 67: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [67]

int List [6];

An inadvertent reference such as

for (J = 1; J <= 6 ; J++) List[J]= J;

will destroy the contents of memory not associated with array List (List[6]); this memory may contain another variable, part of the compiler, part of the operating system, or be unused at the moment. The results are unpredictable and are often destructive.

3. Comparing Array components to each other can lead to errors in using subscripts.

# define Length 100int A[Length];

a. Attempting to compare A[J] to A[J + 1]. If this does not stop at Array Length – 2, then J + 1 will be out of range.

b. Attempting to compare A[J – 1] to A[J]. This presents the same problem at the beginning of an Array. Remember; J – 1 cannot have

a value less than 0.

5. After using a sequential search, make sure you check to see if the value has been found. For example, if Num contains the value 3 and A is the Array whose elements 1-4 are

the search

Index = 1;Length = 4;while (Num != A[Index]) && (Index < Length) ) Index = Index + 1;

yields values

Since this loop can be terminated by either (a) finding the sought number (Num) or by (b) exhausting the search of the array, it is imperative that you remember to check to see that ( A[Index]==Num ) before making logical decisions based on a successful search.

SUMMARY Key Terms / Words

arraybinary searchcharacter array (string)component (element, cell) of an Array

Page 68: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [68]

End-of-String Markerindex (subscript)pointer arithmeticpointer decrementationpointer incrementationselection sortsequential search

Key Concepts

An Array is a structured variable; a single declaration can reserve several variables.

It is good practice to define the array MAX. Many logic problems are avoided if the array is declared to have MAX+1 elements and the first element used is element 1.

# define MAX 10int X[MAX+1];

Arrays can be visualized as lists; thus, the previous Array could be envisioned as either of the following:

Each component of an Array is a variable of the declared type (int, float, double, char, long int, long double, boolean, etc.).

Loops can be used to fill an array with random information.

for (Index = 1; Index <= MAX_ROLLS; Index ++){Die = (int) (rand()/32768.0 * 6 + 1);DiceDistribution[Die] ++;

} Loops can use pointer arithmetic information.

intNo[100], Ptr = &No[0], Index;

for (Index = 0; Index < 100; Index ++, Ptr++)*Ptr = Index;

Loops can be used to fill an array from the keyboard.

do {

printf ("Enter Score A[%d] <-1 to exit> : ",ActNo+1);scanf ("%d ",&Temp);if (Temp != -1 ){

ActNo++;List[ActNo] = Temp;

} }

Page 69: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [69]

while (Temp != -1);

Loops can be used to print data from Arrays.

for (Index = 1; Index <= MAX_ROLLS; Index ++)printf ("DiceDistribution[%d] = %8.2f\n",

DiceDistribution[Index];

Loops can be used perform calculations with Arrays, such as average, sum, etc.

for (Sum = 0, Index = 1; Index <= ActNo; Index ++)Sum += List[Index];

Average = Sum/ActNo;

Manipulating components of an Array is generally accomplished by using the index as a loop variable; for example, assuming the previous Score, to find the smallest value in the Array we can use

Smallest = List[1];for (Index = 2; Index <= ActNo; Index ++)

if (List[Index} < Smallest)Smallest = List[Index];

A selection sort is one method of sorting elements in an Array from high to low or low to high; for example, if A is an Array of length N, a low–to–high sort is

for (J = 1; J <= N–1; J++ ) { Index = J; for (K = J + 1; K <= N; K++ ) if (A[K] < A[Index]) Index = K; Temp = A[Index]; A[Index] = A[J]; A[J] = Temp; }

Arrays may be passed to subprograms as an array

main(){intX[10];InitializeArrayToZero (X, 10);

}

void InitializeArrayToZero (int List[], int Max){intSubscript;

for (Subscript = 0; Subscript < Max; Subscript++)List[Subscript]=0;

}

Page 70: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [70]

Arrays may be passed to subprograms as a pointer to an Array

main(){intX[10];InitializeArrayToZero (&X, 10);

}

void InitializeArrayToZero (int *Ptr, int Max){intSubscript;

for (Subscript = 0; Subscript < Max; Subscript++, Ptr++)(*Ptr) = 0;

}

Sorting Arrays is conveniently done using functions, Good program design insists such functions should be written generic enough to support passing a variety of arrays of that data type.

A sequential search of a list consists of examining the first item in a list and then proceeding through the list in sequence until the desired value is found or the end of the list is reached; code for this search is

Index = 1;while ( (SoughtNum != List[Index]) && (Index < ActNo) ) Index++;if (SoughtNum == List[Index]) printf ("%d is in position %d of List\n",SoughtNum,Index);else printf ("%d is not in List\n",SoughtNum);

A sequential search of a sorted list consists of examining the first item in a list and then proceeding through the list in sequence until the desired value is found or the search has progressed far enough; code for this search is

Index = 1;while ( (SoughtNum > List[Index]) && (Index < ActNo) ) Index++;if (SoughtNum == List[Index]) printf ("%d is in position %d of List\n",SoughtNum,Index);else printf ("%d is not in List\n",SoughtNum);

A binary search of a list consists of deciding which half of the list contains the value in question and then which half of that half, and so on; code for this search is

First = 1;Last = ActNo;Found = False;while ((!Found) && (First <= Last)){Mid = (First + Last) / 2;if (SoughtNum == List[Mid])

Page 71: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [71]

Found = True;else if (SoughtNum > List[Mid]) First = Mid + 1;

elseLast = Mid – 1;

}

When the computer scientist is designing operating systems, compilers, or real time systems, he/she often strives toward efficiency; for most applications that must be maintained, readability is often more important than a few bytes of memory.

––––––––––––––––––––PROGRAMMING PROBLEMS––––––––––––––––––––

For each of the programs below(A) construct the hierarchy structure chart(B) write the pseudocode for all modules(C) create a working copy [attractively include the computer scientist name(s)

on the output screen for each program](D) test the program(E) document the program and each module in accordance with your

instructor's requirements.

1. Write a program to read an unknown number of integer test scores from keyboard (assume at most 150 scores). Print out the original list of scores, the scores sorted from low to high, the scores sorted from high to low, the highest score, the lowest score, and the average score.

2. Write a program to help you balance your checkbook. The input consists of the beginning balance and then a sequence of transactions, each followed by a transaction code. Deposits are followed by a "D" and withdrawals are followed by a "W." The output should consist of a list of transactions, a running balance, an ending balance, the number of withdrawals, and the number of deposits. Include an appropriate message for overdrawn accounts.

3. Write a program to read a line of text as input. Print out the original line of text, the line of text in reverse order, and the number of vowels contained in the line.

4. Write a program that sorts data of type float as it is read from the keyboard. Do this by putting the first data item in the first component of an Array and then inserting each subsequent number in the Array in order from high to low. Print out the sorted Array. Assume there are at most 25 numbers.

5. Read in a list of 50 integers from the Keyboard. Place the even numbers into an Array called Even, the odd numbers into an Array called Odd, and the negatives into an Array called Negative. Print all three Arrays after all numbers have been read.

6. Read in 300 real numbers. Print the average of the numbers followed by all the numbers that are greater than the average.

7. In many sports events, contestants are rated by judges with an average score being determined by discarding the highest and lowest scores and averaging the remaining scores. Write a program in which eight scores are entered, computing the average score for the contestant.

Page 72: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [72]

8. Given a list of 20 test scores (integers), print the score that is nearest to the average.

9. The Game of Nim is played with three piles of stones. There are three stones in

the first pile, five stones in the second, and eight stones in the third. Two players alternate taking as many stones as they like from any one pile. Play continues until someone is forced to take the last stone. The person taking the last stone loses. Write a program which permits two people to play the game of Nim using an Array to keep track of the number of stones in each pile.

10. There is an effective strategy that can virtually guarantee victory in the game of Nim. Devise a strategy and modify the program in problem 11 so that the computer plays against a person. Your program should be virtually unbeatable if the proper strategy is developed.

11. The median of a set of numbers is the value in the middle of the set if the set is arranged in order. Given a list of 21 numbers, print the median of the list.

12. Rewrite problem 12 to permit the use of any length list of numbers.

13. The standard deviation is a statistic frequently used in education measurement. Write a program that, given a list of test scores, will find and print the standard deviation of the numbers. The standard deviation formula can be found in most statistics books.

14. Revise problem 15 so that after the standard deviation is printed, you can print a list of test scores that are more than one standard deviation below the average and a list of the scores more than one standard deviation above the average.

15. Salespeople for the Wellsville Wholesale Company earn a commission based on their sales. The commission rates are as follows:

Sales Commission

$0–1000 3%1001–5000 4%5001–10000 5%over 10000 6%

In addition, any salesperson who sells above the average of all salespeople receive a $50 bonus, and the top salesperson receives an addition $75 bonus.

Given the social security numbers and amounts sold by each of 20 salespeople, write a program that prints a table showing the salesperson's social security number, the amount sold, the commission rate, and the total amount earned. The average sales should also be printed.

16. Write a program that will allow you to gather information performance times to sequentially search an integer array that in internal memory. Then calculate the time to binary search the same array in internal memory. Use a spreadsheet program to produce a graph similar to that in figure 7-3.

17. Modularize program SortFloat.c. It must include the following prototypes

Page 73: carme.cs.trinity.educarme.cs.trinity.edu/thicks/CTextBook/Chap07-Arrays.doc  · Web viewNote that Scores[0] could be used to hold the ActNoScores variable. For unstructured languages

West Publishing - Chapter 7 - Introduction to Computer Science With C - Hicks, Nance, & Naps [73]

void SelectionSortFloat (float Array[], int ActNo);void DisplayArrayFloat (float Array[], int ActNo, char Title[]);void FillArrayFloatKeyboard (float Array[], int ActNo, float Low,

float High, float Sentinel);

The output of the program must be the same as that for SortFloat.c. The main program must contain only calls to the three subprograms prototyped above.