Programming, Problem Solving


RUNNING AND DEBUGGING TIPS



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

RUNNING AND

DEBUGGING TIPS

––––––––––––––––––––––

1. Do not attempt to use a subscript that is out of range. Suppose we have


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 100

int

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

array


binary search

character array (string)

component (element, cell) of an Array

End-of-String Marker

index (subscript)

pointer arithmetic

pointer decrementation

pointer incrementation

selection sort

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

int


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.


int

No[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;

}

}



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()

{

int



X[10];

InitializeArrayToZero (X, 10);

}
void InitializeArrayToZero (int List[], int Max)

{

int



Subscript;
for (Subscript = 0; Subscript < Max; Subscript++)

List[Subscript]=0;

}


Arrays may be passed to subprograms as a pointer to an Array


main()

{

int



X[10];

InitializeArrayToZero (&X, 10);

}
void InitializeArrayToZero (int *Ptr, int Max)

{

int



Subscript;
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])

Found = True;

else if (SoughtNum > List[Mid])

First = Mid + 1;

else

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


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.


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