CSci 230: Computing Systems Organization
Home Syllabus Readings Assignments Tests

Assignment 2: C introduction

Due: 5:00pm, Friday, September 2. Value: 30 pts.

Below is a program [text file] that reads a single line from the user and displays the number of characters in that line. For example, if the user enters the line hello world and then presses enter, the program displays the number 11 (five letters in each word, plus the space).

#include <stdio.h>

int main() {
    int count;
    char c;

    printf("Input: ");
    count = 0;
    c = getchar();
    while (c != '\n') {
        count++;
        c = getchar();
    }
    printf("%d\n"count);
    return 0;
}

Your job is to write four different programs based on this one, as described below. Important: You may not use any built-in C functions except for getchar() and printf(). You should submit your solution to each problem in the file named in the problem title.

Problem 1: spaces.c

Count the number of spaces in the line typed by the user. Thus, for hello world, the output should be 1, since there is just one space between the two words.

I have prepared a separate page detailing how you can compile a C program in the Linux lab.

Problem 2: square.c

Assuming the user types a number below 10000, display the square of the number entered by the user. For example, if the user types 250 and the Enter key, the program should respond with 62500.

Here, you'll need to convert the digits typed by the user into a number. You might find the following pseudocode useful for your inspiration:

num ← 0
while there are more digits:
    num ← 10 · num + next digit
display num · num

You'll need to convert a digit character to its corresponding number to make this happen. You could simply treat the character as a number in an expression, as in i = c; where i is an int and c is a char. But its ASCII code will be used, so if c holds the digit '1', i will receive its ASCII value, which is 49. Fortunately, the ASCII code assigns the digits 0 through 9 successive values from 48 ('0') through 57 ('9'), and so you can perform this conversion by simply subtracting 48 from the character value.

Problem 3: words.c

Count the number of words in the line typed by the user, defined as the number of sequences of non-space characters — or, equivalently, the number of times a non-space character is preceded either by a space or by the beginning of the line. Here are some sample inputs and the corresponding outputs.

InputOutput
hello world2
hello   world2
4 words - right?4
   word   word   2

Problem 4: sum.c

Assuming the user types several numbers separated by single spaces, display the sum of the numbers entered. For instance, given the input 54 23 10, the output should be 87. You can assume that there are no more than 10 numbers, each of which is less than 1,000,000.