CS 61C (Fall 2007)

Homework Assignment 1

Two exercises, submit as "hw1_1" and "hw1_2".  Due 2:45pm before lecture 9/5/2007.

Goals

This homework is intended to give you practice with fundamental aspects of C—arithmetic, function definition, flow of control, and character input—as well as with converting back and forth between internal and external representations of numeric values.

Submission instructions

Throughout this semester, you will be using the "submit" command to submit your homework and project solutions. For those of you new to Berkeley, you do this as follows:

  1. Make a directory in your home directory whose name matches that specified in the assignment.
  2. Copy the file(s) you wish to submit into that directory.
  3. From within the directory, give the command "submit directoryName".
  4. The submit program will ask you which files in the directory should be submitted (you will usually want to submit them all).

For this assignment, submit your program for exercise 1 (bitcount.c) under the name "hw1_1", and submit your program for exercise 2 (adder.c) as "hw1_2".

Exercise 1

Write a function named bitCount that returns the number of 1-bits in the binary representation of its unsigned integer argument. Add your function to the following program, which is available online in ~cs61c/files/hw/1/bitcount.c, fill in the identification information, and run the completed program.

	/*
		Name: 
		Lab section time:
	*/
	
	#include <stdio.h>
	
	int bitCount (unsigned int n);
	
	int main ( ) {
		printf ("# 1-bits in base 2 rep of %u = %d, should be 0\n",
			0, bitCount (0));
		printf ("# 1-bits in base 2 rep of %u = %d, should be 1\n",
			1, bitCount (1));
		printf ("# 1-bits in base 2 rep of %u = %d, should be 16\n",
			1431655765, bitCount (1431655765));
		printf ("# 1-bits in base 2 rep of %u = %d, should be 1\n",
			1073741824, bitCount (1073741824));
		printf ("# 1-bits in base 2 rep of %u = %d, should be 32\n",
			4294967295u, bitCount (4294967295u));
		return 0;
	}
	
	/* Your bit count function goes here. */

Exercise 2

Write a C program named adder.c that simulates an adding machine. Input to the program will represent integer values, typed one per line without leading or trailing white space. (Don't worry about incorrectly formatted input.) Input should be handled as follows:

Your solution must use the getchar function to read input; it must not use scanf or any of its variations.  You are forbidden to use arrays or strings.  Add a comment at the start of the program that lists your name and lab section.

Example

user inputprogram's output
5
6
0subtotal 11
-3
-2
5
0subtotal 0
13
-13
8
0subtotal 8
0total 19

This problem is a bit tricky. In particular, you should make sure it works correctly when the first two input values are both 0. This should cause the program to print a subtotal of 0, a total of 0 and then exit.

Exercise 3

Register your CPS transmitter, using the procedure described on the CS 61C home page.