Programming, Problem Solving



Download 0.51 Mb.
Page2/6
Date05.08.2017
Size0.51 Mb.
#26659
1   2   3   4   5   6

Example 7.4

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


char

Alpha [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,




char

Name [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);

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 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.5

The 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);


would print




ABCDEFGHIJKLMNOPQRSTUVWXYZ

Example 7.6

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




# define MAX_FLAGS 10

boolean


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.1

1. Using descriptive names, and declare an array variable for each of the following:


a. A list of 35 test scores

b. The prices of 20 automobiles

c. The answers to 50 True or False questions

d. 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.
3. Find all errors in the following declarations of array variables.
a. int

Time (20)


b. int

Scores [5];


c. boolean

Flag[10] = True, False, True, False, True, False,

True, False, True, False;
d. int

Scores [5] = 3,4,2,1,6;


e. int

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


f. float

Data [4] = {3.5 4.2 7.6 8.1};


g. boolean

Answer [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.
8. Assume the address assigned to Info (by the memory manager) is 235760. What output is generated from


#define MAX_INFO 5

int


Index,

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 4

int


Index;

float


TaxRates [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 14

int


Index;

char


Characters [MAX_CHARS];
for (Index = 0; Index < MAX_CHARS; Index ++)

if (Index % 2 == 0)

Characters[Index] = Index + 65;

else


Characters[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");



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 1

typedef int boolean;
#define MAX_FLAGS 12

int


Index;

boolean


Flag [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




float

Money[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 ++)

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.2

Interactively

Filling an

Array

Filling Arrays With Scanf
Example 7.7

Let 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
int

Index,TempNo,Low,High,Sum,

ActNoScores = 0,

Scores[MAX_SCORES+1];

float

Average;


boolean

ValidNo;


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,

-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> : 83

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

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

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

***ERROR*** Invalid Number - Try Again!
Enter Exam Score <-999 - to Quit> : 100

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

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.2

1. What is meant by array overflow?


2. Assume the array List is declared as

int

List [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));

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.8

b. assign 65 to Test[–1]

c. display all relevant memory in a form similar to that of Example 7.8

d. assign 65 to Test[6]

e. display all relevant memory in a form similar to that of Example 7.8


# define MAX 6

char


A = 'a',

B = 'b',


C = 'c';

int


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

char


D = 'd',

E = 'e',


F = 'f';

5. Let the array Best be declared by




int

Best[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'};


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.3

Sorting

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.

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 0

int

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.

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 Index

1.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 = 1

Inner 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 1

Pass 2 5 2 3 8 4 False 1

Pass 3 5 2 4 10 4 False 1

Pass 4 5 2 5 1 4 True 1

End 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 = 2

Inner loop : (K = 3; K <= 5; K++ )
N Index K A[K] A[Index] A[K] < A[Index] J - ----- - ---- -------- --------------- -

Pass 1 5 2 3 8 4 False 2

Pass 2 5 2 4 10 4 False 2

Pass 3 5 2 5 6 4 False 2

End 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 = 3

Inner 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 3

Pass 2 5 3 5 6 8 True 3

End 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 = 4

Inner 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 4

End 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.

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.8

Our 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 high

4. Output sorted list-uses a for loop to output the sorted list



PROGRAM

SortFloat.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

# include

# define True 1

# define False 0

# define SUCCESSFUL 1

# define UNSUCCESSFUL 0

# define LIST_MAX 20
typedef int boolean;

void ClearScreen(void);

boolean GetFloat1 (char Prompt[], float * Newfloat, float Low, float High,

float Sentinel);

void PrintHeading(void);
main ()

{

float



TempFloat,

List[LIST_MAX+1];

int

ActNoItems,



Index,

IndexSmallestNo,

Pass,

Subscript;



boolean

Done;


char

Prompt [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++;

else


Done = 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");

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> : 10

Enter List [2] < -1.000000 to Exit> : 8

Enter List [3] < -1.000000 to Exit> : 6

Enter List [4] < -1.000000 to Exit> : 1

Enter List [5] < -1.000000 to Exit> : 9

Enter List [6] < -1.000000 to Exit> : 3

Enter List [7] < -1.000000 to Exit> : 4

Enter List [8] < -1.000000 to Exit> : -1


The unsorted list is as follows:
List[ 7] = 4.000

List[ 6] = 3.000

List[ 5] = 9.000

List[ 4] = 1.000

List[ 3] = 6.000

List[ 2] = 8.000

List[ 1] = 10.000
The sorted list is as follows:
List[ 7] = 10.000

List[ 6] = 9.000

List[ 5] = 8.000

List[ 4] = 6.000

List[ 3] = 4.000

List[ 2] = 3.000

List[ 1] = 1.000
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.3

1. 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 to

a. 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.4

Passing Arrays to

Functions

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, 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

# include


# 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[])

{

int



Nos1[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.9

Subprogram 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.


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;

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

|--------| |-------|



Download 0.51 Mb.

Share with your friends:
1   2   3   4   5   6




The database is protected by copyright ©ininet.org 2024
send message

    Main page