You are on page 1of 72

Programming Principles Folio

Name: Woo Kean Yip

Student ID: 15072457

Subject Code: PRG1102

Weightage: 15%

Lecturer: Pn. Aishah


LECTURE PLAN

Course: SUBS

Subject Name : Programming Principles

Subject Code : PRG1102

No. of Credit Hours : 3

Total Contact Hours :

Semester & Year : Semester 1, Year 1

Subject Lecturer : Pn. Aishah

(03) 74918622 (Ext: 7134)


Work Telephone:
Extension : aishahl@sunway.edu.my

E-mail : Monday and Tuesday : 10:30am-12:30pm

Counseling Hrs :
(Day / Time)

Course Description: This course introduces basic programming to students. It is a middle-level


language which comprises a combination of both high-level and low-level
language features.

Course Objectives : The objectives of this subject is to enable students to:

Understand programming logic


Understand the fundamental principles of programming.
Understand different types of data, operators, control structures and
demonstrate knowledge of programming

Learning Outcomes : Upon conclusion of this subject, the student should be able to:

Comprehend the basic concepts & common programming terminology.


Construct a simple program using various control structures and
functions
Apply the best programming practices
Assessment Mode: Examination : 50%

Coursework : 50%
Test # 1 20%
Test # 2 15%
Assignment 15%

Test # 1 (20%) Week 4


Date : A test for testing student the understanding of the
principles of programming, the concepts and skills
learn in the course.
Coursework Details:
Basic Concepts and
Control Structures

Test # 2 (15%) Week 7


Date : A test for testing student the understanding of the
principles of programming, the concepts and skills
learn in the course.
Coursework Details:
Arrays and Functions

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%

Weekly Course Week Lecture Topic Readings


Schedule
Introduction to
Computers and
1 Chapter 1
Programming
Language

Introduction to C
1 Chapter 2
Programming
Structured Program
2 Chapter 3
Development in C

Structured Program
2 Chapter 3
Development in C

3 C Program Control Chapter 4

3 C Program Control Chapter 4

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

Assigned Text : Main reference

Deitel H.M and Deitel P.J., 2010. C How to Program. 6th edition, Prentice-Hall.
Chapter 1

Lab Exercise (Chapter 1)

Exercise 1. Familiarize with the C development environment:


a. MinGW
i. Download the MinGW portable from eLearn and install it on your
PC/Laptop.
ii. Use any text editor (e.g. Notepad) to create a file with content below and
save as helloworld.c in the bin folder of MinGW that youve installed earlier

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)

b. Microsoft Visual C++


i. Start the Microsoft Visual C++
ii. Create a new Win32 console empty project
iii. Create a new c program file with the same content as above and save it as
helloworld.c
iv. Run the program by clicking the menu option Debug->Start without
debugging

(Refer to the demo)

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 3: click next


Step 4: select Empty project, then click Finish

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]

Step 6: Done! Youre now ready to type your c program code.

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?

Note: Try out other escape sequence character: \n \t \a \\ \

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.

a. Function printf always begins printing at the beginning of a new line.


False, function printf begins printing where the cursor is positioned, it may be
anywhere on the screen.
b. Comments cause the computer to print the text enclosed between /* and */ on the
screen when the program is executed.
False, Comments do not perform any action when the program is executed. Theyre
used to documents programs and improve their readability,
c. The escape sequence \n when used in a printf format control string causes the
cursor to position to the beginning of the next line on the screen.
True
d. All variables must be defined before theyre used.
True
e. All variables must be given a type when theyre defined.
True
f. C considers the variables number and NuMbEr to be identical.
False, C is case sensitive, variables are unique.
g. Definitions can appear anywhere in the body of a function.
False, definitions must appear after the { of the body of a function and before any
executable statements.
h. All arguments following the format control string in a printf function must be
preceded by an ampersand (&).
False, arguments in a printf function should not be preceded by an ampersand.
i. The remainder operator (%) can be used only with integer operands.
True
j. The arithmetic operators *, /, %, + and - all have the same level of precedence.
False, the operators *, / and % are on the same level of precedence, and the
operators + and are on a lower level of precedence.
k. The following variable names are identical on all Standard C systems.
thisisasuperduperlongname1234567
thisisasuperduperlongname1234568
False, some systems may distinguish between identifiers longer than 31 characters.
l. A program that prints three lines of output must contain three printf statements.
False, a print statement with multiple \n escape sequences can print several lines.

2.3 Write a single C statement to accomplish each of the following:

a) Define the variables C, thisVariable, q76354 and number to be of type int.


Int c, thisVariable, q76354, number;
b) Prompt the user to enter an integer. End your prompting message with a colon (:)
followed by a space and leave the cursor positioned after the space.
printf( Enter an integer: )
c) Read an integer from the keyboard and store the value entered in integer variable a.
scanf( %d, &a );
d) If number is not equal to 7, printf The variable number is not equal to 7.
If ( number != 7 )
{
printf( The variable number is not equal to 7.\n );
}
e) Print the message This is a C program. on one line.
printf( This is a C program. );
f) Print the message This is a c program. on two lines so that the first lines ends with
C.
printf( This is a C\nprogram.\n );
g) Print the message This is a C program. with each words on a separate line.
printf( This\nis\na\nC\nprogram.\n );
h) Print the message This is a C program. with the words separated by tabs.
printf( This\tis\ta\tC\tprogram.\t );

2.4 Write a statement (or comment) to accomplish each of the following:


a. State that a program will calculate the product of three integers.
/* Calculate the product of three integers */
b. Define the variables x, y, z and results to be of type int.
int x, y, z, result;
c. Prompt the user to enter three integers.
printf( Enter three integers );
d. Read three integers from the keyboard and store them in the variables x, y, and z.
scanf( %d%d%d, &x, &y, &z );
e. Compute the product of the three integers contained in variables x, y, z, and assign
the results to the variable result.
result = x * y * z;
f. Print The product is followed by the value of the integer variable result.
printf( The product is %d\n, result );

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

b) printf(The product of %d and %d is %d\n, x, y,);


Error: %d\n
Correction: %d\n

c) firstNumber + secondNumber = sumOfNumbers


Error: firstNumber + secondNumber = sumOfNumbers
Correction: sumOfNumbers = firstNumber + secondNumber

d) if (number => largest)


largest == number;
Error: =>
Correction: >=

e) */ Program to determine the largest of three integers /*


Error: (i) */ (ii) /*
Correction: (i) /* (ii) */
f) Scanf(%d, anInteger);
Error: (i) Scanf (ii) anInteger
Correction: (i) scanf (ii) &anInteger

g) printf(Remainder of %d dividend by %d is \n, x, y, x % y);


Error: is\n
Correction: is %d.\n

h) if ( x = y );
printf( %d is equal to %d\n, x, y);
Error: (i) %d (ii) =
Correction: (i) %d (ii) ==

i) print(The sum is %d\n, x + y);


Error: print
Correction: printf

j) Printf(The value you entered is: %d\n, &value);


Error: (i) Printf (ii) %d\n (iii) &value
Correction: (i) printf (ii) %d\n (iii) value

2.9 Write a single C statement or line that accomplishes each of the following:

a) Print the message Enter two numbers.

printf( Enter two numbers.\n);

b) Assign the product of variables b and c to variable a.

a= b * c

c) State that a program performs a sample payroll calculation (i.e., use test that helps to
document a program).

/* sample payroll calculation program */

d) Input three integer values from the keyboard and place these values in integer
variables a, b and c.

scanf( %d%d%d, &a, &b, &c);

2.10 State which of the following are true and which are false. If false, explain your answer.

a) C operators are evaluated from left to right.

False, the operator = is evaluated from right to left.

b) The following are all valid variable names: _under_bar_, m928134, t5 ,j7,
her_sales, his_account_total, a, b, c, z, z2.
True.

c) The statement printf(a = 5;); is a typical example of an assignment statement.

False, the statement prints a=5; on the screen.

d) A valid arithmetic expression containing no parentheses is evaluated from left to


right.

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.

False, those beginning with a number are invalid.

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=

d) printf(x=%d, x); x=2

e) printf(%d=%d, x+y, y+x); 5=5

f) z=x+y; nothing

g) scanf(%d%d, &x, &y); nothing

h) /* printf(x+y=%d, 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>

int main (void)


{
int integer1;
int integer2;
int sum;
int product;
int difference;
int quotient;
int remainder;

printf( "Enter first integer\n" );


scanf( "%d", &integer1);

printf( "Enter second integer\n" );


scanf( "%d", &integer2);
sum = integer1 + integer2;

printf( "Sum is %d\n", sum );

product = integer1 * integer2;

printf( "Product is %d\n", product);

difference = integer1 - integer2;

printf( "Difference is %d\n", difference);

quotient = integer1 / integer2;

printf( "Quotient is %d\n", quotient);

remainder = integer1 % integer2;

printf( "Remaider is %d\n", remainder);

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.

b) Using one printf statement with four conversion specifiers.

c) Using for printf statement.

#include <stdio.h>

int main (void)


{
printf( "1 2 3 4\n\n");

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>

int main (void)


{
int x;
int y;

printf( "Enter the numbers: " );


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

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:

Input 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 (void)


{
int num1;
int num2;
int num3;
int sum;
int average;
int product;
int smallest;
int largest;

printf("Input three different integers: ");


scanf("%d%d%d", &num1, &num2, &num3);

sum = num1 + num2 + num3;


printf( "Sum is %d\n", sum);

average = (num1 + num2 + num3) / 3;


printf( "Average is %d\n", average);

product = num1 * num2 * num3;


printf( "Product is %d\n", product);

smallest = num1 ;
if (smallest > num2){
smallest = num2;
}

if (smallest > num3){


smallest = num3;
}

printf("Smallest is %d\n", smallest);

largest = num1;
if (largest < num2){
largest = num2;
}

if (largest < num3){


largest = num3;
}

printf("Largest is %d\n", largest);

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);

printf( "\n The diameter is %d\n", 2*radius);


printf( "The circumference is %d\n", 2*3.14159*radius);
printf( "The area is %d\n", 3.14159*radius*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>

int main (void)


{
int integer;
printf( "Input an integer: ");
scanf( "%d", &integer);

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.

Lab Exercise (Chapter 2)

Exercise 1. (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. The sample
output of screen dialogue should appear as follows:

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!

Exercise 3. (2.32 Body Mass Index Calculator)


Formulas for calculating BMI are

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 $ * + /

Tips: printf( "A's integer equivalent is %d\n", 'A' );


Chapter 3

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++;

[3.3] Write a single C statement to accomplish each of following:

a) Assign the sum of x and y to z and increment the value of x by 1 after the
calculation.

z = x++ + y;

b) Multiply the variable product by 2 using the *= operator.

product *= 2;

c) Multiply the variable product by 2 using the = and * operators.

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.

If( count > 10 )

printf(Count is greater than 10.\n);

e) Decrement the variable x by 1, then subtract it from the variable total.

total -= --x;

f) Add the variable x to the variable total, then decrement x by 1.

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.

[3.4] Write a C statement to accomplish each of the following tasks.

a) Define variables sum and x to be of type int.

int sum, x;

b) Initialize variable x to 1.

x = 1;

c) Initialize variable sum to 0.

sum = 0;

d) Add variable x to variable sum and assign the result to variable sum.

sum += x; or sum = sum + x;

e) Print The sum is: followed by the value of variable sum.

printf(The sum is: %d\n, 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.

/* Calculate the sum of the integers from 1 to 10 */


#include <stdio.h>

int main (void)


{
int sum, x; /* define variables sum and x */

x = 1; /* initialize x */
sum = 0; /* initialize sum */

while ( x<= 10) { /* loop while x is less than or equal to 10 */


sum += x; /* increment x */
++x; /* increment x */
}

printf("The sum is: %d\n", sum);


return 0;
}

[3.9] Identify and correct the errors in each of the following:

a) while ( c <= 5) {

product *= c;

++c;

Error: Missing the closing right brace of the while body.

Correction: Add closing right brace after the statement ++c;.

b) scanf(%.4f, &value);

Error: Precision used in a scanf conversion specification.

Correction: Remove .4 from the conversion specification.

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.

Correction: Remove the semicolon after else.

[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.]

a) if( age >=65 );

printf(Age is greater than or equal to 65\n);

else
printf(Age is less than 65\n);

Error: semicolon after the statement if age >=65

Correction: remove the semicolon

b) int x = 1, total;

while ( x <= 10 ) {

total += x;

++x;

Error: total

Correction: total = 0

c) While ( x <= 100 )

total += x;

++x;

Error: (i) While (ii) absence left brace and right brace of the while body

Correction: while ( x <= 100 ) {

total += x;

++x;

d) while ( y > 0 ) {

printf(%d\n, y);

++y;

Error: ++

Correction: --

[3.13] What does the following program print?

#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;
}

printf("Total is %d\n", total);


system("PAUSE");
return 0;
}

[3.15] Formulate a pseudocode algorithm for each of the following:

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.

Input first number from keyboard


Input second number from keyboard
If the first number is greater than the second number
print it
Else if the second number is greater than the first number
print it
Else print a message stating that the numbers are equal

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.

Input a value from the keyboard


while the input value is not equal to -1
add the number to the running total
input the next number
print the sum

[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.

False, flowlines indicate the order in which steps are performed.

d) Conditions written inside decision symbols always contain arithmetic operator (i.e., +, -, *, /, and
%).

False, they normally contain conditional operators.


e) In top-down, stepwise refinement, each refinement is a complete representation of the algorithm.
True
[3.17] (Gas Mileage) Drivers are concerned with the mileage obtained by their automobiles. One
driver has kept track of several tankfuls of gasoline by recording miles driven and gallons used for
each tankful. Develop a program that will input the miles driven and gallons used for each tankful.
The program should calculate and display the miles per gallon obtained for each tankful. After
processing all input information, the program should calculate and print the combined miles per
gallon obtained for all tankfuls. Here is a sample input/output dialog:
Enter the gallons used (-1 to end): 12.8
Enter the miles driven: 287
The miles / gallon for this tank was 22.421875
Enter the gallons used (-1 to end): 10.3
Enter the miles driven: 200
The miles / gallon for this tank was 19.417475
Enter the gallons used (-1 to end): 5
Enter the miles driven: 120
The miles / gallon for this tank was 24.000000
Enter the gallons used (-1 to end): -1
The overall average miles/gallon was 21.601423

#include <stdio.h>

int main (void)


{
double gallons;
double miles;
double totalGallons =0.0;
double totalMiles = 0.0;
double totalAverage;

printf( "Enter the gallons used (-1 to end): ");


scanf( "%lf", &gallons);

while ( gallons != -1.0){


totalGallons += gallons;

printf( "Enter the miles driven: ");


scanf( "%lf", &miles);
totalMiles += miles;

printf( "The Miles/ Gallon for this tank was %f\n\n",


miles/gallons);

printf( "Enter the gallons used (-1 to end): ");


scanf( "%lf", &gallons);
}
totalAverage = totalMiles / totalGallons;
printf( "\n The overall average Miles / Gallons was %f\n",
totalAverage);

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:

Enter sales in dollars (-1 to end): 5000.00


Salary is: $650.00
Enter sales in dollars (-1 to end): 1234.56
Salary is: $311.11
Enter sales in dollars (-1 to end): 1088.89
Salary is: $298.00
Enter sales in dollars (-1 to end): -1

#include <stdio.h>

int main (void)


{
double sales;
double wage;

printf( "Enter sales in dollars (-1 to end): ");


scanf("%lf", &sales);

while ( sales != -1.0){


wage = 200.00 + 0.09 * sales;
printf( "Salary is $%.2f\n\n", wage);
printf( "Enter sales in dollars (-1 to end ): ");
scanf( "%lf", &sales);
}

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.

N 10*N 100*N 1000*N

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

10 100 1000 10000

#include <stdio.h>

int main (void)


{
int n=0;
printf( "\tN\t\t10*N\t\t100*N\t\t1000*N\n\n");

while (++n <= 10){


printf( "\t%-2d\t\t%-5d\t\t%-5d\t\t%-6d\n", n, 10*n, 100*n,
1000*n);
}

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 */

Lab Exercise (Chapter 3)

Exercise 1. (3.20 Interest Calculator)


The simple interest on a loan is calculated by the formula:

Interest = principal * annualrate * days / 365;

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!

Exercise 2. (3.26 Tabular Output)


Write a program that utilizes looping to produce the following table of values:
Tips:
You can use a while loop, and print the output with statement below:
printf( "%d\t%d\t%d\t%d\n", a, a + 2, a + 4, a + 6 );

Exercise 3. (3.28 Validating User Input)

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.

a) The default case is required in the switch selection statement.

False. The default case is optional. If no default action is needed, then there is
no need for a default case.

b) The break statement is required in the default case of a switch selection


statement.

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.

d) An expression containing the || operator is true if either or both of its operands is


true.

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;

for( count = 1; count <= 99; count += 2 ) {

sum += count:

b) Print the value 333.546372 in a field width of 15 characters with precisions of 1, 2, 3, 4


and 5. Left justify the output. What are the five values that print?

printf(%-15.1f\n, 333.546372); /* prints 333.5 */

printf(%-15.2f\n, 333.546372); /* prints 333.55 */

printf( %-15.3f\n, 333.546372); /* prints 333.546 */

printf(%-15.4f\n, 333.546372); /* prints 333.5464 */

printf(%-15.5f\n, 333.546372); /* prints 333.54637 */

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;

while ( ++x <= 20 ) {

if ( x % 5 == 0 ) {

printf(%d\n, x);
}

else {

printf(%d\t, x);

e) Repeat Exercise 4.3(d) using a for statement.

for ( x = 1; x <= 20; x++ ) {

printf(%d, x);

if (x % 5 == 0 ) {

printf(\n);

else {

printf(\t);

OR

for ( x = 1; x <= 20; x++ ) {

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 }.

b) for ( y = .1; y != 1.0; y += .1 )

printf(%f\n, y);

Error: Using a floating-point number to control a for repetition statement.

Correction: Use an integer, and perform the proper calculation to get the
values you desire.

for ( y = 1; y != 10; y++ )

printf(%f\n, (float) y / 10 );

c) switch ( n ) {

case 1:

printf(The number is 1\n);

case 2:

printf(The number is 2\n);

default:

printf(The number is not 1 or 2\n);

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.

d) The following code should print the values 1 to 10.

n=1;

while ( n < 10 )

printf(%d, n++);

Error: Improper relational operator used in the while repetition-continuation


condition.

Correction: Use <= rather than <.

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);

Error: (i) For (ii) x = 100, x>=1

Correction: (i) for (ii) x=1; x<=100;

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);

Error: missing break for case 0

Correction: add break

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(Integer: %d\nCharacter: %c\n, intVal, charVal);

Error: charVal = getchar();

Correction: scanf(\n%c, &charVal)

d) for ( x = .000001; x == .0001; x += .000001) {

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:

for ( x =999; x >= 1; x += 2) {

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;

} While(counter < 100);

D in Do should be in lowercase as well as w in while. The range 2 to 100 needs to be


printed, so the relational operator < should be changed to <=, to include 100.The if test
is not necessarily here, because counter is being incremented by 2, and will always be even
within the body of the dowhile.

g) The following code should sum the integers from 100 to 150 (assume total is initialized to 0):

for(x = 100; x <= 150; x++); {

total += x;

Error: Semicolon at the end of statement

Correction: Remove it

[4.6] State which values of the control variable x are printed by each of the following for statements:

a) for(x = 2; x <= 13; x += 2 ){

printf(%d\n, x);

2, 4, 6, 8, 10, 12

b) for(x + 5; x <= 22; x += 7) {

printf(%d\n, x);

5, 12, 19

c) for(x = 3; x <= 15; x += 3) {

printf(%d\n, x);

3, 6, 9, 12, 15

d) for(x = 1; x <= 5; x += 7) {
printf(%d\n, x);

e) for(x = 12; x >= 2; x -= 3) {

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

for ( x=1; x<=7; x+1);

printf( %d, x);

b) 3,8,13,18,23

for ( x=3; x<=23;x+5);

printf( %d, x);

c) 20,14,8,2,-4,-10

for ( x=20; x>=-10; x-=6);

printf( %d, x);

d) 19,27,35,43,51

for ( x=19; x<=51; x+8);

printf( %d, x);

[4.8] What does the following program do?

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>

int main (void)


{
int i;
int sum=0;

for (i=2; i<=30; i+=2){


sum = sum + i;
}
printf( "Sum of the even integers from 2 to 30 is %d\n", sum);

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;

for (i=3; i<=15; i+=2){


product*=i;
}
printf("Product of the odd integer from 1 to 15 is: %d\n", product);

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>

int main (void)


{
int row;
int col;
int space;

for (row=1; row<=10; row++){

for (col=1; col<=row; col++){


printf("*");
}
printf("\n");
}
printf("\n");

for (row=10; row>=1; row--){


for (space=1; space<=10-row; space++){
printf(" ");
}
for (col=1; col<=row; col++){
printf("*");
}
printf("\n");
}
printf("\n");

for (row=10; row>=1; row--){

for (col=1; col<=row; col++){


printf("*");
}
printf("\n");
}
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");
}
printf("\n");

system("PAUSE");

return 0;
}

Lab Exercise (Chapter 4)

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>

int main (void)


{
int n;
printf("Enter value of n: ");
scanf("%d",&n);
switch (n){
case 1:
printf("the number is 1\n");
break;
case 2:
printf("the number is 2\n");
break;
default:
printf("The number is not 1 or 2\n");
break;
}

system("PAUSE");
return 0;
}

Exercise 3. (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, using a single for loop statement.

Answer:

#include <stdio.h>

int main (void)


{
int i;
int sum=0;

for (i=2; i<=30; i+=2){


sum =sum +i;}
printf("Sum of the even integers from 2 to 30 is %d\n", sum);
system("PAUSE");
return 0;
}

Exercise 4. (4.16 Triangle Printing Program)


Write a program that prints the following patterns separately. Use for loops to
generate the patterns. All asterisks (*) should be printed by a single printf
statement of the form printf (*);
[Hint: the second pattern requires that each line begin with an appropriate number
of blanks. And, you will need two for loops nested]

First pattern:

Second pattern:
Answer:
#include <stdio.h>

int main (void)


{
int row, col, space;
for(row=1;row<=10;row++){

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>

int main (void)


{
/* Calculates and outputs the square root */
printf("sqrt(%.1f) = %.1f\n", 900.0, sqrt(900.0) );
printf("sqrt(%.1f) = %.1f\n", 9.0, sqrt(9.0) );

/* Calculates and outputs the exponential function e to the x */


printf("exp(%.1f) = %.1f\n", 1.0, exp(1.0) );
printf("exp(%.1f) = %.1f\n", 2.0, exp(2.0) );

/* Calculates and outputs the logarithm (base e) */


printf("log(%f) = %.1f\n", 2.718282, log(2.718282) );
printf("log(%f) = %.1f\n", 7.389056, log(7.389056) );

/* Calculates and outputs the logarithm (base 10) */


printf("log10(%.1f) = %.1f\n", 1.0, log10(1.0));
printf("log10(%.1f) = %.1f\n", 10.0, log10(10.0));
printf("log10(%.1f) = %.1f\n", 100.0, log10(100.0));

/* Calculates and outputs the absolute value */


printf("fabs(%.1f) = %.1f\n", 13.5, fabs(13.5) );
printf("fabs(%.1f) = %.1f\n", 0.0, fabs(0.0) );
printf("fabs(%.1f) = %.1f\n", -13.5, fabs(-13.5) );

/* Calculates and outputs ceil(x) */


printf("ceil(%.1f) = %.1f\n", 9.2, ceil(9.2) );
printf("ceil(%.1f) = %.1f\n", -9.8, ceil(-9.8) );

/* Calculates and outputs floor(x) */


printf("floor(%.1f) = %.1f\n", 9.2, floor(9.2) );
printf("floor(%.1f) = %.1f\n", -9.8, floor(-9.8) );

/* Calculates and outputs pow(x, y) */


printf("pow(%.1f, %.1f) = %.1f\n", 2.0, 7.0, pow(2.0, 7.0) );
printf("pow(%.1f, %.1f) = %.1f\n", 9.0, 0.5, pow(9.0, 0.5) );

/* Calculates and outputs fmod(x, y) */


printf("fmod(%.3f/%.3f) = %.3f\n", 13.675, 2.333, fmod(13.675, 2.333) );

/* Calculates and outputs sin(x) */


printf("sin(%.1f) = %.1f\n", 0.0, sin(0.0) );

/* Calculates and outputs cos (x) */


printf("cos(%.1f) = %.1f\n", 0.0, cos(0.0) );

/* Calculates and outputs tan (x) */


printf("tan(%.1f) = %.1f\n", 0.0, tan(0.0) );

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.5 Give the function prototype for each of the following:


a) The function described in Exercise 5.4(a).
double hypotenuse(double side1, double side2)
b) The function described in Exercise 5.4(b).
int smallest(int x, int y, int z)

c) The function described in Exercise 5.4(c).


void instructions(void)
d) The function described in Exercise 5.4(d).
float intToFloat(int number)

5.6 Write a declaration for each of the following:


a) Integer count that should be maintained in a register. Initialize count to 0.
register int count = 0;
b) Floating-point variable lastVal that is to retain its value between calls to the function
in which its defined.
static float lastVal;
c) External integer number whose scope should be restricted to the remainder of the file in
which its defined.
static 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>

double calculateCharges( double );

int main()
{
double h, currentCharge, totalCharges = 0.0, totalHours = 0.0;
int i, first = 1;

printf( "Enter the hours parked for 3 cars: " );

for ( i = 1; i <= 3; i++ )


{
scanf( "%lf", &h );
totalHours += h;

if ( first )
{
printf( "%5s%15s%15s\n", "Car", "Hours", "Charge" );
first = 0; /* prevents this from printing again */
}

totalCharges += ( currentCharge = calculateCharges( h ) );


printf( "%5d%15.1f%15.2f\n", i, h, currentCharge );
}

printf( "%5s%15.1f%15.2f\n", "TOTAL", totalHours, totalCharges );

system("PAUSE");
return 0;
}

double calculateCharges( double hours )


{
double charge;

if ( hours < 3.0 )


charge = 2.0;
else if ( hours < 19.0 )
charge = 2.0 + .5 * ceil( hours - 3.0 );
else
charge = 10.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>

double hypotenuse(double, double);


int main()
{
int i;
double side1, side2;

for (i = 1; i <= 3; i++ )


{
printf("Enter the sides of the triangle: ");
scanf("%lf%lf", &side1, &side2 );
printf("Hypotenuse: %.1f\n\n", hypotenuse(side1, side2));
}

system("PAUSE");
return 0;
}

double hypotenuse(double s1, double s2)


{
return sqrt(pow(s1, 2) + pow(s2, 2));
}

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;

for (i = 1; i <= 3; i++)


{
printf("Enter an integer: ");
scanf("%d", &x);

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;

printf("Enter side: ");


scanf("%d", &side );
square(side);

system("PAUSE");
return 0;
}

void square(int s)
{
int i, j;

for (i = 1; i <= s; i++)


{

for (j = 1; j <= s; j++)


printf( "*" );
printf("\n");
}
}

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>

void square(int, char);

int main()
{
int s;
char c;

printf("Enter a character and the side length: ");


scanf("%c%d", &c, &s);
square(s, c);

system("PAUSE");
return 0;
}

void square(int side, char fillCharacter)


{
int loop, loop2;

for (loop = 1; loop <= side; loop++)


{
for (loop2 = 1; loop2 <= side; loop2++)
printf("%c", fillCharacter);

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;

printf("Fahrenheit equivalents of Celcius temperatures:\n");


printf("Celcius\t\tFahrenheit\n");

for (i = 0; i <= 100; i++)


printf("%d\t\t%d\n", i, fahrenheit(i));

printf("\nCelcius equivalents of Fahrenheit temperatures:\n");


printf("Fahrenheit\tCelcius\n");

for (i = 32; i <= 212; i++)


printf("%d\t\t%d\n", i, celcius(i));

system("PAUSE");
return 0;
}

int celcius(int fTemp)


{
return (int) (5.0 / 9.0 * (fTemp 32));
}

int fahrenheit(int cTemp)


{
return (int) (9.0 / 5.0 * cTemp + 32);
}
5.25 (Find the Minimum) Write a function that returns the smallest of three floating-point
numbers.
#include <stdio.h>

double smallest3(double, double, double);

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;
}

double smallest3(double a, double b, double c)


{
double smallest = a;

if(b < smallest)


smallest = b;
if(c < smallest)
smallest = c;

return smallest;
}

Lab Exercise (Chapter 5)

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 */

Exercise 7. (5.32 Guess the Number)


Write a C program that plays the game of guess the number as follows: Your program
should automatically choose a random number to be guessed by selecting an integer at
random in the range 1 to 1000. Then ask the player to guess the number. The player
then types a guess. The program responds with one of the following:
1. Excellent! You guessed the number!
Would you like to play again ( 1=yes, 2=no )?
2. Too low. Try again.
3. Too high. Try again.

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.3 Answer the following questions regarding an array called fractions.


a) Define a symbolic constant SIZE to be replaced with the replacement text 10.
#define SIZE 10
b) Define an array with SIZE elements of type double and initialize the elements to 0.
double fractions[SIZE] = {0.0};
c) Name the fourth element from the beginning of the array.
fractions[3]
d) Refer to array element 4.
fractions[4]
e) Assign the value 1.667 to array element nine.
fractions[9] = 1.667;
f) Assign the value 3.333 to the seventh element of the array.
fractions[6] = 3.333;
g) Print array elements 6 and 9 with two digits of precision to the right of the decimal point, and
show the output that is displayed on the screen.
printf(%.2f%.2f\n, fractions[6], fractions[9]);
Output; 3.33 1.67
h) Print all the elements of the array, using a for repetition statement. Assume the integer
variable x has been defined as a control variable for the loop. Show the output.
for(x = 0; x < SIZE; x++){
printf(fractions[%d] = %f\n, x, fractions[x]);
}
Output:
fractions[0] = 0.000000
fractions[1] = 0.000000
fractions[2] = 0.000000
fractions[3] = 0.000000
fractions[4] = 0.000000
fractions[5] = 0.000000
fractions[6] = 0.333000
fractions[7] = 0.000000
fractions[8] = 0.000000
fractions[9] = 1.667000

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.

6.8 Write statements to accomplish each of the following:


a) Display the value of the seventh element of character array f.
printf(%c\n), f[6]);
b) Input a value into element 4 of single-subscripted floating-point array b.
scanf(%f, &b[4]);
c) Initialize each of the five elements of single-subscripted integer array g to 8.\
for (loop = 0; loop <= 4; ++loop)
g[loop] = 8;
d) Total the elements of floating-point array c of 100 elements.
for (loop = 0; loop <= 10; ++loop)
sum += c[loop];
e) Copy array a into the first portion of array b. Assume double a[11], b[34];
for (loop = 0; loop <= 10; ++loop)
b[loop] = a[loop];
f) Determine and print the smallest and largest values contained in 99-element floatingpoint
array w.
smallest = largest = w[0];
for (loop = 1; loop <= 98; ++loop)
if(w[loop] < smallest)
else if (w[loop] > largest)
largest = w[loop];
6.12 Write single statements that perform each of the following single-subscripted array
operations:
a) Initialize the 10 elements of integer array counts to zeros.
for (i=0; i<=9; i++)
counts[i] = 0;
b) Add 1 to each of the 15 elements of integer array bonus.
for (i=0; i<=14; i++)
++bonus[i];
c) Read the 12 values of floating-point array monthlyTemperatures from the keyboard.
for (i=0; I<=11; i++){
printf(%s, Enter a temperature: );
scanf(%f, &monthlyTemperatures[i]);
}
d) Print the five values of integer array bestScores in column format.
for (i=0; i<=4; i++){
printf(%d\n), bestScores[i]);
}

You might also like