Problem Solving in Programming

Tom Kelliher, CS29

Feb. 20, 1997

Two problems to consider:

  1. Echoing a file.

  2. Comparing pairs of strings.

The Steps

  1. The problem statement.

  2. The elements of the problem.

  3. Resolving ambiguity.

  4. Pseudo-code/flowcharting: ``sketching out'' a solution.

  5. Converting the sketch to a concrete program.

Sketch elements:

  1. Sequential execution.

  2. Conditional execution.

  3. Repetitive execution.

Why are these our elements?

Echoing a File

Write a program which opens a disk file and echoes it, line by line, onto the terminal.

How do we go about solving this problem?

A final solution:

#!/usr/contrib/bin/perl -w

# This is a small perl program which demonstrates some file I/O
# operations:
#    o File handles.
#    o Opening a file for input and checking to see if it opened.
#    o Using an opened file for input.
#    o Closing a file.
#
# This program interactively reads a file name and then copies the contents
# of that file to the screen.


print "Enter file name: ";      # Get the file name.
$name = <STDIN>;
chop($name);

open(INPUT, $name) ||           # Try to open the file.
    die "Cannot open $name";

print "Contents of $name:\n";

while ($line = <INPUT>)         # Print the file on the screen.
{
    print $line;
}

close(INPUT);                   # Close the file.

exit 0;

Comparing Pairs of Strings

Write a program which reads pairs of strings from the terminal, compares the strings dictionary-wise, and then prints out if the strings are equal, the first comes before the second, or vice-versa. The program should terminate when it encounters end-of-file on reading the first string.

How do we solve this problem?

A final solution:

#!/usr/contrib/bin/perl -w

print "Enter first string: ";
$string1 = <STDIN>;
if (!$string1)
{
    exit 0;
}
chop($string1);
print "Enter second string: ";
$string2 = <STDIN>;
chop($string2);

while (1)
{
    if ($string1 lt $string2)
    {
        print "$string1 comes before $string2\n\n";
    }
    elsif ($string1 gt $string2)
    {
        print "$string1 comes after $string2\n\n";
    }
    else
    {
        print "The two strings are the same\n\n";
    }

    print "Enter first string: ";
    $string1 = <STDIN>;
    if (!$string1)
    {
        exit 0;
    }
    chop($string1);
    print "Enter second string: ";
    $string2 = <STDIN>;
    chop($string2);

}

exit 0;



Thomas P. Kelliher
Thu Feb 20 07:51:09 EST 1997
Tom Kelliher