Lab: Basic Types

We’ve been using types like int for a while now, but today’s lab will dig deeper into more of the basic types C gives us.

A. Integer Expressions, Revisited

Consider the following C program fragment:

char a = 10;
short b = a * 50;
int c = b * 200;
long d = c / 3;
long long e = a - 11;
printf("a=%d, b=%d, c=%d, d=%ld, e=%lld\n", a, b, c, d, e);

a += c;
b -= e;
c = (char)c;
printf("a=%d, b=%d, c=%d\n", a, b, c);

Exercises

  1. Write down predictions for what you believe the first printf above will output.
  2. Test the first part of the code fragment to check your predictions, and explain any cases you predicted incorrectly.
  3. Write down predictions for what you believe the second printf above will output.
  4. Test the code to check your predictions, and explain any cases you predicted incorrectly.

B. Assignment and Casting

This section asks you to consider the effect of type casting when evaluating C expressions. The exercises below refer to the following C program fragment:

int i = 9;
double j = i / 2;
double k = (double)i / 2;
int l = k * 2;
int m = (int)k * 2;
int n = 1000;
char o = n;
int p = (char)n;
printf("i=%d, j=%lf, k=%lf, l=%d, m=%d, n=%d, o=%d, p=%d\n", i, j, k, l, m, n, o, p);

Exercises

  1. Write down predictions for what you believe the code above will print.
  2. Test the code to check your predictions, and explain any cases you predicted incorrectly.

C. Characters as Numbers

Our reading for today describes how characters in C are represented as numbers. The exercises below ask you to take advantage of this property to perform some useful tasks.

Exercises

  1. Write a C program called letter-check.c that asks a user to type in a single character, which you should read using the getchar() function. Your program should print out a message to report whether the character is a lowercase letter, an uppercase letter, or not a letter. Your implementation should use one if, an else if, and an else; do not use any other conditionals. If you aren’t sure how to use getchar(), refer to our reading or the manpage for that function.
  2. It is sometimes useful to refer to an ASCII table to see what numbers represent which letters. But you can also write a program to do this on your own. Write a program called ascii-table.c that loops over character values from 0 to 127 (inclusive) and prints the number along with the character it represents. Your program should produce output like this example output from the middle of the program’s run, which includes single quotes around each character:
    ...
    63: '?'
    64: '@'
    65: 'A'
    66: 'B'
    67: 'C'
    68: 'D'
    69: 'E'
    70: 'F'
    71: 'G'
    ...
    
  3. Use the output from your ASCII table printing program to look for the following characters and write down the integer values that represent each of them:
    • lowercase a
    • the digit 1
    • percent sign
    • space
    • newline
    • backspace