Professional Documents
Culture Documents
Weightage: 15%
Course: SUBS
Counseling Hrs :
(Day / Time)
Learning Outcomes : Upon conclusion of this subject, the student should be able to:
Coursework : 50%
Test # 1 20%
Test # 2 15%
Assignment 15%
Assignment (15%):
Week 8
Submission Due Date :
Group Assignment will be given to student to
apply their learned skill.
Coursework Details:
Control Structures and
Functions
Total 100%
Introduction to C
1 Chapter 2
Programming
Structured Program
2 Chapter 3
Development in C
Structured Program
2 Chapter 3
Development in C
C Program Control
4 Chapter 4
Revision
4
Test # 1 (2,3,4)
5
C Functions Chapter 5
5 C Functions
Chapter 5
6
C Arrays Chapter 6
6
C Arrays Chapter 6
7 Revision
Revision
7
Test # 2 (5,6)
8 Assignment Submission
Examination
Deitel H.M and Deitel P.J., 2010. C How to Program. 6th edition, Prentice-Hall.
Chapter 1
iii. Run the command prompt by typing cmd from your windows
iv. Go to the bin folder of MinGW and run command below:
gcc helloworld.c -o helloworld.exe
v. Notice it will create an executable program call helloworld.exe. You can run
the program that youve just created by typing the program name (e.g.
helloworld)
Step 1: Go to New->Project
Step 2: click on Win32, choose Win32 Console Application, then type your project
name you want to create (a project name can be different from the .c file name)
Step 5: Right click the Source files, click Add -> New Item, to add a new .c file
Step 6: Choose C++ File (.cpp), and type your file a name and end with .c extension.
Then click Add. [IMPORTANT: For c program, remember to end your file with .c
extension, else default will be .cpp]
Exercise 2. Modify the program as below and run it. Notice if theres any difference?
Modify the program as below and run it again. Notice if theres any difference?
Exercise 3. Create a simple calculator that can add two integers and produce the output
Chapter 2
Self-Review Exercises
2.2 State whether each of the following is true or false. If false, explain why.
2.5 Using the statements you wrote in Exercise 2.4, write a complete program that calculates
the product of three integers.
1. /* Calculate the product of three integers */
2. #include <stdio.h>
3.
4. int main (void)
5. {
6. int x, y, z, result; /* declare variables */
7.
8. printf( Enter three integers: ); /* prompt */
9. scanf( %d%d%d, &x, &y, &z ); /* read three integers */
10. result = x * y * z; /* multiply values */
11. printf( The product is %d\n, result ); /* display result */
12. return 0;
13. } /* end function main */
2.6 Identify and correct the errors in each of the following statements:
a. printf( The value is %d\n, &number );
Error: &number.
Correction: Eliminate the &.
b. scanf( %d%d, &number1, number2);
Error: number2 does not have an ampersand.
Correction: it should be &number2.
c. If ( c < 7);{
printf( C is less than 7\n );
}
Error: semicolon after the right parenthesis of the condition in the if statement.
Correction: remove the semicolon after the right parenthesis.
d. If ( c => 7) {
printf( C is equal to or less than 7\n );
}
Error: The relation operation =>
Correction: It should be >=
Exercises
2.7 Identify and correct the errors in each of the following statements.
a) scanf( d, value );
Error: (i) d (ii) value
Correction: (i) %d (ii) &value
h) if ( x = y );
printf( %d is equal to %d\n, x, y);
Error: (i) %d (ii) =
Correction: (i) %d (ii) ==
2.9 Write a single C statement or line that accomplishes each of the following:
a= b * c
c) State that a program performs a sample payroll calculation (i.e., use test that helps to
document a program).
d) Input three integer values from the keyboard and place these values in integer
variables a, b and c.
2.10 State which of the following are true and which are false. If false, explain your answer.
b) The following are all valid variable names: _under_bar_, m928134, t5 ,j7,
her_sales, his_account_total, a, b, c, z, z2.
True.
False, multiplication, division, and modulus are all evaluated first form left to
right. Then addition and subtraction are evaluated from right to left.
e) The following are all invalid variable names: 3g, 87, 67h2, h22, 2h.
2.12 What, if anything, prints when each of the following statements is performed? If
nothing prints, then answer Nothing. Assume x=2 and y=3.
a) printf(%d, x); 2
b) printf(%d, x+x); 4
c) printf(x=); x=
f) z=x+y; nothing
i) printf(\n); nothing
2.14 Given the equation y=a 2 +7, which of the following, if any, are correct C statements for
this equation?
a) y = a*x*x*x+7;
b) y = a*x*x*(x+7);
c) y = (a*x)*x*(x+7);
d) y = (a*x)*x*x+7;
e) y = a*(x*x*x)+7;
f) y = a*x*(x*x+7);
Answer: a, d, e
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;
x = 7+18/2-1;
x = 7+9-1;
x = 16-1;
x = 15
b) x = 2%2+2*2-2/2;
x = 0+2*2-2/2;
x = 0+4-2/2;
x = 0+4-1;
x=3
c) x = (3*9*(3+(9*3/(3))));
x = (3*9*(3+(9*1)));
x = (3*9*(3+9));
x = (3*9*12);
x = (27*12);
x = 324
2.16 (Arithmetic) Write a program that asks the user to enter two numbers, obtains them
from the user and prints their sum, product, difference, quotient and remainder.
#include <stdio.h>
system("PAUSE");
return 0;
}
2.17 (Printing Values with printf) Write a program that prints the numbers 1 to 4 on the
same line. Write the program using the following methods.
a) Using one printf statement with no conversion specifiers.
#include <stdio.h>
printf( "%d%d%d%d\n\n", 1, 2, 3, 4 );
printf("1");
printf("2");
printf("3");
printf("4\n");
system("PAUSE");
return 0;
}
[2.18 ] (Comparing Integers) Write a program that asks the user to enter two integers, obtains the
numbers from the user, then prints the larger number followed by the words is larger. If the
numbers are equal, print the message These numbers are equal. Use only the single-selection
form of the if statement you learned in this chapter.
#include <stdio.h>
if ( x > y ){
printf( "%d is larger\n", x);
}
if ( x < y ){
printf( "%d is larger\n", y);
}
if ( x == y){
printf(" These numbers are equal\n");
}
system("PAUSE");
return 0;
}
[2.19] (Arithmetic, Largest Value and Smallest Value) Write a program that inputs three different
integers from the keyboard, then prints 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 appear as follows:
smallest = num1 ;
if (smallest > num2){
smallest = num2;
}
largest = num1;
if (largest < num2){
largest = num2;
}
system("PAUSE");
return 0;
}
[2.20] (Diameter, Circumference and Area of a Circle) Write a program that reads in the radius of
circle and prints the circles diameter, circumference and area. Use the constant value 3.14159 for.
Perform each of these calculations inside the printf statement(s) and use the conversion specifier %f.
[Note: In this chapter, we have discussed only integer constants and variables. In chapter 3 well
discuss floating-point numbers, i.e., values that can have decimal points.]
#include <stdio.h>
int main (void)
{
int radius;
printf( "Input the circle radius: ");
scanf( "%d", &radius);
system("PAUSE");
return 0;
}
[2.24] (Odd or Even) Write a program that reads an integer and determines and prints whether it is
odd or even. [Hint: Use the remainder operator. An even number is a multiple of two. Any multiple
of two leaves a remainder of zero when divided by 2.]
#include <stdio.h>
if (integer %2 == 0){
printf("%d is an even integer\n", integer);
}
if (integer %2 != 0){
printf( "%d is an odd integer\n", integer);
}
system("PAUSE");
return 0;
}
[2.28] Distinguish between the terms fatal error and nonfatal error. Why might you prefer to
experience a fatal error rather than a nonfatal error?
A fatal error causes the program to terminate prematurely. A nonfatal error occurs when the logic of
the program is incorrect, and the program does not write properly. A fatal error immediately lets you
know there is a problem with the program, whereas a nonfatal error can be subtle and possibly go
undetected.
Note:
Your program should be able to cater for inputs of different values, hence DO NOT
HARDCODE the values!
Exercise 2. (2.30 Separating Digits in an Integer)
Write a program that inputs one five-digit number, separates the number into its
individual digits and prints the digits separated from one another by three spaces
each. [Hint: Use combinations of integer division and the remainder operation.] For
example, if the user types in 42139, the program should print
Note: Your program should be able to cater for inputs of different values, hence DO
NOT HARDCODE the values!
Create a BMI calculator application that reads the users weight in kilograms and
height in meters, then calculates and displays the users body mass index. Also, the
application should display the following information from the Department of health
and Human Services/National Institutes of Health so the user can evaluate his/her
BMI. BMI Values if less than 18.5, display Underweight, otherwise display Normal
Exercise 4. (2.29 Integer Value of a Character)
C programming use small integers internally to represent each uppercase letters,
lowercase letters and variety of special symbols. (refer appendix B in the text book)
Write a C program that prints the integer equivalents of the letters/symbols below:
A B C a b c 0 1 2 $ * + /
Self-Review Exercise
[3.2] Write four different C statements that each add 1 to integer variable x.
x = x + 1;
x += 1;
++x;
x++;
a) Assign the sum of x and y to z and increment the value of x by 1 after the
calculation.
z = x++ + y;
product *= 2;
product = product * 2;
d) Test if the value of the variable count is greater than 10. If it is, print Count is
greater than 10.
total -= --x;
total += x--;
g) Calculate the remainders after q is divided by divisor and assign the result to q.
Write this statement two different ways.
q % = divisor;
q = q % divisor;
h) Print the value 123.4567 with 2 digits of precision. What value is printed?
printf(%.2f, 123.4567);
123.46 is displayed.
i) Print the floating-point value 3.14159 with three digits to the right of the decimal
point. What value is printed?
printf(%.3f\n, 3.14159);
3.142 is displayed.
int sum, x;
b) Initialize variable x to 1.
x = 1;
sum = 0;
d) Add variable x to variable sum and assign the result to variable sum.
[3.5] Combine the statements that you wrote in exercise 3.4 into a program that calculates the sum
of the integers from 1 to 10. Use the while statement to loop through the calculation and increment
statements. The loop should terminate when the value of x becomes 11.
x = 1; /* initialize x */
sum = 0; /* initialize sum */
a) while ( c <= 5) {
product *= c;
++c;
b) scanf(%.4f, &value);
c) if (gender == 1 )
printf(Woman\n);
else;
printf(Man\n);
Error: Semicolon after the else part of the ifelse statement results in a logic
error. The second printf will always be executed.
[3.10] What is wrong with the following while repetition statement (assume z has value 100), which
is supposed to calculate the sum of the integers from 100 down to 1:
while ( z >= 0 )
sum += z;
The value of the variable z is never changed in the while statement. Therefore, an infinite loop is
created. To prevent the infinite loop, z must be decremented so that it eventually becomes 0.
Exercise
[3.11] Identify and correct the errors in each of the following. [Note: There may be more than one
error in each piece of code.]
else
printf(Age is less than 65\n);
b) int x = 1, total;
while ( x <= 10 ) {
total += x;
++x;
Error: total
Correction: total = 0
total += x;
++x;
Error: (i) While (ii) absence left brace and right brace of the while body
total += x;
++x;
d) while ( y > 0 ) {
printf(%d\n, y);
++y;
Error: ++
Correction: --
#include <stdio.h>
int main(void)
{
int x=1, total = 0, y;
while ( x<=10 ) {
y = x * x;
printf("%d\n", y);
total += y;
++x;
}
a) Obtain two numbers from the keyboard, compute their sum and display the result.
Input first number, input second number, add the two numbers, output the sum
b) Obtain two numbers from the keyboard, and determine and display which (if either) is the larger
off the two numbers.
c) Obtain a series of positive numbers from the keyboard, and determine and display their sum.
Assume that the user types the sentinel value -1 to indicate end of data entry.
[3.16] State which of the following are true and which are false. If a statement is false, explain why.
a) Experience has shown that the most difficult part of solving a problem on a computer is producing
a working C program.
False, the algorithm is the hardest of solving a problem.
b) A sentinel value must be a value that cannot be confused with a legitimate data value.
True.
c) Flowlines indicate the actions to be performed.
d) Conditions written inside decision symbols always contain arithmetic operator (i.e., +, -, *, /, and
%).
#include <stdio.h>
system("PAUSE");
return 0;
}
[3.19] (Sales Commission Calculator) One large chemical company pays its salespeople on a
commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week.
For example, a salesperson who sells $5000 worth of chemicals in a week receives $200 plus 9% of
$5000, or a total of $650. Develop a program that will input each salespersons gross sales for last
week and will calculate and display that salesperson's earnings. Process one salesperson's figures at
a time. Here is a sample input/output dialog:
#include <stdio.h>
system("PAUSE");
return 0;
}
[3.25] (Tabular Output) Write a program that uses looping to print the following table of values. Use
the tab escape sequence, \t, in the printf statement to separate the columns with tabs.
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
5 50 500 5000
6 60 600 6000
7 70 700 7000
8 80 800 8000
9 90 900 9000
#include <stdio.h>
system("PAUSE");
return 0;
}
[3.29] What does the following program print?
1. #include <stdio.h>
2.
3. int main (void)
4. {
5. int count = 1; /* initialize count */
6.
7. while ( count <= 10 ) { /* loop 10 times */
8.
9. /* output line of text */
10. printf(%s\n, count % 2 ? ****: ++++++++);
11. count++; /* increment count */
12. } /* end while */
13.
14. return 0; /* indicate program ended successfully */
15. } /* end function main */
Develop a program that will ask user to input the principal, annualrate and days for
several loans then calculate and display the interest for each loan. The program
should end only when user input -1. Sample output as below:
Note:
Your program should be able to cater for inputs of different values, hence DO NOT
HARDCODE the values!
Create a C program with content below (no need to include the comments /* */),
run and observe the output:
Modify the above program to validate its inputs. On any input, if the value entered is
other than 1 or 2, keep looping until the user enters a correct value.
Exercise 4. (3.33 Square of Asterisks)
Write a program that reads in the side of a square and then prints that square out of
asterisks. Your program should work for squares of all side sizes between 1 and 20.
For example, if your program reads a size of 4, it should print
Chapter 4
Self-Review Exercise
[4.2] State whether the following are true or false. If the answer is false, explain why.
False. The default case is optional. If no default action is needed, then there is
no need for a default case.
False. The break statement is used to exit the switch statement. The break
statement is not required when the default case is the last case.
c) The expression (x>y && a<b) is true if either x > y is true or a < b is true.
False. Both of the relational expressions must be true in order for the entire
expression to be true when using the && operator.
True.
[4.3] Write a statement or a set of statements to accomplish each of the following tasks:
a) Sum the odd integers between 1 and 99 using a for statement. Assume the integer
variables sum and count have been defined.
sum = 0;
sum += count:
c) Calculate the value of 2.5 raised to the power of 3 using the pow function. Print the
result with a precision of 2 in a field width of 10 position. What is the value that prints?
printf(%10.2f\n, pow(2.5, 3) ); /* prints 15.63 */
d) Print the integers from 1 to 20 using a while loop and the counter variable x. Assume
that the variable x has been defined, but not initialized. Print only five integers per line. [Hint: Use
the calculation x % 5. When the value of this is 0, print a newline character, otherwise print a
tab character.]
x = 1;
while ( x <= 20 ) {
printf(%d, x);
if ( x % 5 == 0 ) {
printf(\n);
else {
printf(\t);
x++;
OR
x = 1;
while ( x <= 20 ) {
if ( x % 5 == 0 ) {
printf(%d\n, x++);
else {
printf(%d\t, x++);
OR
x = 0;
if ( x % 5 == 0 ) {
printf(%d\n, x);
}
else {
printf(%d\t, x);
printf(%d, x);
if (x % 5 == 0 ) {
printf(\n);
else {
printf(\t);
OR
if ( x % 5 == 0 ) {
printf(%d\n, x);
else {
printf(%d\t, x);
[4.4] Find the error in each of the following code segments and explain how to correct it.
a) x = 1;
while ( x <= 10 );
x++;
Error: The semicolon after the while header causes an infinite loop.
Correction: Replace the semicolon with a { or remove both the : and the }.
printf(%f\n, y);
Correction: Use an integer, and perform the proper calculation to get the
values you desire.
printf(%f\n, (float) y / 10 );
c) switch ( n ) {
case 1:
case 2:
default:
break;
Error: Missing break statement in the statements for the first case.
Correction: Add a break statement at the end of the statements for the first
case. This is not necessarily an error if you want the statement of case 2: to
excute every time the case 1:statement executes.
n=1;
while ( n < 10 )
printf(%d, n++);
Exercise
[4.5] Find the error in each of the following. (Note: There may be more than error.)
a) For ( x = 100, x >= 1, x++)
printf(%d\n, x);
b) The following code should print whether a given integer is odd or even:
switch(value % 2){
case 0:
printf(Even integer\n);
case 1:
printf(Odd integer\n);
c) The following code should input an integer and a character and print them. Assume the user types
as input 100 A.
scanf(%d, &intVal);
charVal = getchar();
printf(%.7f\n, x);
Floating point numbers should not be used in loops due to imprecision. This imprecision
often causes infinite loop to occur. To correct this, an integer variable should be used for loop.
e) The following code should output the odd integers from 999 to 1:
printf(%d\n, x);
Error: += Correction: -=
f) The following code should output the even integers from 2 to 100:
counter = 2;
Do {
if (counter % 2 == 0){
printf(%d\n, counter);
counter += 2;
g) The following code should sum the integers from 100 to 150 (assume total is initialized to 0):
total += x;
Correction: Remove it
[4.6] State which values of the control variable x are printed by each of the following for statements:
printf(%d\n, x);
2, 4, 6, 8, 10, 12
printf(%d\n, x);
5, 12, 19
printf(%d\n, x);
3, 6, 9, 12, 15
d) for(x = 1; x <= 5; x += 7) {
printf(%d\n, x);
printf(%d\n, x);
12, 9, 6, 3
[4.7] Write for statement that print the following sequences of values:
a) 1,2,3,4,5,6,7
b) 3,8,13,18,23
c) 20,14,8,2,-4,-10
d) 19,27,35,43,51
1. #include <stdio.h>
2.
3. /* function main begins program execution */
4. int main (void)
5. {
6. int x;
7. int y;
8. int i;
9. int j;
10.
11. /* prompt user for input */
12. printf(Enter two integers in the range 1-20:);
13. scanf(%d%d, &x, &y); /* read values for x and y */
14.
15. for(i = 1; i <= y, i++) { /* count from 1 to y */
16.
17. for(j = 1; j <= x; j++) { /* count from 1 to x */
18. printf(@); /* output @ */
19. } /* end inner for */
20.
21. printf(\n); /* begin new line */
22. } /* end outer for */
23.
24. return 0; /* indicate program ended successfully */
25. } /* end function main */
[4.12] (Calculating the Sum of Even Integers) Write a program that calculates and prints the sum of
the even integers from 2 to 30.
#include <stdio.h>
system("PAUSE");
return 0;
}
[4.13] (Calculating the Product of Odd Integers) Write a program that calculates and prints the
product of the odd integers from 1 to 15.
#include <stdio.h>
int main (void)
{
long i;
long product=1;
system("PAUSE");
return 0;
}
[4.16] (Triangle Printing Program) Write a program that prints the following patterns separately, on
below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a
single printf statement of the form printf (*); (this causes the asterisks to print side by side). [Hint:
The last two patterns require that each lime begin with an appropriate number of blanks.]
a)
**
***
****
*****
******
*******
********
*********
**********
b)
**********
*********
********
*******
******
*****
****
***
**
#include <stdio.h>
system("PAUSE");
return 0;
}
Exercise 1.
Print the value 333.546372 in a field width of 15 characters with precisions of 1, 2, 3,
4 and 5. Right justify the output. What are the five values that print? What should
you do if you want to print Left justify output?
Tips:
printf(%15.1f\n, 333.546372);
printf(%-15.1f\n, 333.546372);
Answer:
#include <stdio.h>
int main (void)
{
printf("%15.1f\n",333.546372);
printf("%15.2f\n",333.546372);
printf("%15.3f\n",333.546372);
printf("%15.4f\n",333.546372);
printf("%15.5f\n",333.546372);
printf("%-15.1f\n",333.546372);
printf("%-15.2f\n",333.546372);
printf("%-15.3f\n",333.546372);
printf("%-15.4f\n",333.546372);
printf("%-15.5f\n",333.546372);
getchar("PAUSE");
return 0;
}
Exercise 2.
Create a C program with the code as below and run it. Do you able to identify the
error? Explain and correct it.
Answer:
#include <stdio.h>
system("PAUSE");
return 0;
}
Answer:
#include <stdio.h>
First pattern:
Second pattern:
Answer:
#include <stdio.h>
for(col=1;col<=row;col++){
printf("*");
}
printf("\n");
}
for(row=1;row<=10;row++){
for(space=1;space<=10-
row;space++){
printf(" ");
}
for(col=1;col<=row;col++){
printf("*");
}
printf("\n");
}
system("PAUSE");
return 0;
}
Chapter 5
Self-Review Exercise
5.2 For the following program, state the scope (either function scope, file scope, block scope or
function prototype scope) of each of the following elements.
1 #include <stdio.h>
2 int cube( int y );
3
4 int main( void )
5{
6 int x;
7
8 for ( x = 1; x <= 10; x++ )
9 printf( "%d\n", cube( x ) );
10 return 0;
11 }
12
13 int cube( int y )
14 {
15 return y * y * y;
16 }
a) The variable x in main.
Block scope
b) The variable y in cube.
Block scope
c) The function cube.
File scope
d) The function main.
File scope
e) The function prototype for cube.
File scope
f) The identifier y in the function prototype for cube.
Function prototype scope
5.3 Write a program that tests whether the examples of the math library function calls shown in
Fig. 5.2 actually produce the indicated results.
#include <stdio.h>
#include <math.h>
system("PAUSE");
return 0;
}
5.4 Give the function header for each of the following functions.
a) Function hypotenuse that takes two double-precision floating-point arguments, side1 and
side2, and returns a double-precision floating-point result.
double hypotenuse(double side1, double side2)
b) Function smallest that takes three integers, x, y, z, and returns an integer.
int smallest(int x, int y, int z)
c) Function instructions that does not receive any arguments and does not return a value.
[Note: Such functions are commonly used to display instructions to a user.]
void instructions(void)
d) Function intToFloat that takes an integer argument, number, and returns a floatingpoint
result.
float intToFloat(int number)
5.7 Find the error in each of the following program segments and explain how the error can be
corrected (see also Exercise 5.46):
a) int g( void )
{
printf( "Inside function g\n" );
int h( void )
{
printf( "Inside function h\n" );
}
}
Error: function h is defined in function g.
Correction: move the definition of h pout of the definition of g.
b) int sum( int x, int y )
{
int result;
result = x + y;
}
Error: The body of function is supposed to return an integer but did not.
Correction: Delete variable result and place this in the function: return x = y;
c) int sum( int n )
{
if ( n == 0 ) {
return 0;
}
else {
n + sum( n - 1 );
}
}
Error: The result of n +sum(n-1) is not returned; sum returns an improper results.
Correction: rewrite the statement in the else clause as: return n + sum(n-1);
d) void f( float a );
{
float a;
printf( "%f", a );
}
Error: Semicolon after the right parenthesis that encloses the parameter list; redefining
the parameter a in the function definition.
Correction: voidf(float a)
{
printf(%f, a);
}
e) void product( void )
{
int a, b, c, result;
printf( "Enter three integers: " )
scanf( "%d%d%d", &a, &b, &c );
result = a * b * c;
printf( "Result is %d", result );
return result;
}
Error: The function returns a value when its not supposed to.
Correction: Eliminate the return statement.
Exercise
5.8 Show the value of x after each of the following statements is performed:
a) x = fabs( 7.5 );
7.5
b) x = floor( 7.5 );
7.5
c) x = fabs( 0.0 );
0.0
d) x = ceil( 0.0 );
0.0
e) x = fabs( -6.4 );
6.4
f) x = ceil( -6.4 );
-6.0
g) x = ceil( -fabs( -8 + floor( -5.5 ) ) );
-14.0
5.9 (Parking Charges) A parking garage charges a $2.00 minimum fee to park for up to three
hours and an additional $0.50 per hour for each hour or part thereof over three hours. The
maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer
than 24 hours at a time. Write a program that will calculate and print the parking charges for
each of three customers who parked their cars in this garage yesterday. You should enter the
hours parked for each customer. Your program should print the results in a neat tabular format,
and should calculate and print the total of yesterday's receipts. The program should use the
function calculateCharges to determine the charge for each customer. Your outputs should
appear in the following format:
Car Hours Charge
1 1.5 2.00
2 4.0 2.50
3 24.0 10.00
TOTAL 29.5 14.50
#include <stdio.h>
#include <math.h>
int main()
{
double h, currentCharge, totalCharges = 0.0, totalHours = 0.0;
int i, first = 1;
if ( first )
{
printf( "%5s%15s%15s\n", "Car", "Hours", "Charge" );
first = 0; /* prevents this from printing again */
}
system("PAUSE");
return 0;
}
return charge;
}
5.13 Write statements that assign random integers to the variable n in the following ranges:
a) 1 n 2
n = 1+ rand() % 2;
b) 1 n 100
n = 1 +rand() % 100;
c) 0 n 9
n = rand() % 10;
d) 1000 n 1112
n = 1000 + rand() %113;
e) 1 n 1
n = -1 + rand() % 3;
f) 3 n 11
n = -3 + rand() % 15;
5.14 For each of the following sets of integers, write a single statement that will print a number
at random from the set.
a) 2, 4, 6, 8, 10.
printf(%d\n, 2*(1+rand()%5));
b) 3, 5, 7, 9, 11.
printf(%d\n, 1+2*(1+rand()%5));
c) 6, 10, 14, 18, 22.
printf(%d\n, 6+4*(rand()%5));
5.15 (Hypotenuse Calculations) Define a function called hypotenuse that calculates the length
of the hypotenuse of a right triangle when the other two sides are given. Use this function in a
program to determine the length of the hypotenuse for each of the following triangles. The
function should take two arguments of type double and return the hypotenuse as a double.
Test your program with the side values specified in Fig. 5.18.
Triangle Side 1 Side 2
1 3.0 4.0
2 5.0 12.0
3 8.0 15.0
#include <stdio.h>
#include <math.h>
system("PAUSE");
return 0;
}
5.18 (Even or Odd) Write a program that inputs a series of integers and passes them one at a
time to function even, which uses the remainder operator to determine if an integer is even.
The function should take an integer argument and return 1 if the integer is even and 0
otherwise.
int even(int);
int main()
{
int x, i;
if (even(x))
printf("%d is an even integer\n\n", x);
else
printf("%d is not an even integer\n\n", x);
}
system("PAUSE");
return 0;
}
int even(int a)
{
return !(a % 2);
}
5.19 (Parking Charges) Write a function that displays a solid square of asterisks whose side is
specified in integer parameter side. For example, if side is 4, the function displays:
****
****
****
****
#include <stdio.h>
void square(int);
int main()
{
int side;
system("PAUSE");
return 0;
}
void square(int s)
{
int i, j;
5.20 (Displaying a Square of Any Character) Modify the function created in Exercise 5.19 to
form the square out of whatever character is contained in character parameter fillCharacter.
Thus if side is 5 and fillCharacter is # then this function should print:
#####
#####
#####
#####
#####
#include <stdio.h>
int main()
{
int s;
char c;
system("PAUSE");
return 0;
}
printf("\n");
}
}
5.24 (Temperature Conversions) Implement the following integer functions:
a) Function celsius returns the Celsius equivalent of a Fahrenheit temperature.
b) Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature.
c) Use these functions to write a program that prints charts showing the Fahrenheit equivalents
of all Celsius temperatures from 0 to 100 degrees, and the Celsius equivalents of all Fahrenheit
temperatures from 32 to 212 degrees. Print the outputs in a neat tabular format that minimizes
the number of lines of output while remaining readable.
#include <stdio.h>
int celcius(int);
int fahrenheit(int);
int main()
{
int i;
system("PAUSE");
return 0;
}
int main(void)
{
double x, y, z;
printf("Enter three doubling point values: ");
scanf("%lf%lf%lf", &x, &y, &z);
printf("The smallest value is %f\n", smallest3(x, y, z));
system("PAUSE");
return 0;
}
return smallest;
}
Exercise 5. (random) Write program that print a random integer n in the following ranges:
a) 2 <= n <= 50
b) -30 <= n <= 11
Random number formula:
n = s + rand () % (e-s+1);
Where the random number range to produce is s <= n <= e
Exercise 6. (5.20 Displaying a Square of Any Character)
Create a program that will displays a solid square based on the size and character
inputted by user. You should use a function which will accept a integer parameter size
and a character parameter fillCharacter and will return nothing.
Sample output:
Tips:
void square( int size, char fillCharacter ); /* function prototype */
If the players guess is incorrect, your program should loop until the player finally gets
the number right. Your program should keep telling the player Too high or Too low to
help the player guess the correct answer.
[Hint: Make sure you use the srand() function to make your game really randomize
Sample output:
Optional:
If youve finished the above, try to include a counter to record how many times the
player made the guess before finally found the correct answer. Display the total.
Chapter 6
Self-Review Exercise
6.2 State whether the following are true or false. If the answer is false, explain why.
a) An array can store many different types of values.
False. An array can only store values of the same type.
b) An array subscript can be of data type double.
False. An array subscript must be an integer or an integer expression.
c) If there are fewer initializers in an initializer list than the number of elements in the array,
C automatically initializes the remaining elements to the last value in the list of initializers.
False. C automatically initializes the remaining elements to zero.
d) Its an error if an initializer list contains more initializers than there are elements in the
array.
True.
e) An individual array element that is passed to a function as an argument of the form a[i]
and modified in the called function will contain the modified value in the calling function.
False. Individual array of an array is passed by value. If the entire function array is
passed to a function, then any modifications will be reflected in the original.
6.5 Find the error in each of the following program segments and correct the error.
a) #define SIZE 100;
Error: Semicolon at the end of #define pre-processor directive.
Correction: Eliminate semicolon.
b) SIZE = 10;
Error: Assigning a value to a symbolic constant using an assignment statement.
Correction; #define SIZE 10
c) Assume int b[ 10 ] = { 0 }, i;
for ( i = 0; i <= 10; i++ ) {
b[ i ] = 1;
}
Error: Referencing an array element outside the bonds of the array (b[10])
Correction; Change the final value of th control variable to 9.
d) #include <stdio.h>;
Error: Semicolon at the end of #include pre-processor directive.
Correction: Eliminate semicolon.
f) #define VALUE = 120
Error: Assigning a value to a symbolic constant using an assignment statement.
Correction: #define VALUE 120
Exercise
6.7 State which of the following are true and which are false. If false, explain why.
a) To refer to a particular location or element within an array, we specify the name of the
array and the value of the particular element.
False. We specify the name and the subscript of the element.
b) An array definition reserves space for the array.
True.
c) To indicate that 100 locations should be reserved for integer array p, write
p[ 100 ];
False. Begin the definitions with int.
d) A C program that initializes the elements of a 15-element array to zero must contain
one for statement.
False. The elements of an array can be initialized in the definitions.
e) A C program that totals the elements of a double-subscripted array must contain nested
for statements.
False. It is possible to total the elements of a double subscripted array by enumerating all the
elements in a calculation; however, it is much easier to use nested loop.
f) The mean, median and mode of the following set of values are 5, 6 and 7, respectively:
1, 2, 5, 6, 7, 7, 7.
True.