ANSI C Exercises

These exercises are structured according to the seminal textbook of Brian W. Kernighan and Dennis M. Ritchie: The C Programming Language, second edition, published in 1988. The sections correspond to the book chapters.

The students are expected to always read the corresponding book chapter before attempting to carry out the exercises. Should there be any doubts regarding the chapter contents, attend class in person to consult with the teacher. You should be advancing approximately one chapter every one or two weeks; the earlier you finish the book, the more time you will have to work on your final project. You are expected to have covered the first half, Chapters 1–4 before taking the midterm exam, and the latter half, Chapters 5–8, before taking the final exam, but you may of course proceed faster than that. Going slower would be a very poor idea with potentially dire consequences. Attend class to seek help from the professor whenever you have trouble understanding the book. She learnt to program reading that very same book almost twenty years ago and has kept the book close at hand ever since.

The only supported compilers are variants of gcc. The libraries permitted are those mentioned in the book. The recommended text editor is emacs (downloads available at GNU FTP server, for example). Difficulties arising from the use of some other tools will not be attended by the professor. For Windows users, the installation of either PowerShell or a virtual machine with Linux is recommended.

You are welcome and encouraged to work on the assignments during class hours. That way you will not be alone with your doubts and compiler errors.

A Tutorial Introduction

Read the entire chapter carefully and try out all the example codes on your computer (write them in files with your editor, giving careful thought to each instruction, compile, and execute). Make modifications to the inputs and the code until you understand perfectly how each element affects the behavior of the program.

From this chapter, you must learn and retain the following constructs: main, integer and floating-point variables, while, for, define, simple functions (definitions and usage), return, access to library routines (printf and getchar, putchar), EOF, fixed-size arrays (declaration and access), \0, extern.

You are expected to understand these and to be able to apply these in the remainder of the course. Do not proceed to Chapter 2 if you still have not understood each and every aspect of the first chapter. Attend class and discuss with the professor if some detail turns out to be difficult to understand on your own. You are strongly encouraged to also do all the exercises in the book, not only the mandatory activities on this website.

Exercise 1

Provide the exact printout of each of the following programs, substituting the upper-case symbols by the provided numeric constants.

where X = 1.5, Y = 20, and Z = 3.


where A = 50, B = 12, and C = 7.


where F = 3, T = 40, and S = 3.


After successfully responding the above three tasks, write completely from scratch (no Googling for code is allowed, you may not copy even a single line of code) a program that takes as standard input valid HTML and converts it to plain text, replacing the blanks in all bold-faced texts and section headers by an underscore, omitting the entire content of all scripts, forms, hyperlinks, tables, and images. The input could be something simple like this (make sure you experiment with different inputs to verify that everything works as intended).

If you do not yet know what HTML is and are for some reason unable to browse the web independently to find out, attend class and request for the professors assistence in making sure you have correctly understood the intended input format and program funcionality.

Do not use file manipulation within your program and leave all that to standard input and output handling of the operating system. We will cover file handling from within the C program later on in this course. If the following example code and the execution instructions do not help you get things going, please consult with the professor in class. Technically, if you read attentively the first chapter, you should have figured out all of this by yourself, but as many struggle with reading things with proper thought, this being a first exercise, here's some extra help for the slow starters.

Suppose that the above code is stored in a file called io.c. Compiling in a standard manner with gcc io.c will procude an executable called a.out or a.exe, depending on whether your OS is UNIX-based or not. Now, if we place input text in a regular file and name it input.txt, we can pass it to the program as standard input using < (remember to use the executable name of your operating system; the below works as such on Linux distros and on Mac OS X):

We can also redirect with > the standard output into a file, let's say output.txt, if we wish:

After having thoroughly tested that your program works as intended, attend class and ask the professor to come revise your work. Make sure you have the source code with you and that you are able to compile and execute your program for the professor with any input she suggests. You must be able to explain the purpose of each line of code you present and also to recover from errors that the professor may introduce in your code in order to assure that you completely dominate it.

Programming exercises are graded exclusively during class hours and there will be no special grading sessions nor extensions. If the class ends before you are graded, attend the next session. Do not leave your grading to the last session of the semester so as not to risk not being able to turn in your work for having ran out of time.

Types, Operators, and Expressions

Again, read the chapter as instructed above. From this chapter, you must understand and retain the concepts regarding data types, constants, enumerations, all ANSI C operators, including the ?: conditional, and precedence rules.

Exercise 2

Complete the following programs, placing an adequate single-line expression in place of "..." to obtain the indicated result.

where A is any non-negative integer (valid in ANSI C) and the value of d corresponds exactly to the minimum number of digits that it requires to represent the value of a in base b, where B = 3.


If you have no idea what it means to "express a number in a base", attend class and consult with the professor. She will explain it to you.

where X is any non-negative integer (valid in ANSI C) and the value of y is obtained from the binary representation of x by forcing the bit at position k to one and the bit at position k/2 to zero, where K = 5.


If you have no idea what a "binary representation" is, attend class and consult with the professor. She will explain it to you.

where the printout says "log of p" when the logarithm of p is larger than the square-root of q, and "sqrt of q" when it is not, both terminated by a newline character. P and Q may both take on arbitrary floating-point values.


Having concluded successfully the above exercises, write a (completely original, with no borrowed code whatsoever) program that prints out the binary strings corresponding to the first k prime numbers, all with the same number of bits (with leading zeroes as necessary), one per line, where the value of k is defined as a numerical constant within the source code.

If you have no idea what a "primer number" is, attend class and consult with the professor. She will explain it to you.

Proceed as instructed for the previous programming assignment when you are ready for grading.

Control Flow

In this chapter, you will need to dominate the if statement in all of its variants, as well as the switch statement. Equally you are expected to perfect your understanding of loop structures, including do-while, break, and continue.

Exercise 3

where A = 50 and B = 12.


Make sure you understand why the program prints what it prints. In the exams, you will need to figure out these things by hand, without being able to execute the code.

where A and B are as above, and additionally C = 3.


where A, B, and C are as before.


Having concluded the above activities, write a program (of your own) that reads from standard input and reproduces the content in standard output with the following modifications: all digits are replaced with a single X (regardless of how many digits there are), except for when the number in question is enclosed in one or more sets of parenthesis or quotes of any kind. All punctuation is omitted. Any other input is reproduced as is. The program exists upon encountering an EOF within the input.

The grading procedure is the same as before.

Functions and Program Structure

In this chapter you learn to write modular, reusable code through the use of (simple, iterative, and recursive) functions. You will also structure your code into libraries of your own using header files. You will know how to use preprocessor directives to control which definitions are used within the code.

Exercise 4

Complete the following programs, placing an adequate single-line expression in place of "..." to obtain the indicated result.

where A and B are any non-negative integers (valid in ANSI C) and the printout corresponds to their greatest common divisor.


If you do not know what "greatest common divisor" means and are unable to find out browsing the web, attend class and ask the professor. She will explain it to you.

where T is an arbitrary (null-terminated) ASCII string and the printout indicates whether the string is a palindrome.


If you do not know what "palindrome" means and are unable to find out browsing the web, attend class and ask the professor. She will explain it to you.

Now, identify the printout of the following code.

where A = 3 and B = 2.


Make sure you understand what it prints any why it prints that.

Implement an interactive, basic integer reverse polish-notation calculator that understands all integer-arithmetic operators and single-letter variables, extending the code base provided in the chapter with your original code. Variable assignments are done as "a = 2", while the upper and the lower case characters (e.g., "a" and "A") must refer to the same variable. The calculator needs to issue a warning and request for user confirmation upon variable rewrites, unless the user "forces" the assignment with a special operator "a := 30". The calculator operates until the user quits by typing an EOF. (You may limit to single-digit input if you choose, resulting in a minor loss of points.)

The grading procedure is as before. Read the entire chapter carefully before attempting to carry out this programming exercise.

Pointers and Arrays

This chapter is extremely essential to programmers as it covers the use of pointers.

Exercise 5

Provide the exact printout of each of the following programs, substituting the upper-case symbols by the provided constants.

where A = 5. Make sure you understand what the program does.


where C = ',' (i.e., a character constant). Again, make sure you understand what the program does.


where X = 63.


Write a minesweeper game. The program first defines as a static two-dimensional ten-by-ten integer array as a minesweeper field. Then, the program places a total of k mines pseudorandomly (where k is given as a command-line parameter upon the execution of the program), not permitting duplicate positions, using -1 to denote the locations that contain mines and digits denoting the number of neighbors with a mine for all other positions. Then, then program lets the user "play" minesweeper by selecting positions. After each selection, the map is displayed in standard output, revealing the digits of the revealed positions and using a whitespace instead of zero when no neighbor contains a mine; unrevealed positions are marked with a hashtag. Upon hitting a mine, the game ends. Upon hitting a blank position, the program recursively reveals the continous blank zone (play a minesweeper game until you understand what this means).

Copying code is strictly forbidden and there is no need to do any of it if you have understood the chapter and the previous chapters. Attend class if you need help.


In this chapter you learn to also organize your data in a modular fashion, as a precursor to object-oriented programming.

Exercise 6

Complete the following programs, placing an adequate single-line expression in place of "..." to obtain the desired effect.

where A = 200.0 and B = 40.0, so that the two accounts have the same final balance.


where the functionality is as follows:

elisa$ ./a.out
elisa$ ./a.out 3
3 7 9
elisa$ ./a.out 5
0 3 7 8 9
elisa$ ./a.out 10
0 2 3 4 7 8 9
elisa$ ./a.out 20
0 2 3 4 5 7 8 9
elisa$ ./a.out 100
0 1 2 3 4 5 6 7 8 9


Analyze the following code.

Provide command-line arguments (omitting the name of the executable that is implicitly considered to be the zero-position command-line argument) that will result in the program producing the printout 3 5 6 7.


Implement a tree (i.e., a data structure organized as a tree) for storing user data with the following rules: the tree ordering is alphabetical (left to right) according to the usernames (that are case-insensitive). All inner nodes must have both a left child node and a right child node. Active usernames are only stored in leaf nodes, whereas the inner nodes act simply as routers for the queries. When a new user registers, the system checks whether that username is already in use. If it is, the system prompts the user for another option until a suitable one is found. The registered username is then inserted into the tree (as a new leaf node). Users may also deregister, in which case their username is removed from the tree and will no longer appear to be reserved. A password is also stored upon user registration, and the user must provide the correct password in order to deregister.

Before starting to write any program code for this assignment, make schematic drawings of how your tree will function and post them on discord to discuss. No code will be graded if there was no previous design revision of this type at least two days prior to the attempted grading session; include a screenshot of your discord post in PNG format in your repository named as homework6.png.

Input and Output

In this chapter you finally figure out the full power of input and output, including formatting issues, as well as accessing the local file system to read and write files, as well as error managament with the standard error signalling.

Exercise 7

Complete the following program, placing an adequate single-line expression in place of both occurrences of "..." to make the program count the lines in the specified files.

Expression (a):

Expression (b):

Provide an adequate expression to read data from a structured file (ending at a valid newline character) that first contains a valid UANL student ID number, then the abbreviation of the study program of the student, and then the grade as an integer between zero and one hundred, for example, "1234567 ITS 88".


Write a program that provides access to a database with the persistent storage implemented through one or more locally stored plain-text files, capable of managing records of the time of entry and exit of employees and producing reports of attendance and hours worked. The employees are registered with unique PINs, which they type in upon arrival and whenever they leave the workplace. The system knows which days of the week each employee works and at what time of the day the person is supposed to come to work. System functionality includes, besides the data capture, the generation of reports of attendence, punctuality, and hours worked, and of course the administrative interface for registering new employees, who are automatically assigned a PIN by the system.

The UNIX System Interface

Read the chapter and try to understand it. There are no exercises for the last chapter, as you are supposed to be working on your individual project assignment (talk to the professor on Discord class when you are done with the exercises and want to start working on your project — all project topics must be approved by the professor previous to beginning the work on the project. Also browse through the appendices of the book for ideas. Everyone must have a different topic; no two people may work on similar projects.

Updated April 29, 2021.