04 November 2012

Part 9 - Counting words in the input

Topics Covered:

Counting words
The bool type and stdbool.h
More about the PATH variable



Watch video >>


Downloadable Files

wc.c

words2lines.c


Exercises

1. Compile and run the program wc.c on your computer. Try running the program with input from the keyboard as well as by using a redirection operator.

2. The program words2lines.c should read from the standard input and print each word in the input on its own line in the output. Use the skeleton provided and complete the program.

Questions

1. A bool variable has the value true or false. What should the final result of the variable test be after the assignments in the following lines marked (a) through (f)?

#include <stdbool.h>
int main()
{
    bool test;
    test = false;
    test = 0;            // (a)
    test = 0.0;          // (b)
    test = 0.0000000001; // (c)
    test = -100;         // (d)
    test = '\0';         // (e)
    test = '0';          // (f)
    return 0;
}

2. Write a C program to answer the questions in Question 1 by direct experimentation. The following if/else construction will print the word "true" or "false" depending on the value stored in test:

if (test)
    printf("true\n");
else
    printf("false\n");

If you prefer, use the following shorthand version of the above construction:

printf("%s\n", (test ? "true" : "false"));

3. In C, the loop control and branching expressions as in if (expr), while (expr), etc. are considered to be "true" if expr is anything other than 0. With this in mind, what should be the output of the following program?

#include <stdio.h>

int main()
{
    unsigned char c = 1;
    while (c) {
        if (c)
            printf("%4d ", c);
        c++;
    }
    printf("\n");
    return 0;
}


How does the output change if the variable c has the type bool rather than unsigned char?


No comments:

Post a Comment