ReferencesTop6 Notes7 Assignments

7 Assignments

Assignment Points Due Date
Class Starts January 21
Getting Started 15 January 28
Fibonacci Series 15 February 4
Robots 15 February 18
Binary Numbers 20 March 4
Bowling 30 March 25
Trip Planning 30 April 1
Multiple Returns 30 April 15
Linked List 40 May 6
Route Finder Optional 30 May 6
Final Exam May 13

7.1 Getting Started

7.1.1 Getting Started -- Programs

  1. hello.c
    
    /* Program to print "hello, world"                  */ 
    /* L Taber   October 13, 1992   PCC                 */
    /* Kernighan & Richie "The C Programming Language"  */ 
    /* Copyright 1978  page 6                           */
    
    #include <stdio.h> 
    
    main() 
    { 
    printf("hello, world\n"); 
    }
    
    When you run it is should look like this:
    hello, world
    
     
  2. limits.c
    /*H*****************************************
     * limits.c   
     * Louis Taber, PCC, Dec 14, 2000
     *******************************************/
    
    #include <limits.h>
    
    main()
    {
    printf( "Minimum and maximun values for"
            " various types.\n\n" );
    printf( "%d <= char <= %d\n", CHAR_MIN, CHAR_MAX );
    printf( "0 <= uchar <= %u\n", UCHAR_MAX );
    printf( "%d <= short <= %d\n", SHRT_MIN, SHRT_MAX );
    printf( "0 <= ushort <= %u\n", USHRT_MAX );
    printf( "%d <= int <= %d\n", INT_MIN, INT_MAX );
    printf( "0 <= uint <= %u\n", UINT_MAX );
    printf( "%ld <= long <= %ld\n", LONG_MIN, LONG_MAX );
    printf( "0 <= ulong <= %lu\n\n", ULONG_MAX );
     
    }
    
    When you run it is should look something like this:
    Minimum and maximun values for various types.
    
    -128 <= char <= 127
    0 <= uchar <= 255
    -32768 <= short <= 32767
    0 <= ushort <= 65535
    -2147483648 <= int <= 2147483647
    0 <= uint <= 4294967295
    -2147483648 <= long <= 2147483647
    0 <= ulong <= 4294967295
    
    
    Please note the limits of your compiler!
  3. modular program with math functions. Run the following 2 module program with a header. I compile it with the following command:
    gcc -o mod mod-main.c mod-sub.c -lm
    
    The "-lm" is used to bring in the math library.
    /*H******************************************************
     *   Program to check out development environment 
     * 
     * Louis Taber
     * December 5, 2000
     * CIS265
     *
     * mod-main.c
     *
     ********************************************************/
    
    #include <stdio.h>
    #include <math.h>
    #include "mod.h" 
    
    float sinandcos( float, float);
    int   iadd(int, int);
    
    int main(void)
    {
    int   a, b = CONSTANT_B, c = CONSTANT_C;
    float x, y = CONSTANT_Y, z = CONSTANT_Z;
    
    /* Print out header */
    
    printf("Your-name\n");
    printf("CIS 265 - Spring 2001 - Taber Lab - 4.1\n\n"); 
    
    /* Integer subroutine and constants */ 
    
    printf("b= %d, %08X    c= %d,  %0o\n", b, b, c, c);    
    a = iadd(b,c);
    printf("a = %07d\n\n",a);
    
    /* Floating point subroutine and constants */ 
    
    printf("y= %f, %18.12g\nz= %f, %18.12g\n\n", y, y, z, z);    
    x = sinandcos(y,z);
    printf("x=%+18.12lg\n", x);
    
    return 0;
    }
    
    
    and
    /*H******************************************************
     *   Program to check out development environment 
     * 
     * Louis Taber
     * December 5, 2000
     * CIS265
     *
     * mod-sub.c
     *
     ********************************************************/
    
    #include <math.h>
    
    int 
    iadd(int b, int c)
    {
    return b+c;
    }
    
    float
    sinandcos(float y, float z)
    {
    return sin( y ) + cos( z );
    }
    
    and
    /*H******************************************************
     *   Program to check out development environment 
     * 
     * Louis Taber
     * December 5, 2000
     * CIS265
     *
     * mod.h
     *
     ********************************************************/
    
    #define CONSTANT_B 12 
    #define CONSTANT_C 18
    #define CONSTANT_Y 1.1111111111111111111111
    #define CONSTANT_Z 2.2222222222222222222222
    
    
    My output looks like:
    Your-name
    CIS 265 - Spring 2001 - Taber Lab - 4.1
    
    b= 12, 0000000C    c= 18,  22
    a = 0000030
    
    y= 1.111111,      1.11111116409
    z= 2.222222,      2.22222232819
    
    x=    +0.28987121582
    

Mark the output of the multiple module program with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.2 Fibonacci Series

 

Write a program that prints out the first 21 elements in the Fibonacci Series.

This program will probably use the for loop.

The series starts with a one(1) and a one(1). Each subsequent number is the sum of the previous two numbers.

So:

Number the first number in the series, the zero with a zero. With this numbering LCD(Fn,Fm) = F(LCD(n,m)).

Your program need to print the following:

Other requirements:

Hints:

  1. Do NOT use recursion. Write an iterative program.

Study areas:

Extra credit:

Make sure that your program runs and prints the twenty-first Fibonacci numbers. Mark your output with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.3 Robots

 

This program will probably use the while loop.

You are in charge of a moon colonization program. It has been determined that the only way to do the project is with robots. The robots know how to build more robots. After there are enough robots people can also be sent to the moon.

Each robot collects materials for two (2) months. During this time it has collected enough materials to build three (3) robots. It takes one month to build a robot. As soon as it is built (and running) it starts collecting materials to build robots its self.

The robot that just finished building the three(3) robots will normally start collecting materials again too.

Stop collecting new material for robots when you have 200 or more robots. Some robots will move directly from being built to being idle. So if the total number of robots at the end of one month equals or exceeds 200, no robots should start collecting the following month. If a robot had started collecting material, let the robot complete its cycle.

Start with one(1) robot, but use a preprocessor #define statement to set this value.

Write a program that computes the number of robots and keeps track of what they are doing each month.

Print out the number of robots at the beginning of each month. The total should include both old robots and the robots that have just been built and their assignments.

Your program need to print the following:

Other requirements:

Hints:

  1. c1=1;
    while( c1+c2+b1+b2+b3 )
      {
      ...
      }
    
  2. Think about the similarities of this program and Fibonacci series program Lab: 7.2. The programs have a lot in common.
  3. Make sure that your program runs until all of the robots are idle.

Study areas:

Extra credit:

Mark your output with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.4 Character processing

 

Looking through a stream of characters for a specific pattern or sequence is frequently done by computers. For an example, think about what a compiler does with a program. It needs to look for comments, operators, identifiers, and constants.

In this lab I want you to do a bit of text processing yourself. (Not quite a compiler for sure.) You can use your standard input, or if you wish to read ahead in your book and process the input from a file. Both approaches are fine. Extra credit will be given if you take the "UNIX" approach of looking on the command line for a file name, and if it exists use it, otherwise use the standard input (keyboard or redirected input).

At the start of your program print out:

Write a program that processes an input stream doing the following:

After your program reads and processes a line it needs to prints out the following information:

At the end of the file print out the following totals:

Hint:

#include <stdio.h>
#define TRUE 1
#define FALSE 0
main()
{
int c;
int comment = FALSE;
 while( (c=getchar()) != EOF )
  {
  if( c == ';' ) 
    {
    comment = TRUE;      
    }
  if( c == '\n' )
    {
    comment = FALSE;
    }
  if( comment == TRUE ) continue;
  putchar(c);
  }
}

Given the following example input.

This has a comment; And the comment is discarded. 101010010010
A hidden binary number 9991999; Of 1
1010109AAAA10; The last binary number is decimal 2 

This output should be in the following format:

No Binary Number       15 Letters           0 Digits
               1       19 Letters           7 Digits
               2        4 Letters           9 Digits
3 Lines --------------------------------------------
               3       38 Letters          16 Digits  

Test your program with the following sample data set.

; This is the test date for the lab "Stream"
; Louis Taber  3/29/98
; CSC130  Pima Community College
                           ; Blank Line
ABCDEFGHIJKLMNOPQRSTUVWXYZ ; Uppercase letters
abcdefghijklmnopqrstuvwxyz ; Lower case letters
1234567890                 ; Digits - binary number: 0
11111111                   ; Binary number 255
1000000000000000           ; This may give you 
                           ;   a negative number (OK)
                           ;   Do you know why?
10101010a10101010b111      ; Last binary number: 7
[]|--+=*#@                 ; Some special symbols
The last Line

It is available by at
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/numbers.dat.

Turn in a copy of your program and its output when used with the above test data marked with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.5 Bowling program

 

Write a program that reads a data file and uses an array to figures out the bowling scores. In bowling, 10 pins are set up for each frame and the player gets two chances to knock them down. If the player knocks down less than 10 ten pins down with the two balls his/her score for that frame is the total number of pins knocked down. If the player knocks down all of the pins with two balls, (a spare, marked with a "/") the player gets 10 points plus the number of pins knocked down with the next ball. If the player knocks down all of the pins with one ball, (a strike, marked with an "X") the player gets 10 points plus the number of pins knocked down with the next two balls.

At the beginning of your program printout the following:

  1. Your name
  2. CIS265 Louis Taber
  3. Lab: 7.3: Bowling.

Your input data will be:

  1. Players name
  2. Number of pins knocked down with a ball.
  3. -1 For end of game (next record new players name)
  4. -2 For end of data file

For each game print out all ten frames. For each frame print out the following:

  1. the number of pins knocked down for each ball.
  2. If the frame was a strike or a spare.
  3. The running score for the player.

For example: (Print error messages when you find the error.)

Name:  John Doe
Frame  1:   Ball 1: 10   Ball 2: none  Strike    Score:   20
Frame  2:   Ball 1:  5   Ball 2:  5    Spare     Score:   36
Frame  3:   Ball 1:  6   Ball 2:  0              Score:   42
Frame  4:   Ball 1: 10   Ball 2: none  Strike    Score:   54
Frame  5:   Ball 1:  0   Ball 2:  2              Score:   56
Frame  6:   Ball 1:  0   Ball 2:  1              Score:   57
Frame  7:   Ball 1:  4   Ball 2:  5              Score:   66
Frame  8:   Ball 1:  4   Ball 2:  6    Spare     Score:   83
Frame  9:   Ball 1:  7   Ball 2:  3    Spare     Score:  103
Frame 10:   Ball 1: 10   Ball 2: none  Strike    Score:  133
Extra Ball 1: 10     Extra Ball 2: 10

You will also need to print out your results using the "traditional" format for a bowling score sheet.

Name:  John Doe

  ( Error message will go here -- if there are any )

___1___2___3___4___5___6___7___8___9__10___
| |X|5|/|6|0| |X|0|2|0|1|4|5|4|/|7|/|X|X|X|
| 20| 36| 42| 54| 56| 57| 66| 83|103|  133|   
-------------------------------------------

Remember that after the last frame, up to two additional balls may be played. (Two for a strike and one for a spare.) Your program also needs to check for errors in the input data: The types of errors your program needs to look for are:

Run your program with the test data available at: Test your program with the following sample data sets. The first one has (hopefully) no errors. It is available by HTTP at
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/bowling.dat.

The second one has lots of errors, to check your error handling code. It is available by HTTP at
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/bwerror.dat.

An example program for reading the data file is available at:
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/read-bowling.c Here is the example program:

/* Louis Taber 3/26/2001
 *
 * --  Read bowling info
 *
 * Third example program for fscanf()
 * example of fscanf, errno, perror
 *                               */

#include <stdio.h>
#include <errno.h>

#define TRUE 1

int extern errno;

int main(int argc, char *argv[])
{
FILE *fp;
int score;
int balls;
char bowler[200];
char blanks[200];

if( argc == 1 )   /* No arguments -- use std input */
  {
  fp= stdin;
  }
else
  {
  if((fp = fopen( argv[1], "r")) == NULL)
    {
    printf(" Error(%d): %s\n", errno, strerror(errno)); 
    printf("%s(line %d): fopen error: %s\n",
           __FILE__, __LINE__,  argv[1]);
    return 1;
    }
  }


while( TRUE ) 
  {
  fgets(bowler, sizeof(bowler), fp);
  balls = 0;
  while( TRUE )
    {
    fscanf(fp, "%d", &score );
    if( score < 0 ) break;
    balls ++;
    printf(" %02d", score);
    }
  fgets(blanks, sizeof(blanks), fp);
  printf("\nballs: %4d  %s\n", balls, bowler);
  if( score == -2 ) break;
  }

fclose(fp);
return 0;
}

Mark your output two printouts and your listing with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.6 Cross Country Trip Simulation

 

Given a list of distances and gas prices, simulate a cross country trip in a car that has a 20 gallon tank and gets 20 miles to the gallon.

This means that your car can go 400 miles between gas stations.

The basic parameters for the trip are as follows. They should be #defined in your program so that they are easy to change.

  1. The car gets 20 miles to the gallon.
  2. The gas tank holds 20 gallons.
  3. The tank starts out with 20 gallons in it.
  4. You can run the tank "dry" as you pull into the next station.
  5. The trip is 3000 miles long.

At the beginning of your program print out:

  1. Your name
  2. CIS265 Louis Taber
  3. Lab: 7.3: Cross Country Trip

Figure out the lowest cost trip. You can "coast" into the next gas station on "vapors". I wouldn't want to do a real trip this way. (Though, I have run out of gas at least 3 times as I pulled into a gas station! This is NOT a recommendation.) Each time that you purchase gas print the following (in a table):

  1. The current distance.
  2. How much gas you purchased.
  3. The cost of the gas.
  4. How much gas was in the tank at prior to the purchase.
  5. How much gas is in the tank at after the purchase.

At the end of the trip, print out the following:

  1. Total gas purchased (gallons and dollars).
  2. Average cost of the gas per gallon.
  3. Miles per dollar.
  4. Remaining gas in tank. (Should be zero).

Read the data from a file. In my data file, the information is in two fields per line (or record). The first field is the distance to gas station from the departure point. The second field is the cost of gas at that point in dollars per gallon. (You may note some price gouging going on on this list.) The data set follows:

  20 1.25
 300 0.90
 350 2.50
 520 4.25
 730 0.70
1060 4.17
1350 2.59
1390 1.11
1500 4.25
1530 3.24
1560 2.11
1590 1.73
1600 0.80
1800 5.97
2000 0.95
2250 2.34
2411 1.47
2549 1.09
2786 4.17
2900 0.99


The data set is available by HTTP from
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/trip.dat An example program for reading the data file is available at:
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/read-gas.c Here is the example program:

/* Louis Taber 3/26/2001
 *
 * --  Read trip info
 *
 * Second example program for fscanf()
 *
 *                               */

#include <stdio.h>
#include <errno.h>

int extern errno;

int main(int argc, char *argv[])
{
FILE *fp;
int milepost;
float price;


if( argc == 1 )   /* No arguments -- use std input */
  {
  fp= stdin;
  }
else
  {
  if((fp = fopen( argv[1], "r")) == NULL)
    {
    perror(argv[1]);
    printf(" Error number: %d\n", errno); 
    printf(" Error: %s\n", strerror(errno)); 
    printf("%s(line %d): can't open: %s\n",
           __FILE__, __LINE__,  argv[1]);
    return 1;
    }
  }

do
  {
  if( fscanf( fp, "%d %f \n",
                  &milepost, &price) <0 ) break;
  printf(" %6d %8.3f\n ",
         milepost, price);
  }  while( milepost != 0 );

fclose(fp);
return 0;
}

Turn in:

mark with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.7 Returning multiple values

 

Subroutines and functions often need to return more than one value, even simple ones. For example, a return value and error conditions. "C" uses pass by value for its function calls. This means that to get more than one value returned you need to pass the address of where you want the return value if you have more then one.

In this lab I want you to go quite a bit further than you did in lab 7.4: Numbers/Character Processing. I want you to write a program that returns (as its return value) the next number received as characters into its standard input.

The signed numbers can be in several formats:

Binary 0b1010101 Must start with a 0b and only 0 & 1
Octal 01234567 Must start with a zero and only 0-7
Decimal 123456789 Must start with 1-9
Hexadecimal 0xhhhhhhh h is one of 0-9 & A-F (Uppercase)

If there is a "-" directly prior to the number it is a negative number.

0bA and 0xG can be considered a

zero binary and zero hexadecimal number respectively.

Numbers are terminated by any character that is not part of their set of characters. For example, an octal number is terminated by a 8 or a 9 and a binary number would be terminated by a 2. This terminating character should be "put back" with a call to ungetchar() so it can be used in the next number. For example, 0123456789 will first return a octal number of 12345678 and then a decimal value of 8910.

A hexadecimal number can be terminated by any lower case letter.

Spaces, new lines, tabs, G-Z, and a-z terminate all numbers. Any special character or non-printing character also terminate all numbers.

The function prototype should look something like this:

int getnumber(int *radix, int *characters_read);
radix should return the following values:
0 No number found
2 Binary number
8 Octal number
10 Decimal number
16 Hexadecimal number
characters_read need to have the total number of character

read from the input minus any put back.

At the start of your program print out:

Write a program that process an input data doing the following:

Given the following example input.

abcde 0b0101 -012 123 0x05A -123

This output should be in (about) the following format:


Your name
CIS265  Louis Taber
Lab: 7.7: Multiple return values

Binary                      5
Octal                     -10
Decimal                   123
Hexadecimal                90
Decimal                  -123

EOF reached  ****************
Binary total                5
Octal total               -10
Decimal total               0
Hexadecimal total          90
Grand total                85
Total characters read      35

Test your program with the following sample data set.

This is the test data for the multiple returns lab.
If you have sixteen bit integers, create your own file.

0b11111 037 31 0x1F  Four thirty ones
-0b11111 -037 -31 -0x1F  Four negative thirty ones
2147483647 Decimal max
-2147483647 Almost decimal min  (sum now zero)

Run together numbers.
0b12 (Binary one, decimal two)
078  (Octal seven, decimal eight)
0xA0b10 (Hexadecimal One Hundred sixty, decimal ten)
This is the last line, no numbers

It is available by HTTP at
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/return.dat.

Extra credit: Handle INT_MIN (-2147483648) correctly.

Turn in a copy of your program and its output when used with the above test data marked with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.8 Linked Lists and Structures

Write a "C" program that uses structures and pointers. This is intended to be a program to work on your linked list and structures skills.

Study areas:

Set up a double linked list with forward and backward pointers with dynamically allocated structures. The structure should have 3 elements. A character, a forward link, and a backwards link.

The program, without comments was, for me 125 lines.

At the start of your program print out:

Then it needs to:

For the following input:

abcdzyxw
F4B4FQ

your program should print:

Your name
CIS265  Louis Taber
Lab: 7.8: Linked Lists and Structures

8
abcdwxyz
zyxwcba
abcxyz
15

Hints:

Test your program with the following sample data set.

8888B8888F   
qwertyuiopasdfghjklzxcvbnmFB
2222222222222F111111111111F1
qwertyuiopasdfghjklzxcvbnmFB
qwertyuiopasdfghjklzxcvbnmFB
X


It is available by HTTP at
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/link.dat.

Turn in a copy of your program and its output when used with the above test data marked with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).

7.9 Find a route

 

This program will use scanf (fscanf) to input data and a number of arrays to process the data.

The program will first input a data set that the first part is composed of records that have four data elements. The first two are zip codes, the third is the distance, in miles, between the two zip codes. The last field is a comment. These records represent a rode between two cities. A route, in this case can be traveled either direction. All three values will be integers.

This section of the data is terminated by a record with all three values set to zero.

The next section in the data file is a set of records that have two zip codes. For each pair of zip codes find a route between the zip codes. There is a third field that has a comment.

Be able to get your data both from the standard input or a specified file name.

The data set is "guaranteed" to have less than 500 roads and less than 250 zip codes. But, use #define pre-processor statements to define these limits (if you need limits).

For extra credit, find multiple routes and select the shortest (and longest?) route.

At the start of your program print out:

Then for each route requested print out:

At the end of your program print the following summary:

Given the following example input.

85716 95949  820 Tucson-GrassValley
99801 95949 1400 GrassValley-Alaska
00000 00000   00
85716 99801      Tucson-Alaska
85716 34562      Tucson-?
00000 00000

This output should be in (about) the following format:


Your name
CIS265  Louis Taber
Lab: 7.7: Find a route

3 roads read in.

1. Route from 85716 to 99801
   85716 to 95949   820 miles
   95949 to 99801   400 miles
** 85716 to 99801  1240 miles

2. Route from 85716 to 34562
** No route available: zip 34562 not found.

Summary:
   1 route(s) found.  Total 1240 miles.  Total 2 roads.
   1 route not found 

Test your program with the following sample data set. It is available by HTTP at
http://lt.tucson.az.us/ltaber/hl2.2009-spring/c/route.dat.

Study areas:

Hints:

Turn in a copy of your program and its output when used with the above test data marked with:

Please turn your lab in to me, Louis Taber, during class, or slide it under the door of Santa Rita Building room A-105 (my office).


Instructor: Louis Taber, louis.taber.at.pima at gmail dot com (520) 206-6850
My web site in California
The Pima Community College web site

ReferencesTop6 Notes7 Assignments