COSC 120 : CASE STUDIES.

There are three complete case studies here. The first two case studies assume that students have been
introduced to the fundamental instructions read in, write out, assign a value, loop (for, while), select (if, if-else)
but are not yet familiar with programmer-defined subroutines.

Case Study #1: Find youngest person's age from a list of ages. (Interactive; No subroutines)
Case Study #2: Find youngest person's age and its frequency from a list of ages. (Uses files; No subroutines)
Case Study #3: Use Newton's Method to find square roots of numbers. (Interactive; Uses subroutines)


CASE STUDY #1

PROBLEM.

Write an interactive program which, given the number of ages in a list and given the list of ages (integers),
finds the lowest (smallest!) age in the list.

CLARIFICATION.

No data editing needs to be done for this program. That is, assume that the user will enter the numbers
within the ranges specified below. It will not matter if the list contains duplicate ages.

Input:

Output: Sample Session #1, with output in bold:

This program finds the smallest age from a list of ages which you
will enter at the keyboard. The ages must be in the range 0 to 125, inclusive.

Number of ages > 2
Age > 12
Age > 9
Smallest age = 9

Sample Session #2:

<Same opening message for each run!>

Number of ages > 3
Age > 68
Age > 68
Age > 68
Smallest age = 68

Sample Session #3:

Number of ages > 9
Age > 18
Age > 49
Age > 65
Age > 17
Age > 22
Age > 17
Age > 81
Age > 17
Age > 17
Smallest age = 17


DESIGN for AGES PROGRAM

DATA:

Input Variables:      numOfAges              integer                  number of ages to be read in
                              currentAge               integer                  age just read in

Output Variables:   smallestAge              integer                  smallest age from among those read in

Other Variables:     counter                     integer                  loop counter

ALGORITHM (shown in the form of a structure chart):

The SAME ALGORITHM in PSEUDOCODE REPRESENTATION with comments in parentheses:

(Greet user)
Write out message to user telling what program does

(Initialize)
smallestAge <-- 125

(Find out how many ages to be entered)
write out "Number of ages ? "
read in numOfAges

(Find age statistics)
Loop for counter going from 1 to numOfAges:

(Display statistics)
write out "Smallest age is", smallestAge


The C++ program :

//--------------------------------------------------------------------------------------------

// Program: Smallest
// Programmed by: Funky Winkerbean, 6/97.
//
// This program reads in a list of ages from the keyboard and then
// displays the smallest age in the list.
//---------------------------------------------------------------------------------------------

#include <iostream.h>

void main()
{

}


CASE STUDY #2: This is a modification of the program in Case Study #1. The two main differences are :
                                     i) this program is not interactive; and
                                     ii) this program also finds the frequency of the smallest age.

PROBLEM.
Write a program which, given a text file containing the number of ages in a list and the list of ages (integers),
finds the lowest (smallest!) age and its frequency and writes that information to another file.

CLARIFICATION.
No data editing needs to be done for this program. That is, assume that the input file contains data which is
within the ranges specified below.

Input (from a file named "ages.dat"):

Output (to a file named "results.dat"): Sample Input #1: (from "ages.dat")
2
12

Sample Output #1: (to "results.dat")

There are 2 ages.

Ages:
12
9

Smallest age = 9
Frequency = 1
 

Sample Input #2: (from "ages.dat")

3
68
68
68

Sample Output #2: (to "results.dat")

There are 3 ages.

Ages:
68
68
68

Smallest age = 68
Frequency = 3

Sample Input #3: (from "ages.dat")

9
18
49
65
17
22
17
81
17
17

Sample Output #3: (to "results.dat")

There are 9 ages.

Ages:
18
49
65
17
22
17
81
17
17

Smallest age = 17
Frequency = 4


DESIGN for AGES PROGRAM
ALGORITHM (shown on next page in the form of a structure chart).
 
 


 
 
 
 
 

THE ALGORITHM in PSEUDOCODE REPRESENTATION with comments in parentheses:

(Initialize)
smallestAge <-- 125
frequency <-- 0

(Open data files)
Open inFile for reading from
Open outFile for writing to

(Find out how many ages to be entered)
read in numOfAges from inFile
write out numOfAges to outFile

(Find age statistics)
Loop for counter going from 1 to numOfAges:

(Display statistics)
write out "Smallest age = ", smallestAge
write out "Frequency = ", frequency

(Close files)
close inFile
close outFile



The C++ program:

//---------------------------------------------------------------------------------------------------
// Program: Smallest (file processing version)
// Programmed by Funky Winkerbean, 6/97.
// This program reads in a list of ages (integers) from a file and then writes the smallest
// integer in the list along with its frequency to another file.
//---------------------------------------------------------------------------------------------------

#include <fstream.h>
#include <iomanip.h>

void main()
{

}


CASE STUDY #3: This case study contains a sample design and resulting program which requires functions
and procedures.

PROBLEM.
Write an interactive program which uses Newton's Method to calculate the square root of a number and
then displays it next to the square root of the same number found using the C++ function "sqrt". The program
will continue giving the user the option to find more square roots until the user chooses to terminate the program.

BACKGROUND.
There are many methods for actually calculating the square root of a number. If you had no square root
function available to you, you'd have to write an algorithm for finding the square root, but the Babylonians
(ca. 1800-1600 BC) beat you to it! Although the method was attributed to Sir Isaac Newton (hence its
name), it was fully described on clay tablets more than three millennia before Newton was even a gleam
in his mother's eye.
 
CLARIFICATION.
Newton's Method to find the square root of a positive real number (which we'll call num) is described here:

The method might have to apply the formula a few times or many times, depending upon the number and the
original guess entered by the user. Each time the formula is applied and the value of the expression becomes
your "new guess" will count as one "iteration".

INPUT SPECIFICATIONS:
1. The number (for which the square root is to be found) will be a positive real.
2. The user's guess will be a positive real.
3. When given a choice to continue, the user must be required to enter a valid response ('Y', 'y', 'N', or 'n).

OUTPUT SPECIFICATIONS:
1. Display an opening message (of your choice) to the user, telling (in brief) what the program does.
2. Prompt the user for all input--namely, the number, the initial guess, and the answer regarding whether or not
    to continue.
3. For each iteration, list the iteration number, the old guess, and the new guess.
4. After the desired precision has been reached, print out the approximated square root calculated using
    Newton's Method and the square roots calculated using the C++ sqrt function. Write all floating point output
    showing 12 decimal places.
5. Appropriately label all output, as shown in the sample session below, including column headings for data
    in (3).

When the user decides to terminate the program, display a final message such as the one shown in the sample
session below.

SAMPLE SESSION (with output in bold):
Welcome to Newton's Method for Square Roots program.

This program allows you to find the square root of a positive real number by entering
a guess for the square root and then applying Newton's Method for calculating the
square root based on your guess.

Number > 56.03
Guess > 7.5

Iteration #       Old Guess            New Guess
-----------------------------------------------------------------

1                       7.5                        7.48533333333
2                       7.48533333333    7.48531896449
3                       7.48531896449    7.48531896448

Newton's Method: 7.48531896448
C++ sqrt function: 7.48531896448

Do you wish to continue? y/n > y

<< screen clears >>

Number > 2
Guess > 1.4

Iteration #       Old Guess            New Guess
-----------------------------------------------------------------

1                       1.4                         1.41428571429
2                       1.41428571429     1.41421356421
3                       1.41421356421     1.41421356237
4                       1.41421356237     1.41421356237

Newton's Method: 1.41421356237
C++ sqrt function: 1.41421356237

Do you wish to continue? y/n > n

<< screen clears >>
Thanks for using Newton's Method!


Note that the design for this program has been developed in a "modular" fashion by using subroutines. The
design for the "main" part of the program is represented as a structure chart. The design for the subroutines
may be represented using structure charts, pseudocode, or both, according to your instructor's wishes. Notice
that main part of the program and each subroutine have their own variable lists. The procedure "calls", as shown
in the structure chart, also show data flow in, out, and in/out of the procedures.

Part One: The MAIN Program.

Input Variables:       (none)
Output Variables:    (none)
Other Variables:      number         real            number for which square root to be found
                               newGuess     real            user's initial guess for square root

The Main Algorithm:


 

THE MAIN ALGORITHM in PseudoCode:

Call WelcomeUser

Loop while UserWantsToContinue:


Part Two: Designs for Subroutines

In place of PreCondition and PostConditions, for the first program design in which subroutines are used, the students may simply describe the "Task" instead. Later, once "programming by contract" has been discussed, students can be required to define pre- and post-conditions.

Procedure :      WelcomeUser
PreCondition:   none
PostCondition: Message telling what program does has been displayed to screen.
Parameters:      (none)
Local variables:(none)

Algorithm:
Write out a welcome to user and tell briefly what program does.


Procedure :      GetValues
PreCondition:   none
PostCondition: User has entered number and initial guess.
Parameters: In:                (none)
Out:              number           real                  Number whose square root is to be found
                    guess              real                  User's initial guess for square root
In/Out:         (none)
Local variables: (none)

Algorithm:


Procedure :     PrintHeadings
PreCondition:  none
PostCondition: Column headings for output have been displayed at screen.
Parameters:     (none)
Local variables: (none)

Algorithm:


Procedure:      CalculateSquareRoot
PreCondition:  number and newGuess have values entered by user
PostCondition: Newton's Method has been applied to find square rot of number
Parameters:          In:                  number          real              Number whose square root is to be found
         Out:               (none)
         In/Out:            newGuess     real              User's initial guess upon entry; square root from Newton's Method upon exit

Constants:        EPSILON        real      1.0 * 10-9

Local Variables:


Procedure:    PrintSquareRoot
PreCond:      number is original number whose square root is to be found;
                    newtonRoot is square root of number from using Newton's Method.
PostCond:    Square roots from Newton's Method and the Borland C++ square
                    root function have been displayed.
Parameters:

Local variables: none

Algorithm:


Function:    MoreAccuracyNeeded
PreCond:     newGuess has latest estimated square root, oldGuess has
                    previous square root value, EPSILON is tolerance.
Returns:        true if difference btw old and new guesses greater than EPSILON; false otherwise Parameters: Local variables:       continue       Boolean       for return value (true if user wants to continue...)

Algorithm:

Notes: Assume existence of an absolute value function.
 


Function:     UserWantsToContinue
PreCond:      none
Returns:        true if user wants to keep finding square roots
                    false otherwise
Parameters:  (None)
Local variables: Algorithm:
Procedure:      Show Iteration
PreCond:        count, oldGuess, newGuess have values for current iteration.
PostCond:      All three values have been displayed.
Parameters: Local variables: (none)

Algorithm:


The Newton's Method Program in C++:

//-------------------------------------------------------------------
// Newtons.cpp
//
// Programmed by Funky Winkerbean, 6/97.
//
// This is an interactive program which finds the square root of a
// number using Newton's Method.
//-------------------------------------------------------------------

// libraries
//---------------------------
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <iomanip.h>
#include <ctype.h>

// prototypes
//------------------------------
void WelcomeUser();
void GetValues (double&, double&);
void PrintHeadings();
void CalculateSquareRoot (double, double&);
void PrintSquareRoot(double, double);
bool MoreAccuracyNeeded (double, double, double);
bool UserWantsToContinue();
void ShowIteration (int, double, double);

// the main program
//--------------------------------------------------------------

void main (void)
{

}

// Subroutines
//--------------------------------------------------------------

// WelcomeUser
// PreCond:   none
// PostCond: Message telling what program does has been displayed to screen.
//-------------------------------------------------------------------------------------
void WelcomeUser()
{

}
 

// GetValues
// PreCond: none
// PostCond: User has entered number and initial guess.
//------------------------------------------------------------------------------
void GetValues (double& number,
                         double& guess)
{

}
 

// PrintHeadings
// PreCond:   none
// PostCond: Column headings for output have been displayed at screen.
//----------------------------------------------------------------------------------------------------
void PrintHeadings()
{

}

// CalculateSquareRoot
// PreCond:   number and newGuess have values entered by user
// PostCond: Newton's Method has been applied to find square root of number.
//-------------------------------------------------------------------------------------
void CalculateSquareRoot(double number,
                                         double& newGuess)
{

}
 

// PrintSquareRoot
// PreCond:      number is original number whose square root is to be found;
//                     newtonRoot is square root of number from using Newton's Method.
// PostCond:    Square roots from Newton's Method and the Borland C++ square
//                     root function have been displayed.
//---------------------------------------------------------------------------------
void PrintSquareRoot(double number,
                                  double newtonRoot)
{

}
 

// MoreAccuracyNeeded (function)
// PreCond: newGuess has latest estimated square root, oldGuess has
//                 previous square root value, EPSILON is tolerance.
// PostCond: true returned if difference btw the two guesses exceeds EPSILON;
//                  false otherwise.
//-----------------------------------------------------------------------------------------
bool MoreAccuracyNeeded (double newGuess,
                                             double oldGuess,
                                             double EPSILON)
{

}
 

// UserWantsToContinue (function)
// PreCond: none
// PostCond: Returns true if user has indicated that he/she
//                  wishes to continue using Newton's Method; false otherwise.
//---------------------------------------------------------------------------------
bool UserWantsToContinue()
{

}
 

// ShowIteration
// PreCond:   count, oldGuess, newGuess have values for current iteration.
// PostCond: All three values have been displayed.
//----------------------------------------------------------------------------
void ShowIteration (int count,
                               double oldGuess,
                               double newGuess)
{

}


END of CASE STUDIES.