Skip to content

Instantly share code, notes, and snippets.

@prsaya
Last active August 12, 2023 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prsaya/97b57414a33c2c15bc4f3392a8c6aeae to your computer and use it in GitHub Desktop.
Save prsaya/97b57414a33c2c15bc4f3392a8c6aeae to your computer and use it in GitHub Desktop.
C Programming Exercise Solutions

C Programming Exercise Solutions

These are some of the exercises from different sections of the first chapter - CHAPTER 1: A Tutorial Introduction of the book C Programming Language (second edition) by Brian W. Kernighan and Dennis M. Ritchie.

The following are just eight of the exercises and solutions covering various topics of the introductory C programming.

1.1 Getting Started

Exercise 1-1

Run the "Hello, world" program on your system. Experiment with leaving out parts of the program to see what error messages you get.

Solution: ex_1_1.c

1.2 Variables and Arithmetic Expressions

Exercise

1-3 Modify the temperature conversion program to print a heading above the table.

Solution: ex_1_3.c

1.3 The For Statement

Exercise 1-5

Modify the temperature conversion program to print the table in reverse order, fom 300 degrees to 0.

Solution: ex_1_5.c

1.5 Character Input and Output

Exercise 1-8

Write a program to count blanks, tabs and newlines.

Solution: ex_1_8.c

1.6 Arrays

Exercise 1-13

Write a program to print a histogram of the lenghts of the words in its input. It is easy to draw a histogram with the bars horizontal; a vertical orientation is challenging.

Solution: ex_1_13.c

1.7 Functions

Exercise 1-15

Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.

Solution: ex_1_15.c

1.9 Character Arrays

Exercise 1-19

Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.

Solution: ex_1_19.c

1.10 External Variables and Scope

Exercise 1-23

Write a program to remove all comments from a C program. Don't forget to handle quoted strings and character constants properly. C comments do not nest.

Solution: ex_1_23.c


C Programming Exercise Solutions
#include <stdio.h>
/* The Hello world program */
int main()
{
printf("Hello World!\n");
}
#include <stdio.h>
/* Program to print a histogram for the input length of words.
The histogram has horizontal bars. */
int main()
{
int c;
while ((c = getchar()) != EOF)
if (c != ' ' && c != '\n')
printf("[]"); /* the histogram bar is made of these characters */
else
printf("\n");
}
#include <stdio.h>
#define LOWER 0
#define UPPER 300
#define STEP 20
float convert(int fahr);
/* Fahrenheit to celsius conversion - using a function */
int main()
{
int fahr;
printf(" Fahr\tCelsius\n");
printf("================\n");
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
printf("%3d\t%6.1f\n", fahr, convert(fahr));
return 0;
}
/* convert: converts fahrenheit to celsius for given fahr, returns the celsius */
float convert(int fahr) {
return (5.0 / 9.0) * (fahr - 32.0);
}
#include <stdio.h>
#define MAX_LINE_LEN 1000 /* Assume each line is limited to this length */
int get_line(char line[], int maxline);
void reverse(char s[]);
/* Program that reverses its input a line at a time.
Uses a function reverse(s) that reverses the character string s. */
int main()
{
char line[MAX_LINE_LEN];
while((get_line(line, MAX_LINE_LEN)) > 0) {
reverse(line);
printf("%s\n", line);
}
return 0;
}
/* get_line: read a line into s, return length */
int get_line(char s[], int lim)
{
int c, i;
for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* length: returns the length of string s */
int length(char s[])
{
int i;
i = 0;
while (s[i] != '\0')
++i;
return i;
}
/* copy: copy from into to; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
/* reverse: reverses the input string */
void reverse(char s1[])
{
int i, j, len;
len = length(s1); /* get length of the string */
/* make copy of the original string */
char s2[len];
copy(s2, s1);
/* make a reverse of the original string */
j = 0;
for (i = len-1; i >= 0; --i, ++j)
s1[j] = s2[i];
}
#include <stdio.h>
#define MAX_LINE_LEN 200 /* assume lines are limited to this length */
#define ON 1
#define OFF 0
#define ASTERIX '*'
#define SLASH '/'
int get_line(char line[], int maxline);
int get_ix(char s[], int lim, int comment_flag);
void remove_comments(int start_ix, char line[]);
void replace_comments(int start_ix, int end_ix, char line[], int len);
/*
Program to remove all comments in a C program.
Assume
- there can be single comment in a line (can have a single starting and/or ending)
- comments can be leading or trailing only
- a comment can span single or multiple lines
- comments are syntactically correct, i.e., no nested comments
*/
int main()
{
int len, start, start_ix, end_ix;
char line[MAX_LINE_LEN], line_2[MAX_LINE_LEN];
start = OFF;
while((len = get_line(line, MAX_LINE_LEN)) > 0) {
start_ix = get_ix(line, len, ON);
end_ix = get_ix(line, len, OFF);
if (start_ix >=0) {
start = OFF;
if (start_ix > 0) {
remove_comments(start_ix, line);
start = (end_ix >= 0) ? OFF : ON; /* comment can continue to next line */
}
else {
if (end_ix >= 0 && end_ix < len-3) {
/* leading comment (can be followed by code) */
replace_comments(start_ix, end_ix, line, len);
}
else {
/* comment starts and ends or continues */
start = (end_ix == -1) ? ON : OFF;
}
}
}
else if (start == ON) { /* comment started on previuos line */
if (end_ix >= 0) {
/* comment ends on this line */
start = OFF;
if (end_ix < len-3) {
replace_comments(start_ix, end_ix, line, len);
}
}
/* else, comment continues on to next line */
}
else
printf("%s", line); /* code without any comments */
}
return 0;
}
/* replace_comments: replace comments with spaces (or tabs).
this is used for leading comments only */
void replace_comments(int start_ix, int end_ix, char line[], int len)
{
int i;
for (i = 0; i < len; ++i) {
if (i >= start_ix && i <= end_ix+1)
line[i] = (line[i] == '\t') ? '\t' : ' ';
}
printf("%s", line);
}
/* remove_comments: removes the comment from the line */
void remove_comments(int start_ix, char line[])
{
int new_len, i;
new_len = start_ix;
char new_line[new_len + 2]; /* add \n \0 in the end */
for (i = 0; i < new_len; ++i)
new_line[i] = line[i];
new_line[i] = '\n';
++i;
new_line[i] = '\0';
printf("%s", new_line);
}
/* get_ix: find if the line contains comment start or comment end;
return its index, else -1 */
int get_ix(char line[], int len, int flag)
{
int c, i, comment;
char first, last; /* first and second charcters of starting or ending of a comment */
if (flag == ON) {
first = SLASH;
last = ASTERIX;
}
else {
first = ASTERIX;
last = SLASH;
}
comment = OFF;
for (i = 0; i < len; ++i) {
c = line[i];
if (c == first)
comment = ON;
else if (comment == ON && c == last)
return --i;
else
comment = OFF;
}
return -1;
}
/* get_line: read a line into s, return its length */
int get_line(char s[], int lim)
{
int c, i;
for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
#include <stdio.h>
/* Program to convert fahrenheit to celsius and print -
for the fahrenheit 0 to 300 in steps of 20 */
int main()
{
int upper, lower, step;
float fahr, celsius;
lower = 0;
upper = 300;
step = 20;
fahr = lower;
printf(" Fahrenheit Celsius\n");
printf("---------------------\n");
while (fahr <= upper) {
celsius = (5.0 / 9.0) * (fahr - 32) ;
printf(" %3.0f %6.1f\n", fahr, celsius);
fahr = fahr + step;
}
}
#include <stdio.h>
/* Fahrenheit to celsius table - prints in reverse,
for the fahrenheit 300 to 0 in steps of 20 */
int main()
{
int fahr;
printf("Fahrenheit\tCelsius\n");
for (fahr = 300; fahr >= 0; fahr = fahr - 20)
printf(" %3d\t\t%6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32));
}
#include <stdio.h>
/* Program to count tabs, blanks and newlines in the input */
int main()
{
int c, tb, bl, nl;
nl = 0;
bl = 0;
tb = 0;
while ((c = getchar()) != EOF)
if (c == '\n')
++nl;
else if (c == '\t')
++tb;
else if (c == ' ')
++bl;
printf("Tab, blank and newline counts are %d %d %d\n", tb, bl, nl);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment