There are several topics coming up in the second half of this course for which knowing
a little bit of the C programming language
would be helpful. So today, we're going get you started with C.
A few observations up front
- C is an imperative programming
language, which means, among other things, that it does not have classes. A C program
typically consists of a collection of functions, including the main function. You can also
use global variables, but that's usually leads to bad design and hard-to-maintain code.
- The syntax of C is similar to Java's, because the designers of Java modeled its syntax
after C.
- The variable types available in C are similar to the primitive types in Java: int, char, double, etc.
Study some simple C programs
Each of the following programs illustrates a few key concepts in C. Read each program,
try to predict what output it will produce, and then compile and execute the program.
Talk about the programs, play around with modifying them, etc. You'll need to know how
they all work.
- hello.c—simple variable types and how to print them
- control.c—conditionals and loops (if/else, while, and for)
- strings.c—using null-terminated char arrays
- functions.c—declaring, implementing, and calling functions
- commandline.c—how to use command-line arguments
- fileio.c—file input and output
Write your own program in C
Any non-trivial program will help you practice your C skills. Here are some ideas you could try.
- Just write some simple functions and test them from main. Like:
bool isPalindrome(const char *string);
void encryptWithCaesarCipher(int shift, char *string);
int factorial(int n);
int greatestCommonDivisor(int a, int b);
int occurrencesInFile(char character, const char *fileName);
etc.
- Write a program that takes a text file name as a command-line argument and prints
out a listing showing how many times each letter of the alphabet appears in the file, sorted
from highest count to lowest.
- Implement a bunch of sorting algorithms and a command-line interface for testing them.
- Write a program to take data in a CSV file and compute averages, maxima, minima, etc. (For example,
you could try writing a simple version of
this
assignment from my CS111 class last fall.
- Write a program to do various kinds of encryption and the corresponding decryption.
- Write a terminal-based tic-tac-toe game.
- etc.