Quiz 2 Solution

CS 29

40 pts., Feb. 27

For each problem, design pseudo-code, flowchart, or a perl program to solve it. If you are stuck on either of the problems let me know and I will suggest alterations to the problem(s) which you may work on for partial credit.

Since I did flowcharts in class, I'll give the perl code here.

  1. Count from 2 to 20 by 3's.

    #!/usr/contrib/bin/perl -w
    
    $count = 2;
    
    while ($count <= 20)
    {
        print "$count\n";
        $count = $count + 3;
    }
    
    exit 0;
    

  2. Prompt the user to enter a series of numbers, one at a time, from the keyboard. When the user enters the number 0, stop prompting and print the sum of the positive (> 0) numbers which were previously entered. For each negative number (< 0) entered, print the message Don't do that! .

    #!/usr/contrib/bin/perl -w
    
    $sum = 0;
    
    print "Enter a 0 to quit.\n\n";
    
    print "Enter a number: ";
    $data = <STDIN>;
    
    while ($data != 0)
    {
        if ($data > 0)
        {
            $sum = $sum + $data;
        }
        else
        {
            print "Don't do that!\n";
        }
    
        print "Enter a number: ";
        $data = <STDIN>;
    }
    
    print "The sum of the positive numbers is: $sum.\n";
    
    exit 0;
    



Thomas P. Kelliher
Tue Mar 4 13:16:03 EST 1997
Tom Kelliher