C How To Program
Chapter 2
Review Exercise solution:
2.7 Identify and correct the errors in each of the following statements.
(Note: There may be more than one error per statement.) a) scanf("d",
value);
b) printf("The product of %d and %d is %d"\n, x, y);
c) firstNumber + secondNumber = sumOfNumbers
d) if (number => largest) { largest == number; }
e) */ Program to determine the largest of three integers /*
f) Scanf("%d", anInteger);
g) printf("Remainder of %d divided by %d is\n", x, y, x % y);
h) if (x = y); { printf(%d is equal to %d\n", x, y); }
i) print("The sum is %d\n," x + y);
j) Printf("The value you entered is: %d\n, &value);
solution of 2.7
a) scanf("d", value);
Error: The format specifier should be "%d" and a pointer is needed.
Correction: scanf("%d", &value);
b) printf("The product of %d and %d is %d"\n, x, y);
Error: The escape sequence for a new line should be inside the quotes.
Correction: printf("The product of %d and %d is %d\n", x, y, x * y);
c) firstNumber + secondNumber = sumOfNumbers
Error: This is an assignment expression. The variables should be in reverse order.
Correction: sumOfNumbers = firstNumber + secondNumber;
d) if (number => largest) { largest == number; }
Error: => is not a valid operator in C. >= should be used, and == should be =.
Correction:
c
Copy code
if (number >= largest) {
largest = number;
}
e) / Program to determine the largest of three integers /
Error: The comment markers are incorrect.
Correction: /* Program to determine the largest of three integers */
f) scanf("%d", anInteger);
Error: The variable should be a pointer.
Correction: scanf("%d", &anInteger);
g) printf("Remainder of %d divided by %d is\n", x, y, x % y);
Error: The format specifier for the result is missing.
Correction: printf("Remainder of %d divided by %d is %d\n", x, y, x % y);
h) if (x => y); { printf("%d is equal to %d\n", x, y); }
Error: => is not a valid operator, and the semicolon after the if condition should be removed.
Correction:
if (x >= y) {
printf("%d is equal to %d\n", x, y);
}
i) printf("The sum is %d\n," x + y);
Error: The comma should be inside the quotes.
Correction: printf("The sum is %d\n", x + y);
j) Printf("The value you entered is: %d\n, &value);
Error: Printf should be printf, and the format specifier should be inside the quotes.
Correction: printf("The value you entered is: %d\n", value);
Here is the corrected version:
#include <stdio.h>
void main() {
int x = 5, y = 10, value, firstNumber = 2, secondNumber = 3, sumOfNumbers, number = 4, largest = 4,
anInteger;
// a)
scanf("%d", &value);
// b)
printf("The product of %d and %d is %d\n", x, y, x * y);
// c)
sumOfNumbers = firstNumber + secondNumber;
// d)
if (number >= largest) {
largest = number;
}
// e)
/* Program to determine the largest of three integers */
// f)
scanf("%d", &anInteger);
// g)
printf("Remainder of %d divided by %d is %d\n", x, y, x % y);
// h)
if (x >= y) {
printf("%d is equal to %d\n", x, y);
}
// i)
printf("The sum is %d\n", x + y);
// j)
printf("The value you entered is: %d\n", value);
return 0;
}
2.8 Fill-In the blanks in each of the following:
a) are used to document a program and improve its readability.
b) The function used to display information on the screen is .
c) A C statement that makes a decision is .
d) Calculations are normally performed by statements.
e) The function inputs values from the keyboard.
Solution:
a) Comments are used to document a program and improve its readability.
b) The printf function used to display information on the screen is printf.
c) A C statement that makes a decision is if.
d) Calculations are normally performed by arithmetic statements.
e) The scanf function inputs values from the keyboard.
2.9)Write a single C statement or line that accomplishes each of the
following:
a) Display the message “Enter two numbers.”
b) Assign the product of variables b and c to variable a.
c) State that a program performs a sample payroll calculation (i.e., use
text that helps to document a program).
d) Input three integer values and place them in int variables a, b and c.
solution:
a) printf(“enter two numbers.\n”);
b) a=b*c;
c) // This program performs a sample payroll calculation
d) scanf("%d %d %d", &a, &b, &c);
2.10 State which of the following are true and which are false. If false,
explain why.
a) C operators evaluate left-to-right.
b) Each of the following is a valid variable name: _under_bar_, m928134,
t5, j7, her_sales, his_account_total, a, b, c, z, z2.
c) The statement printf("a = 5;"); is an example of an assignment
statement.
d) An arithmetic expression containing no parentheses evaluates left-to-
right.
e) The following are all invalid variable names: 3g, 87, 67h2, h22, 2h.
solution:
a) C operators evaluate left-to-right.
False. This is partially true. While most operators evaluate left-to-right, some operators like assignment (=),
conditional (?:), and unary operators evaluate right-to-left.
b) Each of the following is a valid variable name: under_bar, m928134, t5, j7, her_sales, his_account_total, a,
b, c, z, z2.
True. All the given names follow the rules for valid C variable names.
c) The statement printf("a = 5;"); is an example of an assignment statement.
False. This is a printf statement that prints the string "a = 5;". It is not an assignment statement.
d) An arithmetic expression containing no parentheses evaluates left-to-right.
True. In the absence of parentheses, arithmetic expressions are evaluated left-to-right, following the operator
precedence rules.
e) The following are all invalid variable names: 39, 87, 67h2, h22, 2h.
True. Variable names cannot start with a digit, and they cannot contain spaces or start with a number.
2.11 Fill-In the blanks in each of the following:
a) What arithmetic operations are on the same level of precedence as
multiplication__________ .
division.
b) When parentheses are nested, which set of parentheses is evaluated
first in an arithmetic expression? ________.
The inner most set of parenthesis.
c) A location in the computer’s memory that may contain different values
at various times throughout the execution of a program is called
a________.
Variable.
2.12 What, if anything, displays when each of the following statements is
performed? If nothing displays, then answer “Nothing.” Assume x = 2 and
y = 3.
a) printf("%d", x);
2
b) printf("%d", x + x);
4
c) printf("%s", "x=");
‘x’=’
d) printf("x=%d", x);
x=2
e) printf("%d = %d", x + y, y + x);
5=5
f) z = x + y;
no output
g) scanf("%d%d", &x, &y);
user input required
h) // printf("x + y = %d", x + y);
no out put
i) printf("%s", "\n");
new line
2.13 Which of the following C statements contain variables whose values
are replaced?
a) scanf("%d%d%d%d%d", &b, &c, &d, &e, &f);
sol;
This statement uses scanf to read integer values from input into variables b, c, d, e, and f. The values of
these variables are replaced by the values entered during execution. So, this statement fits the description of
variables whose values are replaced.
b) p = i + j + k + 7;
sol:
This statement calculates a new value (i + j + k + 7) and assigns it to variable p. The previous value of p (if
any) is replaced with the new calculated value. So, this also involves variables whose values are replaced.
c) printf("%s", "Values are replaced");
sol;
This statement prints a string literal "Values are replaced" using printf. It does not involve variables whose
values are replaced because there are no variables in the printf statement whose values are being changed.
d) printf("%s", "a = 5");
sol:
this statement prints a string literal "a = 5" using printf. It does not involve variables whose values are
replaced.
2.14 Given the equation y = ax3 + 7, which of the following, if any, are
correct C statements for this equation?
a) y = a * x * x * x + 7;
correct
b) y = a * x * x * (x + 7);
incorrect
c) y = (a * x) * x * (x + 7);
incorrect
d) y = (a * x) * x * x + 7;
incorrect
e) y = a * (x * x * x) + 7;
correct
f) y = a * x * (x * x + 7);
incorrect
2.15 State the order of evaluation of the operators in each of the following
C statements and show the value of x after each statement is performed.
a) x = 7 + 3 * 6 / 2 - 1;
sol:
Order of evaluation:
Multiplication: 3 * 6 = 18
Division: 18 / 2 = 9
Addition: 7 + 9 = 16
Subtraction: 16 - 1 = 15
Value of 𝑥 𝑥=15
b) x = 2 % 2 + 2 * 2 - 2 / 2;
Order of evaluation:
Modulus: 2 % 2 = 0
Multiplication: 2 * 2 = 4
Division: 2 / 2 = 1
Addition and Subtraction (left to right): 0 + 4 - 1 = 3
Value of =3
c) x = (3 * 9 * (3 + (9 * 3 / (3))));
sol:
Order of evaluation:
Parentheses innermost:
Division: 9 * 3 / 3 = 27 / 3 = 9
Addition: 3 + 9 = 12
Multiplication: 3 * 9 = 27
Outer parentheses multiplication: 27 * 12 = 324
Value of 𝑥=324
2.16 (Arithmetic) Write a program that reads two integers from the user
then displays their sum, product, difference, quotient and remainder.
Solution:
#include <stdio.h>
int main() {
int num1, num2; int sum, product, difference, quotient, remainder;
// Input two integers from the user
printf("Enter first integer: ");
scanf("%d", &num1);
printf("Enter second integer: ");
scanf("%d", &num2);
// Perform arithmetic operations
sum = num1 + num2;
product = num1 * num2;
difference = num1 - num2;
quotient = num1 / num2;
remainder = num1 % num2;
// Display results
printf("Sum: %d\n", sum);
printf("Product: %d\n", product);
printf("Difference: %d\n", difference);
printf("Quotient: %d\n", quotient);
printf("Remainder: %d\n", remainder);
return 0; }
2.17 (Displaying Values with printf) Write a program that displays the
numbers 1 to 4 on the same line. Write the program using the following
methods. a) Using one printf statement with no conversion specifications.
b) Using one printf statement with four conversion specifications. c) Using
four printf statements.
Solution:
Method a) Using one printf statement with no conversion specifications
#include <stdio.h>
int main() {
printf("1 2 3 4\n");
return 0;
}
Method b) Using one printf statement with four conversion specifications
#include <stdio.h>
int main() {
printf("%d %d %d %d\n", 1, 2, 3, 4);
return 0;
}
Method c) Using four printf statements
#include <stdio.h>
int main() {
printf("1 ");
printf("2 ");
printf("3 ");
printf("4\n");
return 0;
}
2.18 (Comparing Integers) Write a program that reads two integers from
the user then displays the larger number followed by the words “is larger.”
If the numbers are equal, display the message “These numbers are equal.”
Use only the single-selec tion form of the if statement you learned in this
chapter
Solution:
int main()
{ int num1, num2;
// Input two integers from the user
printf("Enter first integer: ");
scanf("%d", &num1);
printf("Enter second integer: ");
scanf("%d", &num2);
// Single selection if statement to determine the larger number or equality
if (num1 > num2) {
printf("%d is larger.\n", num1); }
if (num2 > num1) {
printf("%d is larger.\n", num2); }
if (num2 == num1) {
printf("These numbers are equal.\n"); }
}
2.19 (Arithmetic, Largest Value and Smallest Value) Write a program that
inputs three different integers from the keyboard, then displays the sum,
the average, the product, the smallest and the largest of these numbers.
Use only the single-selection form of the if statement you learned in this
chapter. The screen dialogue should ap pear as follows:
Enter three different integers: 13 27 14
Sum is 54
Average is 18
Product is 4914
Smallest is 13
Largest is 27
#include <stdio.h>
int main() {
int num1, num2, num3;
int sum, product;
float average;
int smallest, largest;
// Input three different integers from the user
printf("Enter three different integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Calculate sum, product, and average
sum = num1 + num2 + num3;
product = num1 * num2 * num3;
average = (float)sum / 3;
// Determine smallest and largest numbers
smallest = num1;
if (num2 < smallest) {
smallest = num2;
}
if (num3 < smallest) {
smallest = num3;
}
largest = num1;
if (num2 > largest) {
largest = num2;
}
if (num3 > largest) {
largest = num3;
}
// Display results
printf("Sum is %d\n", sum);
printf("Average is %.2f\n", average);
printf("Product is %d\n", product);
printf("Smallest is %d\n", smallest);
printf("Largest is %d\n", largest);
return 0;
}
2.20 (Circle Area, Diameter and Circumference) For a circle of radius 2,
display the diameter, circumference and area. Use the value 3.14159 for π.
Use the following for mulas (r is the radius): diameter = 2r, circumference
= 2πr and area = πr2. Perform each of these calculations inside the printf
statement(s) and use the conversion specifica tion %f. This chapter
discussed only integer constants and variables. Chapter 3 will discuss
floating-point numbers—that is, values that can have decimal points.
Solution:
#include <stdio.h>
int main() {
// Constants
const float PI = 3.14159;
const int radius = 2;
// Calculations
float diameter = 2 * radius;
float circumference = 2 * PI * radius;
float area = PI * radius * radius;
// Display results
printf("For a circle with radius 2:\n");
printf("Diameter: %f\n", diameter);
printf("Circumference: %f\n", circumference);
printf("Area: %f\n", area);}
output:
For a circle with radius 2:
Diameter: 4.000000
Circumference: 12.566360
Area: 12.566360
2.21 What does the following code display? printf("%s",
"*\n**\n***\n****\n*****\n");
Solution:
*
**
***
****
*****
2.22 (Odd or Even) Write a program that reads an integer and determines
and displays whether it’s odd or even. Use the remainder operator. An
even number is a mul tiple of two. Any multiple of two leaves a remainder
of zero when divided by 2.
Solution:
#include <stdio.h>
int main() {
int number;
// Input an integer from the user
printf("Enter an integer: ");
scanf("%d", &number);
// Check if the number is even or odd
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}
return 0;
}
2.23 (Multiples) Write a program that reads two integers and determines
and dis plays whether the first is a multiple of the second. Use the
remainder operator.
Solution:
int main() {
int num1, num2;
// Input two integers from the user
printf("Enter two integers (separated by space): ");
scanf("%d %d", &num1, &num2);
// Check if num1 is a multiple of num2
if (num2 != 0 && num1 % num2 == 0)
{
printf("%d is a multiple of %d.\n", num1, num2); }
else {
printf("%d is not a multiple of %d.\n", num1, num2); }
return 0; }
2.24 Distinguish between the terms fatal error and nonfatal error. Why
might you prefer to experience a fatal error rather than a nonfatal error?
Solution:
Fatal Error:
Definition: A fatal error is an error that causes a program to terminate abnormally. This typically
happens when the error is severe enough that the program cannot continue executing safely.
Impact: When a fatal error occurs, the program stops immediately and usually outputs an error
message. Common causes of fatal errors include segmentation faults (accessing memory
incorrectly), stack overflow (exceeding the stack size limit), or certain types of runtime errors that
violate language or system rules.
Example: Accessing an array out of bounds or dereferencing a null pointer often leads to a fatal
error.
Nonfatal Error:
Definition: A nonfatal error, also known as a recoverable error, is an error that does not cause the
program to terminate immediately. The program can continue to execute after encountering a
nonfatal error, possibly after handling the error condition.
Impact: Nonfatal errors might affect specific operations or functionalities within the program but do
not prevent the entire program from running. Examples include input validation errors, file not found
errors (if handled properly), or recoverable network timeouts.
Example: If a program attempts to open a file that does not exist, it can handle this error by
displaying an appropriate message and then continuing to run.
Preference for Fatal vs Nonfatal Errors:
Fatal Error: In some cases, experiencing a fatal error might be preferred because it provides
a clear indication of a severe issue in the program. It stops execution immediately,
preventing further potentially incorrect operations or data corruption. This can be
particularly beneficial during development and testing phases as it helps identify critical
bugs early.
Nonfatal Error: On the other hand, encountering a nonfatal error allows the program to
handle the error gracefully and potentially recover from it. For user-facing applications,
especially those deployed in production environments, it's often preferable to handle errors
gracefully to maintain continuity of service and provide a better user experience.
Summary:
Fatal errors are severe and cause the program to terminate abruptly, often due to critical issues that
cannot be safely ignored or handled at runtime.
Nonfatal errors are less severe and allow the program to continue executing, typically after handling
or mitigating the error condition.
The preference for experiencing a fatal or nonfatal error depends largely on the context of the
application, its deployment environment, and the stage of development or operation.
2.25 (Integer Value of a Character) Here’s a peek ahead. In this chapter,
you learned about integers and the type int. C can also represent
uppercase letters, lowercase letters and a considerable variety of special
symbols. C uses small integers internally to represent each different
character. The set of characters a computer uses together with the
corresponding integer representations for those characters is called that
computer’s character set. You can display the integer equivalent of
uppercase A, for example, by executing the statement printf("%d", 'A');
Write a C program that displays the integer equivalents of some uppercase
letters, lowercase letters, digits and special symbols. At a minimum,
determine the integer equivalents of the following: ABCabc012$*+/ and the
space character.
Solution:
#include <stdio.h>
int main() {
// Displaying integer equivalents of characters
printf("Integer equivalents:\n");
printf("Uppercase letters: A=%d, B=%d, C=%d\n", 'A', 'B', 'C');
printf("Lowercase letters: a=%d, b=%d, c=%d\n", 'a', 'b', 'c');
printf("Digits: 0=%d, 1=%d, 2=%d\n", '0', '1', '2');
printf("Special symbols: $=%d, *=%d, +=%d, /=%d\n", '$', '*', '+', '/');
printf("Space character: %d\n", ' ');
Output
Integer equivalents:
Uppercase letters: A=65, B=66, C=67
Lowercase letters: a=97, b=98, c=99
Digits: 0=48, 1=49, 2=50
Special symbols: $=36, *=42, +=43, /=47
Space character: 32
2.26 (Separating Digits in an Integer) Write a program that inputs one five-
digit number, separates the number into its individual digits and displays
the digits separated from one another by three spaces each. [Hint: Use
combinations of integer di vision and the remainder operation.] For
example, if the user types in 42139, the program should display
42139
Solution:
#include <stdio.h>
int main() {
int number;
int digit1, digit2, digit3, digit4, digit5;
// Input a five-digit number from the user
printf("Enter a five-digit number: ");
scanf("%d", &number);
// Separate the number into individual digits
digit1 = number / 10000; // Extract first digit
digit2 = (number / 1000) % 10; // Extract second digit
digit3 = (number / 100) % 10; // Extract third digit
digit4 = (number / 10) % 10; // Extract fourth digit
digit5 = number % 10; // Extract fifth digit
// Display the digits separated by three spaces each
printf("%d %d %d %d %d\n", digit1, digit2, digit3, digit4, digit5);
return 0;
2.27 (Table of Squares and Cubes) Using only the techniques you learned
in this chapter, write a program that calculates the squares and cubes of
the numbers from 0 to 10 and uses tabs to display the following table of
values:
Solution:
#include <stdio.h>
int main() {
int number = 0;
int square, cube;
// Print header
printf("Number\tSquare\tCube\n");
// Calculate and display squares and cubes using single if statements
square = number * number;
cube = number * number * number;
// Display number, square, and cube
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
if (number >= 0 && number <= 10) {
square = number * number;
cube = number * number * number;
printf("%d\t%d\t%d\n", number, square, cube);
number++;
}
}
}
}
}
}
}
}
}
}
return 0;}
2.28 (Target Heart-Rate Calculator) While exercising, you can use a heart-
rate monitor to see that your heart rate stays within a safe range
suggested by your doctors and trainers. According to the American Heart
Association (AHA) (http://bit.ly/ AHATargetHeartRates), the formula for
calculating your maximum heart rate in beats per minute is 220 minus your
age in years. Your target heart rate is 50–85% of your maximum heart rate.
Write a program that prompts for and inputs the user’s age and calculates
and displays the user’s maximum heart rate and the range of the user’s
tar get heart rate. [These formulas are estimates provided by the AHA;
maximum and target heart rates may vary based on the health, fitness and
gender of the individual. Always consult a physician or qualified
healthcare professional before beginning or modifying an exercise
program.
Solution:
#include <stdio.h>
int main() {
int age;
int max_heart_rate;
float target_heart_rate_min, target_heart_rate_max;
// Input the user's age
printf("Enter your age: ");
scanf("%d", &age);
// Calculate maximum heart rate
max_heart_rate = 220 - age;
// Calculate target heart rate range (50% to 85% of maximum heart rate)
target_heart_rate_min = 0.5 * max_heart_rate;
target_heart_rate_max = 0.85 * max_heart_rate;
// Display results
printf("Your maximum heart rate is %d beats per minute.\n", max_heart_rate);
printf("Your target heart rate should be between %.0f and %.0f beats per minute.\n",
target_heart_rate_min, target_heart_rate_max);
return 0;
}
2.29 (Sort in Ascending Order) Write a program that inputs three different
numbers from the user. Display the numbers in increasing order. Recall
that an if statement’s body can contain more than one statement. Prove
that your script works by running it on all six possible orderings of the
numbers. Does your script work with duplicate numbers? [This is
challenging. In later chapters you’ll do this more conveniently and with
many more numbers.]
#include <stdio.h>
int main() {
int num1, num2, num3;
int smallest, middle, largest;
// Input three different numbers from the user
printf("Enter three different numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Determine the smallest, middle, and largest numbers
if (num1 <= num2 && num1 <= num3) {
smallest = num1;
if (num2 <= num3) {
middle = num2;
largest = num3;
} else {
middle = num3;
largest = num2;
}
} else if (num2 <= num1 && num2 <= num3) {
smallest = num2;
if (num1 <= num3) {
middle = num1;
largest = num3;
} else {
middle = num3;
largest = num1;
}
} else { // num3 is the smallest
smallest = num3;
if (num1 <= num2) {
middle = num1;
largest = num2;
} else {
middle = num2;
largest = num1;
}
}
// Display numbers in ascending order
printf("Numbers in ascending order: %d, %d, %d\n", smallest, middle, largest);
return 0;
}
The End