[go: up one dir, main page]

0% found this document useful (0 votes)
35 views13 pages

C Exercises

Uploaded by

myamo2613
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views13 pages

C Exercises

Uploaded by

myamo2613
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Exercises 29

*Q: Is it really true that there’s no limit on the length of an identifier? [p. 24]
A: Yes and no. The C standard says that identifiers may be arbitrarily long. However,
compilers are only required to remember the first 31 characters. Thus, if two
names begin with the same 31 characters, a compiler might be unable to distin¬
guish between them.
To make matters even more complicated, the C standard has special rules for
external linkage >-18.2 identifiers with external linkage; most function names fall into this category. Since
these names must be made available to the linker, and since some older linkers can
handle only short names, the standard says that only the first six characters are sig¬
nificant. Moreover, the case of letters doesn’t matter. As a result, ABCDEFG and
abcdefh might be treated as the same name.
Most compilers and linkers are more generous than the standard, so these
rules aren’t a problem in practice. Don’t worry about making identifiers too long—
worry about making them too short.

Q: How many spaces should I use for indentation? [p. 26]


A: That’s a tough question. Leave too little space, and the eye has trouble detecting
indentation. Leave too much, and lines run off the screen (or page). Many C pro¬
grammers indent nested statements eight spaces (one tab stop), but four is also
common. Indenting eight spaces is probably too much, especially when some
screens and printers are limited to 80 columns. Studies have shown that the opti¬
mum amount of indentation is three spaces. I’ll use two spaces in this book, how¬
ever, so that programs will fit within the margins.

Exercises
Section 2.1 1 Create and run Kernighan and Ritchie’s famous “hello, world” program:
#include <stdio.h>

main()
{
printf("hello, world\n");
}
Do you get a warning message from the compiler? If so, what’s needed to make it go away?

Section 2.2 2. Consider the following program:


#include <stdio.h>

main()
{
printf("Parkinson's Law:\nWork expands so as to ");
printf("fill the time\n");
printf("available for its completion.\n");
return 0;
}
30 Chapter 2 C Fundamentals

(a) Identify the directives and statements in this program.


(b) What output does the program produce?

3. Write a program that uses printf to display the following picture on the screen:

★ *

* *

Section 2.4 4. Condense the dweight.c program by (1) replacing the assignments to height,
length, and width with initializers and (2) removing the weight variable, instead cal¬
culating (volume + 165) / 166 within the last printf.

5. Write a program that computes the volume of a sphere with a 10-meter radius, using the for¬
mula v = 4/37tA Write the fraction 4/3 as 4.0/3 . 0. (Try writing it as 4/3. What hap¬
pens?)

6. Write a program that declares several int and float variables—without initializing
them—and then prints their values. Is there any pattern to the values? (Usually there isn’t.)

Section 2.5 7. Modify the program of Exercise 5 so that it prompts the user to enter the radius of the
sphere.

8. Write a program that asks the user to enter a dollar amount, then displays the amount with
5% tax added:
Enter a dollar amount: 100.00
With 5% tax added: 105.00

Section 2.6 9. Modny Exercise 7 by making PI a macro that represents the value of n.

Section 2.7 10. Which of the following are not legal C identifiers?
(a) 100_bottles
(b) _100_bottles
(c) one_hundred_bottles
(d) bottles_by_the_hundred_

11. Which of the following are keywords in C?


(a) for
(b) If
(c) main
(d) printf
(e) while

Section 2.8 12. How many tokens are there in the following statement?

a=(3 *q-p*p)/3 ;

13. Insert spaces between the tokens in Exercise 12 to make the statement easier to read.
42 Chapter 3 Formatted Input/Output

printf("Enter a number: ");


scanf("%d", &i);

Suppose that the user enters a valid number, followed by nonnumeric characters:

Enter a number: 23foo

In this case, scanf reads the 2 and the 3, storing 23 in i. The remaining charac¬
ters (f oo) are left to be read by the next call of scanf (or some other input func¬
tion). On the other hand, suppose that the input is invalid from the beginning:

Enter a number: foo

In this case, the value of i is undefined and f oo is left for the next scanf.
What can we do about this sad state of affairs? Later, we’ll see how to test
detecting errors in scant >22.3 whether a call of scanf has succeeded. If the call fails, we can have the program
either terminate or try to recover, perhaps by discarding the offending input and
asking the user to try again. (Ways to discard bad input are discussed in the Q&A
section at the end of Chapter 22.)

Q: I don’t understand how scanf can “put back” characters and read them
again later, [p. 38]
A: As it turns out, programs don’t read user input as it is typed. Instead, input is stored
in a hidden buffer, to which scanf has access. It’s easy for scanf to put charac¬
ters back into the buffer for subsequent reading. Chapter 22 discusses input buffer¬
ing in more detail.

Q: What does scanf do if the user puts punctuation marks (commas, for exam¬
ple) between numbers?
A: Let’s look at a simple example. Suppose that we try to read a pair of integers using
scanf:

printf("Enter two numbers: ");


scanf("%d%d", &i, &j);

If the user enters

4,28

scanf will read the 4 and store it in i. As it searches for the beginning of the sec¬
ond number, scanf encounters the comma. Since numbers can’t begin with a
comma, scanf returns immediately. The comma and the second number are left
for the next call of scanf.
Of course, we can easily solve the problem by adding a comma to the format
string if we’re sure that the numbers will always be separated by a comma:

printf("Enter two numbers, separated by a comma: ");


scanf("%d,%d", &i, &j);
Exercises 43

Exercises
Section 3.1 1. What output do the following calls of printf produce?
(a) printf("%6d,%4d", 86, 1040);
(b) printf ("%12.5e” , 30.253);
(c) printf ("%.4f" , 83.162) ;
(d) printf ("%-6.2g" , .0000009979);

2. Write calls of printf that display a float variable x in the following formats.
(a) Exponential notation; left-justified in a field of size 8; one digit after the decimal point.
(b) Exponential notation; right-justified in a field of size 10; six digits after the decimal
point.
(c) Fixed decimal notation; left-justified in a field of size 8; three digits after the decimal
point.
(d) Fixed decimal notation; right-justified in a field of size 6; no digits after the decimal
point.

Section 3.2 3. For each of the following pairs of scanf format strings, indicate whether or not the two
strings are equivalent. If they’re not, show how they can be distinguished.
(a) " %d" versus " %d
(b) " %d-%d-%d." versus "%d
(c) " % f" versus " %f
(d) "%f,%f" versus "%f,

4. Write a program that accepts a date from the user in the form mm/dd/yy and then displays
it in the form yymmdd:
Enter a date (mm/dd/yy): 2/17/96
You entered the date 960217

5. Write a program that formats product information entered by the user. A session with the
program should look like this:

Enter item number: 583


Enter unit price: 13.5
Enter purchase date (mm/dd/yy): 10/24/95

Item Unit Purchase


Price Date
583 $ 13.50 10/24/95

The item number and date should be left justified; the unit price should be right justified.
Allow dollar amounts up to $9999.99. Hint: Use tabs to line up the columns.

6. Books are identified by an International Standard Book Number (ISBN) such as 0-393-
30375-6. The first digit specifies the language in which the book was written (for example,
0 is English and 3 is German). The next group of digits designates the publisher (393 is the
code for W. W. Norton), and the one after it is a number assigned by the publisher to identify
the book (30375 is the code for Stephen Jay Gould’s The Flamingo’s Smile). The number
ends with a “check digit’’ that is used to verify the accuracy of the preceding digits. Write a
program that breaks down an ISBN entered by the user:
44 Chapter 3 Formatted Input/Output

Enter ISBN: 0-393-30375-6


Language: 0
Publisher: 393
Book number: 30375
Check digit: 6

Test your program with actual ISBN values (usually found on the back cover of a book and
on the copyright page).

*7. Suppose that we call scanf as follows:


scant("%d%f%d", &i, &x, &j);

If the user enters


10.3 5 6

what will be the values of i, x, and j after the call? (Assume that i and j are int variables
and x is a float variable.)

*8. Suppose that we call scanf as follows:


scanf("%f%d%f", &x, &i, &y);

If the user enters


12.3 45.6 789

what will be the values of x, i, and y after the call? (Assume that x and y are float vari¬
ables and i is an int variable.)

’•‘Starred exercises are tricky—the correct answer is usually not the obvious one. Read the question
thoroughly, review the relevant section if necessary, and be careful!
60 Chapter 4 Expressions

Exercises
Section 4.1 i. Show the output produced by each of the following code fragments. Assume that i, j, and
k are int variables.
(a) i = 5; j = 3 ;
printf("%d %d", i / j , i % j) ;
(b) i = 2; j = 3;
printf("%d", (i + 10) % j);
(c) i = 7; j =8; k = 9;
printf("%d" , (i + 10) % k / j) ;
(d) i = 1; j = 2; k - 3;
printf("%d", (i + 5) % (j + 2) / k) ;

*2. If i and j are positive integers, does (-i)/j always have the same value as - ( i/ j ) ?
Justify your answer.

3. Write a program that asks the user to enter a two-digit number, then prints the number with
its digits reversed. A session with the program should have the following appearance:
Enter a two-digit number: 28
The reversal is: 82
Read the number using %d, then break it into two digits. Hint: If n is an integer, then n % 10
is the last digit in n and n / 10 is n with the last digit removed.

4. Extend the program in Exercise 3 to handle three-digit numbers.

5. Rewrite the program in Exercise 4 so that it prints the reversal of a three-digit number with¬
out using arithmetic to split the number into digits. Hint: Review the upc . c program.

Section 4.2 6. Show the output produced by each of the following code fragments. Assume that i, j, and
k are int variables.
(a) i = 7; j = 8 ;
i *= j + 1 ;
printf("%d %d", i, j);
(b) i = j = k = 1;
i += j += k;
printf("%d %d %d", i, j, k);
(c) i = 1; j = 2; k = 3 ;
i -= j -= k;
printf("%d %d %d", i, j, k);
(d) i = 2; j = 1; k = 0;
i *= j *- k;
printf("%d %d %d", i, j, k);

Section 4.3 *7. Show the output produced by each of the following code fragments. Assume that i, j, and
k are int variables.
(a) i = 1 ;
printf("%d ", i++ - 1);
printf("%d", i);
Exercises 61

(b) i = 10; j = 5;
printf("%d ", i++ - ++j);
printf("%d %d", i, j);
(c) i = 7; j = 8;
printf("%d ", i++ - --j);
printf("%d %d", i, j);
(d) i = 3; j =4; k = 5;
printf("%d ", i++ - j++ + --k) ;
printf("%d %d %d", i, j, k);

8. Only one of the expressions + + i and i++ is exactly the same as (i += 1); which is it?
Justify your answer.

Section 4.4 9. Supply parentheses to show how a C compiler would interpret each of the following expres¬
sions.
(a) a*b-c*d + e
(b) a / b % c / d
(c) -a-b + c- + d
(d) a * - b / c-d

*10. How many possible values are there for the expression (i++) + (i--)? What are those
values, assuming that i has the value 1 initially?

Section 4.5 11. Describe the effect of executing each of the following expression statements. (Assume that
i has the value 1 initially and j has the value 2.)
(a) i += j ;
(b) i—;
(c) i * j / i;
(d) i % ++j ;
82 Chapter 5 Selection Statements

The first method is fine when the statements in each case are short and there
are relatively few of them. The second method is better for large switch state¬
ments in which the statements in each case are complex and/or numerous.

Exercises
1 The following code fragments illustrate the relational and equality operators. Show the out¬
Section 5.1
put produced by each, assuming that i, j, and k are int variables.

(a) i = 2; j = 3 ;
k = i * j == 6;
printf("%d", k);
(b) i = 5; j = 10; k = 1;
printf("%d", k > i < j);
(c) i = 3; j = 2; k = 1 ;
printf("%d", i < j == j <k);
(d) i = 3; j = 4; k = 5 ;
printf("%d", i % j + i < k);

2. The following code fragments illustrate the logical operators. Show the output produced by
each, assuming that i, j, and k are int variables.

(a) i = 10; j = 5;
printf("%d", !i < j);
(b) i = 2; j =1;
printf("%d", !!i + !j);
(c) i = 5; j = 0; k = -5;
printf("%d", i && j || k);
(d) i = l;j=2;k = 3;
printf("%d", i < j || k);

*3. The following code fragments illustrate the short-circuit behavior of logical expressions.
Show the output produced by each, assuming that i, j, and k are int variables.

(a) i = 3; j = 4; k = 5;
printf("%d ", i < j || ++j < k) ;
printf("%d %d %d", i, j, k) ;
(b) i = 7; j - 8; k = 9;
printf("%d ", i - 7 && j++ < k);
printf("%d %d %d", i, j, k);
(C) i = 7; j = 8; k = 9;
printf("%d ", (i = j) || (j - k));
printf("%d %d %d", i, j, k);
(d) i = 1; j = 1; k = 1;
printf("%d ", ++i || ++j && ++k);
printf("%d %d %d", i, j, k);

*4. Write a single expression whose value is either -1, 0, or +1, depending on whether i is less
than, equal to, or greater than j, respectively.
Exercises 83

Section 5.2 5. Write a program that determines the number of digits in a number:
Enter a number: 374
The number 374 has 3 digits

You may assume that the number has no more than four digits. Hint: Use if statements to
test the number. For example, if the number is between 0 and 9, it has one digit. If the num¬
ber is between 10 and 99, it has two digits.

6. Write a program that asks the user for a 24-hour time, then displays the time in 12-hour
form:
Enter a 24-hour time: 21:11
Equivalent 12-hour time: 9:11 PM

Be careful not to display 12:00 as 0:00.

7. Modify the broker. c program by making both of the following changes:


(a) Ask the user to enter the number of shares and the price per share, instead of the value
of the trade.
(b) Add statements that compute the commission charged by a rival broker ($33 plus 30 per
share for fewer than 2000 shares; $33 plus 20 per share for 2000 shares or more). Dis¬
play the rival’s commission as well as the commission charged by the original broker.

8. Here’s a simplified version of the Beaufort scale, which is used to measure wind force:
Velocity (knots) Description
Less than 1 Calm
1-3 Light air
4-27 Breeze
28-47 Gale
48-63 Storm
Above 63 Hurricane
Write a program that asks the user to enter a wind velocity (in knots), then displays the cor¬
responding description.

9. In one state, single residents are subject to the following income tax:
Income Amount of tax
Not over $750 1% of income
$750-$2,250 $7.50 plus 2% of amount over $750
$2,250-$3,750 $37.50 plus 3% of amount over $2,250
$3,750-$5,250 $82.50 plus 4% of amount over $3,750
$5,250-$7,000 $142.50 plus 5% of amount over $5,250
Over $7,000 $230.00 plus 6% of amount over $7,000
Write a program that asks the user to enter the amount of taxable income, then displays the
tax due.

10. Modify the upc . c program of Section 4.1 so that it checks whether a UPC is valid. After
the user enters a UPC, the program will display either VALID or NOT VALID.

*11. Is the following if statement legal in C?


if (n >= 1 <= 10)
printf("n is between 1 and 10\n");
If so, what does it do when n is equal to 0?
84 Chapter 5 Selection Statements

* 12. Is the following i f statement legal in C?


if (n == 1-10)
printf("n is between 1 and 10\n");

If so, what does it do when n is equal to 5?

13. What does the following statement print if i has the value 17? What does it print if i has the
value -17?
printf("%d\n", i >= 0 ? i : -i);

Section 5.3 14. Using the switch statement, write a program that converts a numerical grade into a letter
grade:
Enter numerical grade: J34
Letter grade: B
Use the following grading scale: A = 90-100, B = 80-89, C = 70-79, D = 60-69, F = 0-59.
Print an error message if the grade is larger than 100 or less than 0. Hint: Break the grade
into two digits, then use a switch statement to test the ten’s digit.

15. Write a program that asks the user for a two-digit number, then prints the English word for
the number:
Enter a two-digit number: 45
You entered the number forty-five.
Hint: Break the number into two digits. Use one switch statement to print the word for the
first digit (“twenty,” “thirty,” and so forth). Use a second switch statement to print the
word for the second digit. Don’t forget that the numbers between 11 and 19 require special
treatment.

*16. What output does the following program fragment produce? (Assume that i is an integer
variable.)
i = 1;
switch (i % 3) {
case 0 : printf("zero"
case 1: printf("one")
case 2 : printf("two")
}
106 Chapter 6 Loops

Q: Are there any other ways to make an empty loop body stand out besides put¬
ting the null statement on a line by itself? [p. 102]
A: Some programmers use a dummy continue statement:

for (d = 2; d < n && n % d != 0; d++)


continue;

Others use an empty compound statement:

for (d = 2; d < n && n % d != 0; d++)


U

Exercises
1 Write a program that finds the largest in a series of numbers entered by the user. The pro¬
Section 6.1
gram must prompt the user to enter numbers one by one. When the user enters 0 or a nega¬
tive number, the program must display the largest nonnegative number entered:

Enter a number: 60
Enter a number: 38.3
Enter a number: 4.89
Enter a number: 100.62
Enter a number: 75.2295
Enter a number: 0

The largest number entered was 100.62

Notice that the numbers aren’t necessarily integers.

2. Write a program that asks the user to enter two integers, then calculates and displays their
greatest common divisor (GCD):
Enter two integers: 12 28
Greatest common divisor: 4
Hint: The classic algorithm for computing the GCD, known as Euclid’s algorithm, goes as
follows: Let m and n be variables containing the two numbers. Divide m by n. Save the divi¬
sor in m, and save the remainder in n. If n is 0, then stop: m contains the GCD. Otherwise,
repeat the process, starting with the division of m by n.

3. Write a program that asks the user to enter a fraction, then converts the fraction to lowest
terms:
Enter a fraction: 6/12
In lowest terms: 1/2
Hint: To convert a fraction to lowest terms, first compute the GCD of the numerator and
denominator. Then divide both the numerator and denominator by the GCD.

4. Add a loop to the broker . c program of Section 5.2 so that the user can enter more than
one trade and the program will calculate the commission on each. The program should ter¬
minate when the user enters 0 as the trade value:
Enter value of trade: 30000
Commission: $166.00
Exercises 107

Enter value of trade: 20000


Commission: $144.00

Enter value of trade: 0^

Section 6.2 5. Exercise 3 in Chapter 4 asked you to write a program that displays a two-digit number with
its digits reversed. Generalize the program so that the number can have one, two, three, or
more digits. Hint: Use a do loop that repeatedly divides the number by 10, stopping when it
reaches 0.

Section 6.3 6. Write a program that prompts the user to enter a number n, then prints all even squares
between 1 and n. For example, if the user enters 100, the program should print the follow¬
ing:
4
16
36
64
100

7. Rearrange the square3 . c program so that the for loop initializes i, tests i, and incre¬
ments i. Don’t rewrite the program; in particular, don’t use any multiplications.

8. Write a program that prints a one-month calendar. The user specifies the number of days in
the month and the day of the week on which the month begins:
Enter number of days in month: 31
Enter starting day of the week (l = Sun, 7 = Sat) : _3

1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

Hint: This program isn’t as hard as it looks. The most important part is a for statement that
uses a variable i to count from 1 to n, where n is the number of days in the month, printing
each value of i. Inside the loop, an if statement tests whether i is the last day in a week; if
so, it prints a new-line character.

*9. What output does the following for statement produce?


for (i = 5, j = i - 1; i > 0, j>0; --i, j=i-l)
printf("%d ", i);

10. Which one of the following statements is not equivalent to the other two (assuming that the
loop bodies are the same)?
(a) for (i = 0; i < 10; i++
(b) for (i = 0; i < 10; ++i
(c) for (i = 0; i + + <10; )

11. Which one of the following statements is not equivalent to the other two (assuming that the
loop bodies are the same)?
(a) while (i < 10) (...)
(b) for (; i < 10;) (...)
(c) do (...) while (i < 10);
108 Chapter 6 Loops

12. Show how to replace a continue statement by an equivalent goto statement.


Section 6.4
13. What output does the following program fragment produce?

sum = 0;
for (i = 0; i < 10? i++) {
if (i % 2) continue;
sum += i;
}
printf("%d\n", sum);

14. The following “prime-testing” loop appeared in Section 6.4 as an example:

for (d = 2; d < n; d++)


if (n % d == 0) break;
This loop isn’t very efficient. It’s not necessary to divide n by all numbers between 2 and
n - 1 to determine whether it’s prime. In fact, we need only check divisors up to the square
root of n. Modify the loop to take advantage of this fact. Hint: Don’t try to compute the
square root of n; instead, compare d * d with n.

Section 6.5 *15. Rewrite the following loop so that its body is empty:
for (n = 0; m > 0; n++)
m /= 2 ;

* 16. Find the error in the following program fragment and fix it.
if (n % 2 == 0);
printf ("n is evenin'');

You might also like