IT202 SG COMPLETE
IT202 SG COMPLETE
C Programming
Study Guide
Version 2.0
© 2006 by Global Business Unit – Higher Education
Informatics Holdings Ltd
A Member of Informatics Group
Informatics Campus
10-12 Science Centre Road
Singapore 609080
IT202
C Programming
Study Guide
Version 2.0
Revised in June 2006
Every precaution has been taken by the publisher and author(s) in the
preparation of this book. The publisher offers no warranties or representations,
not does it accept any liabilities with respect to the use of any information or
examples contained herein.
All brand names and company names mentioned in this book are protected by
their respective trademarks and are hereby acknowledged.
The developer is wholly responsible for the contents, errors and omission.
TABLE OF CONTENTS IT202
Objectives 1-1
1.1 Values in C 1-2
1.1.1 Numeric Values 1-2
1.1.2 Character Values 1-2
1.2 Variables in C 1-2
1.3 Data Types and Declaration 1-3
1.3.1 Declaration 1-3
1.3.2 Data Types 1-4
1.4 Arithmetic Expressions 1-5
1.4.1 Integer Arithmetic 1-6
1.5 Assignment 1-7
1.6 Sample Programs 1-8
1.7 Programming Exercise 1-10
1.8 Revision Exercise 1-13
Objectives 2-1
2.1 Output 2-2
2.1.1 Conversion Codes 2-2
2.1.2 Size Modifiers 2-3
2.2 Input 2-3
2.2.1 Conversion Codes 2-4
2.2.2 Prompts 2-4
2.2.3 Flushing the Input Stream 2-5
2.3 Sample Programs 2-6
2.4 Programming Exercise 2-9
2.5 Revision Exercise 2-12
Objectives 3-1
3.1 Structured Programming 3-2
3.2 Conditions 3-2
3.2.1 Relational and Equality Operators 3-2
3.2.2 Logical Operators 3-3
3.3 The if and else Statement 3-5
3.4 The switch Statement 3-6
3.5 Sample Programs 3-7
3.6 Programming Exercise 3-18
3.7 Revision Exercise 3-23
i
TABLE OF CONTENTS IT202
CHAPTER 4: ITERATION
Objectives 4-1
4.1 The Iteration Structure 4-2
4.1.1 Pretest Loops 4-2
4.1.2 Posttest Loops 4-3
4.2 Accumulating and Counting 4-3
4.3 Counter-Controlled Loops 4-4
4.4 Nested Loops 4-5
4.5 Sample Programs 4-6
4.6 Programming Exercise 4-15
4.7 Revision Exercise 4-18
CHAPTER 5: FUNCTIONS
Objectives 5-1
5.1 Why Function are Used in C 5-2
5.2 The Structure of Functions 5-3
5.2.1 The Function Definition 5-3
5.2.2 Calling the Function 5-4
5.2.3 Function Prototype 5-4
5.2.4 Local Variables 5-5
5.2.5 Functions that Return a Value 5-6
5.2.6 Using Arguments to Pass Data to a Function 5-7
5.2.7 Passing Multiple Arguments 5-7
5.2.8 External Variables 5-8
5.3 Sample Programs 5-10
5.4 Programming Exercise 5-16
5.5 Revision Exercise 5-19
CHAPTER 6: ARRAYS
Objectives 6-1
6.1 Array Declaration 6-2
6.2 The Variable Defined Array 6-3
6.3 Sample Programs 6-4
6.4 Programming Exercise 6-10
6.5 Revision Exercise 6-13
ii
TABLE OF CONTENTS IT202
CHAPTER 7: STRING
Objectives 7-1
7.1 String Variables 7-2
7.2 String Input 7-3
7.3 String Output 7-4
7.4 String Manipulation 7-5
7.5 Character Classification 7-6
7.6 Sample Programs 7-7
7.7 Programming Exercise 7-15
7.8 Revision Exercise 7-18
CHAPTER 8: FILES
Objectives 8-1
8.1 Opening Files 8-2
8.1.1 Files Modes 8-2
8.1.2 Binary versus Text Files 8-3
8.2 Closing a File 8-3
8.3 Character Access to Files 8-3
8.4 Finding The End of A File 8-4
8.5 Sample Programs 8-5
Objectives 9-1
9.1 Structures 9-2
9.1.1 Definition and Declaration 9-2
9.1.2 The sizeof a Structure 9-4
9.2 Accessing Structures 9-4
9.3 Arrays of Structure 9-5
9.4 Files and Structure 9-5
9.5 Sample Programs 9-7
iii
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
Students would learn how to form a simple C program and expose to C language step
by step. Additionally, students would know fundamentals of C language.
1-1
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
1.1 Values in C
There are two types of values in C known Integral and Real numbers. Due to different
storage space is required for different values, students have to know the type of values in
order to declare some memory spaces to store them.
There are two categories of numeric values: real numbers, those allow decimal points;
and integral, or whole numbers. In C, decimal numbers in either category can be
expressed exactly as we do in normal math.
1-2
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
1.2 Variables in C
Variables represent some segment of memory location in computer. Different values
placed in the storage depend on the value type. Variable should be declared prior to
storage of any values. When declaring variables in C, rules must be followed, such as:
• Spacing in a variable name is not allowed. If the variable name contains more
than one word, there should be underscore in place of the space. For example,
gross pay should be GrossPay, gross_pay or Gross_Pay.
• C is case-sensitive; upper- and lowercase characters are not treated the same. For
example, Total, total, and TOTAL would be considered as three different variable
names. For readability, many C programmers capitalized the first character of
each word in the variable and limit the use of the underscore.
• Reserve words are not allowed. The C compiler looks for certain key words,
words with special meanings, when it compiles the program. They are treated as
reserved words – set aside for use by the compiler. A list of ANSI C’s 32
reserved words is shown in Table 1-1:
do if static while
1-3
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
1.3.1 Declaration
Whenever we use a value or a variable, we will declare it and its data type. Variables
must be explicitly declared before they are used. Each declaration statement in C
language must end with a semicolon. A declaration performs a number of functions such
as (i) it directs C as to how to store the value, (ii) it allocates memory to the value or
variable, and the type of declaration tells the computer how much memory required, and
(iii) it initializes a variable by assigning a meaningful value to that space in memory.
There is various way of declaring variables, and the following are some examples of
variable declaration.
Example:
int GrossPay;
Integral data types allow only integral, or whole, numbers with no decimal points.
Integral data type can be singed or unsigned. The signed integral data type means that the
value may be either positive or negative. Generally, we do not need to specify whether a
variable is singed because by default it is so. The unsigned data type means the number
may only be positive.
Additionally, integral data type may be either short or long, whereby it tells the computer
the size of the integral number. In most of the cases, short is 16 bits and long is 32 bits.
There are different ranges of value allowed for short and long integral numbers; Figure
1-4
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
1-1 shows all the ranges. The following are some examples of integral variable
declaration.
Example:
short Age;
Real numbers, those with decimal points, are stored as floating-point data types. For
floating-point values, the computer stores the mantissa and the exponent. The memory
space allocated to the number is fixed, depending on the data type we declare, and is
divided between mantissa and exponent.
There are three different floating-point data types: float, double, and long double. These
data types are differ from each other in terms of the size. Generally, a float is 32 bits, a
double is 64 bits, and a long double is 80 bits. Unlike integral data types, floating-point
data types always allow positive or negative values, and so cannot have unsigned or
signed. When declaring a long double, to be sure to state long double, not just long,
because that would default to a long int. There are different ranges of value allowed for
floating-point data types as shown in Figure 1-1. The following are some examples of
floating-point variable declaration.
Example:
1-5
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
1-6
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
Example:
13 % 3 = 1
1%5=1
1%3=1
8%3=2
14 % 1002 = 14
1-7
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
1.5 Assignment
As mentioned earlier, variables identify spaces in main memory. These spaces are
variable because they can contain various and changeable values. Putting a value into one
of these spaces is known as assignment. We usually refer to “assigning a value to a
variable,” but technically, we are writing a value into the memory space identified by the
variable.
Sometime, we must also make assignments as part of our program. For example, we wish
to store the results of calculation in variable, but all of them follow this fundamental rule:
We may assign many different values to a variable, but each time we do, we write to the
memory space reserved for that variable. The standard assignment operator is the equal
sign (=). The following are some valid assignment statements:
Example:
x =17;
x = (y + 4) / 10;
1-8
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
Output
The value in a is 10.
Program 1-2
#include <stdio.h>
void main(void)
{
printf(“Here is the character %c\n”, ‘X’);
printf(“and the numbers %i and %g\n”, 100, 235.654);
printf(“Now we print %i as a number\n”, ‘X’);
}
Output
Here is the character X
And the numbers 100 and 235.654
Now we will print 88 as a number
1-9
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
Program 1-3
#include <stdio.h>
void main(void)
{
int a, b;
a =30;
b = 10;
Output
The value in a is: 30
The value in b is: 10
The addition result is: 40
The subtraction result is: 20
1 - 10
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
2. Write a program to find the average of the four values 4, 42, 16.7, and .0045.
Variables:
v1, v2, v3, v4
Average
Output
The four numbers are:
4 42 16.7 0.0045
The average is:
15.676126
3. Write a program that produces a bill and coin breakdown for an amount of
money. Initialize the amount in the float variable known as dollars and use the
cents variable to keep track of the amount not yet converted to bills and coins.
You will have to make use of integer arithmetic and the remainder in this
program.
1 - 11
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
Variables
dollars (float)
cents (int)
Output
The coin breakdown for 7.73 dollars is:
Dollar bills: 7
Fifty cents: 1
Twenty cents: 1
Ten cents: 0
Five cents: 0
One cents: 3
4. There are 12 inches in a foot. Write a program in which you initialize the integer
variable inches to a value, say 46, assign the number of feet to feet, and print the
result.
Variables
Inches, feet
Output
56 inches is 3.83333 feet
1 - 12
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
1. Of the following, which are invalid variable names? Why are they invalid?
i. Gnash
ii. union
iii. 9Times
iv. too_many
3. In the C you use, in what data types of the following values be stored? In what
data types could they actually fit?
i. 91
ii. 45
iii. 48652
iv. 16.25
4. What are the values and data types of the following expression?
i. 7/4
ii. 9 / 2. + 25 / 3
iii. 6 + 4.8 / 2 * 3
iv. 25 % 5 + 12.5 * 2 / 5
5. If x = 5 and y = 2 and both are integers, what are the values of the following
expressions?
i. x % y + 14.6 / y
ii. y = 1. * x / 2 + 3.5
iii. y=y*x
iv. y = 16.2 * x / 3
1 - 13
CHAPTER 1: INTRODUCTION TO C PROGRAMMING IT202
i. Which characters can be used in C variable names? What can the name
start with?
ii. Are books and BOOKS the same variable?
iii. What does the data type say about a value or variable?
iv. What does a declaration do in a program?
v. Which data types are integral? Which are floating-point?
vi. What characters do we use at the end of numbers to declare values as
unsigned? Long? Unsigned long? Float? Long double?
vii. How do we put a quote mark in string value?
viii. How does C interpret two string values separated only by whitespace?
1 - 14
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
• Understand how to prompt messages on the screen for data entry purposes
• Learn how to capture data by incorporating the scanf( ) function
• Understand why and when to include appropriate Conversion Codes in C program
• Understand and appreciate the purpose of Size Modifiers in C program
• Create simple data entry program to capture input temporary
2-1
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
2.1 Output
Output in C means display messages and values on screen. The printf( ) function is used
to produce output. When use the printf( ) function to display something, appropriate
Conversion Code should be included depends on the type of values to be displayed. The
Size Modifiers enables a programmer to format the output for variable.
Conversion codes in C are used to reserve space in the output for some other values to
print – the value of a variable or expression, and to show how those values should be
converted to characters and printed. All conversion codes begin with a % symbol and
with a type specifier. A list of conversion codes for printf( ) is found in Table 2-1. The
following example illustrates how conversion code is used.
Example:
void main(void)
{
int x = 100;
printf(“The value in variable x is: %i”, x);
}
Explanation:
All the characters in the format are printable except the conversion code %i, which
reserves space for an integer value to print. The format requires a value to fill in that
space, so C takes the value of x, and puts it there.
2-2
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
Size modifier normally appears before the type specifier. We may set the minimum width
of a print field by putting a number before the type specifier, if one exists. The format of
the size modifier with width and precision is as below:
%[width][.precision][size] type
Example:
Statement Output
The width parameter is the minimum width. If the value to be printed has more
characters than the minimum, the entire value will be printed. By default, fields with
specified widths will be right-justified, that is, line up on the right side. They will be
padded with leading spaces. In addition to the width, the precision parameter comes after
the width if there is one, before the size modifier if there is one, and always starts with a
decimal point. The precision parameter for floating point data type specifies the number
of digits after the decimal point; the value will be rounded to that number of digits. The
width is the minimum width of the entire field, inclusive of signs (negative or positive),
decimal points, and digits after the decimal point.
2.2 Input
The input in C enables user to enter values for e.g. data entry. The function enables
programmer to prompt for data entry during program execution. Appropriate Conversion
Codes should be specified in order to display the required value. Consider the following
example:
2-3
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
Example:
or
Explanation:
The scanf( ) function takes input characters and then divide them into sets of characters
to convert to appropriate data types for the locations. The ampersands (&) in front of the
variable a, and b is the locations in main memory – the memory addresses of a, and b.
When the scanf( ) function executes, it matches the character in the input stream with the
characters in the control string. A single conversion code in the control string will match
input characters following the steps below:
1. Leading white space characters (spaces, tabs, and newlines) are skipped (except
for type specifier c). A previous scanf( ) will leave a newline in the input stream.
2. Subsequent characters will be taken for conversion and assignment up to the first
character that is inappropriate for the data type.
For example, if the input characters are ***46.8\n (the * indicates a space), a %i
conversion code would skip the three spaces and store the value 46 at the memory
location of the variable, leaving the characters .8\n for the next match. The conversion
stopped there because a decimal point is not an appropriate character for an integer
conversion.
2.2.2 Prompts
The printf( ) before each scanf( ) is known as prompt. The printf( ) exist to display
something on the screen to tell the person at the keyboard what to type in.
2-4
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
In the sample program run, 1.23 was typed in as the integer. The scanf( ) converted to the
first inappropriate character, the decimal point, and assigned the value 1 to the next
variable (of the float type). At that point, the input stream contained .23. The next scanf()
found characters in the stream, and they were appropriate for a float, so without waiting
for any further input, it converted them and assigned the value 0.23 to the next variable
(of the float type). To clean up some of the problems we may encounter from characters
left in the input stream, we can empty the stream with the following statement:
OR
fflush(stdin);
2-5
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
#include <stdio.h>
#define FEET_METER 3.2808
void main(void)
{
char letter = ‘A’;
int meters = 2;
float feet = 25.8;
Output
The character A can also be interpreted as the number 65.
At 3.280800 feet per meter, 2 meters is 6.5616 feet.
25.799999 feet is 7.86394 meters.
Program 2-2
#include <stdio.h>
void main(void)
{
long eastville = 322536, westport = 643, gotham = 6445821;
Output
Eastville has 322536 people.
Westport has 643 people.
Gotham has 6445821 people.
2-6
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
Program 2-3
#include <stdio.h>
void main(void)
{
float x = 1.2345;
int y = 1;
Output
Number positions: 123456
The value of x is 1.23
The value of x is 1.2
The value of y is 01
Program 2-4
#include <stdio.h>
void main(void)
{
float food, drink, tip, total, tax, bill;
2-7
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
Output
Food total: 34.82
Beverages: 16.75
Tip: 6
Tax: 3.45
Please pay: 61.02
Program 2-5
#include <stdio.h>
void main(void)
{ int i;
long l;
float f;
double d;
Output
Enter values for an int and a longl: 524 79735
Your int is 524 and long is 79735
2-8
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
1. Write a program that accepts two numbers from the keyboard and prints the
following information.
Variables
first
second
Output
First number? 7
Second number? 2
The second number goes into first 3 times
with a remainder of 1.
The quotient is 3.5.
2. Write a program to print out a customer bill for Ajax Auto Repair. The parts and
labor charges are input and a 6 percent sales tax is charged on parts but not on
labor. Your program should display the following information.
Variables
Parts
Labor
SalesTax
Total
Output
PARTS? 104.50
LABOR? 182.15
AJAX AUTO REPAIR
SERVICE INVOICE
PARTS $104.50
LABOR 182.15
SALES TAX 6.27
TOTAL $292.92
2-9
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
3. Write a program that will accept keyboard input of various coins and return the
total value.
Variables
input ( value from keyboard)
total (to accumulate the value of the inputs)
Output
Fifty cents? 3
Twenty cents? 2
Ten cents? 1
Five cents? 2
One cents? 3
Your total is: $ 1.93.
4. Write a program that accepts a number of seconds from the keyboard and
converts it into days, hours, minutes, and seconds. Use integer arithmetic and the
remainder operator.
Variables
seconds
Output
How many seconds? 106478
Days: 1
Hours: 5
Minutes: 34
Seconds: 38
2 - 10
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
Constants
Variables
Hours
HourlyPay
GrossPay
FIT Federal income tax witholding
FICA Social security tax witholding
Savings Payroll savings
Retirement
NetPay Gross pay less deductions
Output
HOURS? 40
HOURLY PAY? 7.50
2 - 11
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
a. 46 |46*|
b. 8.046 |**8.05|
c. 73.28 |73.3*|
d. 86425 |*086425|
e. 214 214.00
f. ‘C’ 67
g. 67 C
h. 35.6 |***35.600|
2. Show the output of these values given the printf( ) conversion codes (use * to
denote space).
a. ‘A’ %3i
b. ‘A’ %c
c. 4.26 %6.1f
d. 425 %g
e. 381.67 %3.1f
f. 16 %4.3i
g. 1.2345 %.2f
h. 52 %5i
2 - 12
CHAPTER 2: BUILDING SIMPLE C PROGRAM IT202
2 - 13
CHAPTER 3: THE SELECTION STRUCTURE IT202
3-1
CHAPTER 3: THE SELECTION STRUCTURE IT202
Sequence. A sequence structure is one operation after another. This is the structures been
demonstrated in the previous chapter’s program.
Selection. A selection structure is a choice between sets of operations. There will be some
sample programs on Selection structure in this chapter.
3.2 Conditions
A condition enables the computer to perform certain tasks base on the outcome of
evaluation. The statements execution would not be in any sequence whereby some
statements might not be executed. Execution is normally base on the outcome of
conditions – true or false. A condition contains one or more comparisons that relate one
to another. Comparisons can be achieved by incorporating Relational operators and
Logical operators in a condition. A condition in C typically consists of one or more
comparisons that relate one value to another.
Example:
x + 10 > 20
Explanation:
The above example condition compares the value of the expression x + 10 with the value
of 20. An expression is anything that reduces to a single value. The comparison operator,
> tells the computer how the comparison should be made.
The comparison operator comes from one of two categories: relational operators and
equality operators. The relational operators have higher precedence than equality
operators. Table 3-1 shows a list of relational and equality operators. The equal operator
(==) is not the same as the assignment operator (=).
3-2
CHAPTER 3: THE SELECTION STRUCTURE IT202
AND Operator
If the comparison on both sides is true, then the whole condition is true. If even one
comparison is false, then the whole condition is false.
3-3
CHAPTER 3: THE SELECTION STRUCTURE IT202
C1 && C2 Result
True True True
True False False
False True True
False False False
Example:
Conditions Result
2 + 7 != 38 / 2 False
16 % 3 < 22 == 6 / 3 >= 2 True
9 >- 7 + 3 && 7 % 3 == 1 True
OR Operator
By using the OR ( | | ) operator, if either or both of the comparisons are true, then the
whole condition is true. Both comparisons would have to be false for the whole condition
to be false.
C1 || C2 Result
True True True
True False True
False True True
False False False
Example:
Conditions Result
6 > 2 || 25 / 5 == 4 True
7 <= 9 || 6 > 5 && 7 == 2 True
(7 <= 9 || 6 > 5) && 7 == 2 False
3-4
CHAPTER 3: THE SELECTION STRUCTURE IT202
NOT Operator
The NOT operator acts on only one expression. The logical NOT operator makes what
was true false, and what was false true.
if (condition) if (condition)
statement; OR statement;
else
statement;
if (condition) if(condition)
{ {
statement; statement;
statement; OR statement;
} }
else
{
statement;
statement;
}
3-5
CHAPTER 3: THE SELECTION STRUCTURE IT202
switch (integral_expression)
{
case integral_value:
statement;
statement;
………
break;
case as many as are necessary;
default:
statement;
statement;
}
The integral_expression following the switch key word must evaluate to some integral
data type, char or int; floating-point results are not allowed. The value of the expression
becomes a case value to be matched to the possible case identifiers within the statement
block following the switch. For example, if the integral_expression evaluated to 6, the
switch would look for case 6:.
3-6
CHAPTER 3: THE SELECTION STRUCTURE IT202
#include <stdio.h>
#define SECRET 10
void main(void)
{ int guess;
Output
What’s your guess? 10
You guessed that the secret number was 10.
3-7
CHAPTER 3: THE SELECTION STRUCTURE IT202
Program 3-2
#include <stdio.h>
Output
What’s your guess? 0.1
You guessed that the secret number was 0.1.
3-8
CHAPTER 3: THE SELECTION STRUCTURE IT202
Program 3-3
#include <stdio.h>
void main(void)
{ float weight, price = .2;
Output
3-9
CHAPTER 3: THE SELECTION STRUCTURE IT202
Program 3-4
#include <stdio.h>
void main(void)
{ float weight, price = .2;
Output
3 - 10
CHAPTER 3: THE SELECTION STRUCTURE IT202
Program 3-5
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
void main(void)
{
float Amt=0, TaxRate;
char Code;
gotoxy(5,10);
printf("Enter your country code [S/M/I]: ");
scanf(" %c", &Code);
gotoxy(5,11);
cprintf("Enter your purchase amount: ");
scanf("%f", &Amt);
if (toupper(Code) == 'S')
{
gotoxy(38,10);
printf("Singapore (8% tax rate)\n");
TaxRate = 0.08;
}
else
if(toupper(Code) == 'M')
{
gotoxy(38,10);
printf("Malaysia (6% tax rate)\n");
TaxRate = 0.06;
}
else
if(toupper(Code) == 'I')
{
gotoxy(38,10);
printf("Indonesia (3% tax rate)\n");
}
else
{
gotoxy(38,10);
printf("Invalid code\n");
}
gotoxy(5,14);
printf("Tax amount: %.2f", Amt * TaxRate);
gotoxy(5,15);
printf("Amount payable: %.2f", Amt + Amt * TaxRate);
}
3 - 11
CHAPTER 3: THE SELECTION STRUCTURE IT202
Output
Enter your country code [S/M/I]: S Singapore (8% tax rate)
Enter your purchase amount: 100
Tax amount: 8.00
Amount Payable: 108.00
Program 3-6
#include <stdio.h>
void main(void)
{
int Age;
3 - 12
CHAPTER 3: THE SELECTION STRUCTURE IT202
Output
Enter your age (1-99 only): 125
Invalid age!
Program 3-7
#include <stdio.h>
#include <ctype.h>
void main(void)
{
char Gender;
Output
Enter your gender [F/M]: F
Female
3 - 13
CHAPTER 3: THE SELECTION STRUCTURE IT202
Program 3-8
#include <stdio.h>
void main(void)
{
char Gender;
Output
Enter your gender [F/M]: F
Female
3 - 14
CHAPTER 3: THE SELECTION STRUCTURE IT202
Program 3-9
#include <stdio.h>
void main(void)
{
int Choice;
float Value1, Value2;
Output
Enter value 1: 40
3 - 15
CHAPTER 3: THE SELECTION STRUCTURE IT202
Enter value 2: 30
1. Multiply
2. Divide
3. Subtract
4. Add
Enter your choice [1-4]: 1
The result is 1200
Enter value 1: 40
Enter value 2: 30
1. Multiply
2. Divide
3. Subtract
4. Add
Enter your choice [1-4]: 3
The result is 10
Enter value 1: 40
Enter value 2: 30
1. Multiply
2. Divide
3. Subtract
4. Add
Enter your choice [1-4]: 4
The result is 70
3 - 16
CHAPTER 3: THE SELECTION STRUCTURE IT202
Program 3-10
#include <stdio.h>
void main(void)
{ float price;
char grade;
Output
3 - 17
CHAPTER 3: THE SELECTION STRUCTURE IT202
Variables
Number1, number2
Outputs
Enter two numbers 48 52.33
52.33 is greater than 48.
Outputs
Enter two numbers 88 88
They are equal.
2. Adams County (country code A) has a 7 percent sales tax rate; the rest of the state
a 6 percent rate. Write a program to print out the amount owed on purchase
including sales tax, given the amount of the purchase and the county.
Variables
Purchase
County
TaxRate
Outputs
AMOUNT OF PURCHASE? 100
COUNTY? A
TOTAL BILL: 107.00
3 - 18
CHAPTER 3: THE SELECTION STRUCTURE IT202
Variables
grade
grade_points
Output
Letter grade: B
Grade point: 3
Letter grade: D
Grade point: 1
4. The Ace Courier Service charges $10 for the first pound or fraction thereof and $6
per pound for anything over one pound. Write a program that figures the charges.
Variables
weight
Output
WEIGHT: .7
CHARGE: 10
WEIGHT: 2.5
CHARGE: 19
WEIGHT: 4.2
CHARGE: 29.2
3 - 19
CHAPTER 3: THE SELECTION STRUCTURE IT202
5. Social security (FICA) tax is currently 7.65 percent of earnings up to $50.00 for
the year. Write a program that accepts earnings for the current week and previous
earnings up to the current week, and returns the amount of FICA tax to be
withheld.
Variables
CurrentEarnings
PrevEarnings
Output
This week’s pay? 700
Previous pay? 12600
FICA to withhold: $53.55
6. Write a program that prompts the user to enter two positive integers, and then
tests whether the larger integer is exactly divisible by the smaller one. In the
process, check the input values are both valid (greater than zero), and establish
which of them is the larger.
Variables
value1
value2
Output
3 - 20
CHAPTER 3: THE SELECTION STRUCTURE IT202
7. The ABC Insurance Company determines auto insurance rates based on a driver’s
age, the number of tickets in the last three years, and the value of a car. The base
rate is 5 percent of the value of the car. Drivers under 25 years of age pay 15
percent over the base, and drivers from 25 through 29 pay 10 percent over. A
driver with one ticket pays 10 percent over the rates already figured. Two tickets
draws a 25 percent extra charges; three tickets adds 50 percent; and drivers with
more than three tickets are refused. Write a program to show a driver’s insurance
premium.
Variables
Outputs
DRIVER’S AGE? 35
NUMBER OF TICKETS? 1
VALUE OF CAR? 10000
PREMIUM: $550
DRIVER’S AGE? 29
NUMBER OF TICKETS? 2
VALUE OF CAR? 15000
PREMIUM: $1031.25
DRIVER’S AGE? 19
NUMBER OF TICKETS? 3
VALUE OF CAR? 850
PREMIUM: $73.3125
3 - 21
CHAPTER 3: THE SELECTION STRUCTURE IT202
1. In mathematics, we might state a range from x as 1 < x < 5. Show how we should
write the following range expression in C.
i. 1<x<5
ii. 16 ≥ x ≥ -7
iii. 22.6 ≥ x ≥ 12.03
iv. 36 < x ≤ 115
i. a>= c – b
ii. b / 2 == a | | c< 3
iii. b < c – 2 | | a * 3 >= c && b > a
iv. 5 | | !b && c
3. With traffic lights, R (for red) means “Stop”, Y means “Caution”, and G means
“Go”. Any other color letter means “Weird”. Given the statement below, write the
program segment that prints what the color letter means. Use else if construct.
printf(“Color letter:”);
scanf(“ %c”, &color);
3 - 22
CHAPTER 3: THE SELECTION STRUCTURE IT202
int x = -1;
if (x * 30 / 10 > 5 – 6 * x)
x = x * 10;
else
x = x + 10;
iv. The tree control structures are ________, ___________ and _________.
v. A program that uses human language rather than a computer language is said
to be written in _____________.
3 - 23
CHAPTER 3: THE SELECTION STRUCTURE IT202
viii. A condition typically consists of one or more comparisons that compare one
value to another. A comparison has the form ___________.
3 - 24
CHAPTER 4: ITERATION IT202
Chapter 4 – Iteration
Objectives
The Iteration Structure in C enables some operations to be repeated until certain
conditions are fulfilled or no longer valid. It saves the programmer’s time in repeating
similar codes/statements/instructions in a program. Additionally, the Iteration Structure
simplifies and organizes lengthy programs. At the end of this lesson, students would have
achieved the following objectives.
4-1
CHAPTER 4: ITERATION IT202
A pretest loop begins with the keyword while. The general form of this configuration is
shown in Figure 4-1. Condition is enclosed in parenthesis; each statement in the block is
indented one level and ends with a semicolon; and there is no semicolon after the block’s
closing brace. The C compiler requires the punctuation. The indentation and line endings
are for program readability.
4-2
CHAPTER 4: ITERATION IT202
The body in posttest loop would be executed once no matter what. The posttest loops
begins with a do and has general form as shown in Figure 4-2. There is semicolon at the
end of condition.
do{
statement;
statement;
} while (condition);
Accumulating
Total = Total + value; Total = Total * value;
OR OR
Total += value; Total *= value;
Counting
++times; or
times++; or
times = times + 1; or
times += 1;
4-3
CHAPTER 4: ITERATION IT202
4-4
CHAPTER 4: ITERATION IT202
statement;
…… ……
}
statement;
statement;
….. …. ..
4-5
CHAPTER 4: ITERATION IT202
Program 4-1
#include <stdio.h>
void main(void)
{ float price;
short quantity;
char answer;
Output
Do you wish to enter a purchase (Y/N)? y
Enter ‘price quantity’: 1.98 6
The total for this item is $11.88
Another (Y/N)? Y
Enter ‘price quantity’: 4.29 15
The total for this item is $ 64.35
Another (Y/N)? n
Thanks you for your patronage.
4-6
CHAPTER 4: ITERATION IT202
Program 4-2
#include <stdio.h>
void main(void)
{ float price;
short quantity;
char answer;
do
{ printf("Enter 'price quantity': ");
scanf("%f %hi", &price, &quantity);
printf("The total for this item is $%6.2f.\n", price * quantity);
printf("Another (Y/N)? ");
scanf(" %c", &answer);
}while (answer == 'Y' | | answer == 'y');
printf("Thank you for your patronage.\n");
}
Output
Enter ‘price quantity’: 2.45 12
The total for this item is $29.40
Another (Y/N)? Y
Enter ‘price quantity’: .99 4
The total for this item is $ 3.96
Another (Y/N)? n
Thanks you for your patronage.
4-7
CHAPTER 4: ITERATION IT202
Program 4-3
#include <stdio.h>
#include <conio.h>
void main(void)
{
int Choice;
float Value1, Value2;
do{
clrscr( );
printf("Enter value 1: ");
scanf("%f", &Value1);
printf("Enter value 2: ");
scanf("%f", &Value2);
printf("\n1. Multiply");
printf("\n2. Divide");
printf("\n3. Subtract");
printf("\n4. Add");
printf("\n5. Quit");
printf("\nEnter your choice [1-5]: ");
scanf("%i", &Choice);
switch(Choice)
{
case 1:
printf("\nThe result is: %g", Value1*Value2);
break;
case 2:
printf("\nThe result is: %g", Value1/Value2);
break;
case 3:
printf("\nThe result is: %g", Value1-Value2);
break;
case 4:
printf("\nThe result is: %g", Value1+Value2);
break;
case 5:
printf("\nThank you");
break;
default:
printf("\nInvalid choice!");
}
}while (Choice != 5);
}
Output
Enter value 1: 40
4-8
CHAPTER 4: ITERATION IT202
Enter value 2: 30
1. Multiply
2. Divide
3. Subtract
4. Add
5. Quit
Enter your choice [1-4]: 1
The result is 1200
Enter value 1: 40
Enter value 2: 30
1. Multiply
2. Divide
3. Subtract
4. Add
5. Quit
Enter your choice [1-4]: 3
The result is 10
Enter value 1: 40
Enter value 2: 30
1. Multiply
2. Divide
3. Subtract
4. Add
5. Quit
Enter your choice [1-4]: 5
Thank you.
4-9
CHAPTER 4: ITERATION IT202
Program 4-4
#include <stdio.h>
#include <conio.h>
#define Code 999
void main(void)
{
int Password, Valid, Try=1;
do{
clrscr( );
gotoxy(8,10);
printf("Enter password: ");
scanf("%i", &Password);
if(Password != 999)
{
printf(“Invalid!”);
Valid = 0;
Try += 1;
}
else
Valid = 1;
} while (!Valid && Try <= 3);
if(Try > 3)
printf("\n\n\tMaximum 3 try only!");
else
printf("\n\n\tAccess approved.");
}
Output
Enter password: 111
Invalid!
4 - 10
CHAPTER 4: ITERATION IT202
#include <stdio.h>
void main(void)
{ float price;
float total = 0;
short quantity;
printf("Enter 0 0 to quit.\n");
printf("Enter 'price quantity': ");
scanf("%f %hi", &price, &quantity);
while (price != 0)
{ printf("The total for this item is $%6.2f.\n", price * quantity);
total += price * quantity;
printf("Enter 'price quantity': ");
scanf("%f %hi", &price, &quantity);
}
printf("Your total is $%6.2f.\n", total);
}
Output
Enter 0 0 to quit.
Enter ‘price quantity’: 6.35 8
The total for this item is $50.80.
Enter ‘price quantity’: 2.50 10
The total for this item is $25.00.
Enter ‘price quantity’: 0 0
Your total is $75.80.
4 - 11
CHAPTER 4: ITERATION IT202
Program 4-6
#include <stdio.h>
void main(void)
{ float price;
float total = 0;
short quantity, items = 0;
printf("Enter 0 0 to quit.\n");
printf("Enter 'price quantity': ");
scanf("%f %hi", &price, &quantity);
while (price != 0)
{ printf("The total for this item is $%6.2f.\n", price * quantity);
total += price * quantity;
items += 1;
printf("Enter 'price quantity': ");
scanf("%f %hi", &price, &quantity);
}
printf("Your total is $%6.2f for %hi different items.\n", total,items);
}
Output
Enter 0 0 to quit.
Enter ‘price quantity’: 22.95 3
The total for this item is $68.85.
Enter ‘price quantity’: 7.29 8
The total for this item is $58.32.
Enter ‘price quantity’: 15 4
The total for this item is $60.00.
Enter ‘price quantity’: 0 0
Your total is $187.17 for 3 different items.
4 - 12
CHAPTER 4: ITERATION IT202
Program 4-7
#include <stdio.h>
void main(void)
{ int count;
Output
1
2
3
Finished, but why is the count 4?
Program 4-8
#include <stdio.h>
void main(void)
{ int n, count, factorial;
4 - 13
CHAPTER 4: ITERATION IT202
Output
Enter a positive integer: 5
Integer Factorial
5 120
4 24
3 6
2 2
1 1
4 - 14
CHAPTER 4: ITERATION IT202
Variables
score (score input)
a_s, b_s, c_s, d_s, f_s (counters for letter grades)
Output
SCORE? 92
THE GRADE IS A
:
SCORE? –1
2 A’s
2 B’s
1 C’s
0 D’s
1 F’s
4 - 15
CHAPTER 4: ITERATION IT202
2. Write a program to create a multiplication table for all combinations of two numbers
from 1 to 8.
Variables
Multiplier
Multiplicand
Output
1 2 3 4 5 6 7 8
1 1 2 3 4 5 6 7 8
2 2 4 6 8 10 12 14 16
3 3 6 9 12 15 18 21 24
4 4 8 12 16 20 24 28 32
5 5 10 15 20 25 30 35 40
6 6 12 18 24 30 36 42 48
7 7 14 21 28 35 42 49 56
8 8 16 24 32 40 48 56 64
3. Write a program that iterates through the odd numbers less than 30, and outputs the
square of each number.
Variable
x
Output
1 9 25 49 81 121 169 225 289 361 441 529 625 729 841
4 - 16
CHAPTER 4: ITERATION IT202
4. Create a program that loops 30 times, but only outputs numbers that are not divisible
by 3 or 5. Decide on the most appropriate form of loop, and use an if statement inside
it.
Variable
x
Output
3 5 9 10 12 15 18 21 24 25 27 30
5. Write C codes to accept two integer values and display the multiplication result on the
screen. Your program should iterate until user enter two negative values.
Variable
x, y
Output
Enter two integer values: 10 2
The multiplication result is 20
4 - 17
CHAPTER 4: ITERATION IT202
6. Write a C program that produces the following patterns using 2 for loops.
Variables
x, y
Output
1 1
2 2 1
3 3 2 1
4 4 3 2 1
5 5 4 3 2 1
6 6 5 4 3 2 1
7 7 6 5 4 3 2 1
7. Write a program to produce the following output. Use nested for loops.
Variables
x, y
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1
4 - 18
CHAPTER 4: ITERATION IT202
x = 14; y = 65;
While (x >= 3) while (y <= 85)
{ {
printf(“%i\n”, x); printf(“%i\n”, y);
x -= 5; y += 5;
} }
a. y += a * ++c;
b. y = (y + a) * c; c++;
4 - 19
CHAPTER 4: ITERATION IT202
c. y = y + a * c; c++;
d. c++; y = y + a * c;
e. none of the above
int t = 0; b = 0; s = 0; z = 0;
scanf(“%i”, &t);
{
s += t;
++z;
scanf(“%i”, &t);
}
b = s / z;
4 - 20
CHAPTER 4: ITERATION IT202
int x = 1;
for (x=11, x >= 1; x -= 3)
printf(“%4i”, x * x);
{ int i = 0, x = 0;
x = 14;
while (x >= 3)
{
printf(“%d”, x);
x -= 5;
}
x = 65;
while (y <= 85)
{
printf(“%d”, y);
x += 5; }
14. Answer questions (i) through (iii) by using the following C codes.
4 - 21
CHAPTER 4: ITERATION IT202
#include <stdio.h>
main( )
{
int a, b;
for (a = 1; a < 3; ++a)
for (b = 1; b <= 3; b++)
printf(“%4d”, a+b);
}
4 - 22
CHAPTER 5: FUNCTION IT202
Chapter 5 – Function
Objectives
Functions in C enable program segments to be grouped as modules. The introduction
of function simplifies and organizes C program’s structure. There are some reasons and
advantages of using functions in C. Functions would enable (i) modularity to be
implemented easily, (ii) increase program’s readability by grouping of some similar
tasks, (iii) improve debugability where errors are easily identified and isolated, (iv)
allows repeatability where some segment of codes could be repeated without repeating
retyping, and (v) enables reusability where new programs are written by using as much
code as possible from old programs. At the end of this chapter, students would have
learned what is function and how to include functions in program as follow.
5-1
CHAPTER 5: FUNCTION IT202
Suppose you have a section of code in your program that calculates the square root of a
number, you don’t want to have to write the same instructions all over again. Instead, in
effect, you want to jump to the section of code that calculates square roots and then jump
back again to the normal program flow when you are done. In this case, a single section
of code can be used many times in the same program. The saving of code is illustrated in
Figure 5-1.
…..
Code written twice
if function not used
…..
…..
…..
Calling program
main( )
{
…… func( )
…… {
Code written
…….
func( ); only once if
…….
…… function used
…….
…… }
func( );
…..
…..
}
5-2
CHAPTER 5: FUNCTION IT202
Program organization
By using the idea of subroutine, make it easier to organize programs and keep track of
what they were doing. If the operation of the program could be divided into separate
activities and each activity placed in a separate subroutine, each subroutine could be
written and checked out more or less independently. Separating the code into modular
functions also made programs easier to design and understand.
Independence
By making subroutines as independent from the main program and from one another
possible. For instance, subroutines were invented that had their own “private” – that is,
variables that couldn’t need to worry about accidentally using the same variable names in
different subroutines; the variables in each subroutine were protected from inadvertent
tampering by other subroutines. Thus is was easier to write large and complex programs.
The function itself is referred to as function definition. The definition starts with a line
that includes the function name, among other elements.
Example:
Function definition, note that
void func(void ) there is NO semicolon at the end.
{
statement;
statement;
…..
….
}
5-3
CHAPTER 5: FUNCTION IT202
Explanation:
Take note that the declarator doesn’t end with a semicolon. It is not a program statement;
it tells the compiler that a function is being defined. The function definition continues
with the body of the function: the program statements that do the work. The body of the
function is enclosed in braces. In the above example, the func is a user-defined function
name.
As with the C library functions we have seen, such as printf( ) and getche( ), our user-
written function func( ) is called from main( ) simply by using its name, including the
parentheses following the name. The parentheses let the compiler know that you are
referring to a function and not to a variable or something else. Calling a function like this
is a C statement, so it ends with a semicolon.
Example:
void main( )
…..
Function call, note that
func( ); there is a semicolon at
the end.
…..
….
The function prototype (declaration) is a third function related element. The function
prototype looks very much like the declarator line at the start of the function definition,
except that it ends with a semicolon. A function is declared in a similar way at the
beginning of a program before it is called. The function declaration tells the compiler the
name of the function; the data type the function returns and data types of the function’s
arguments. In our example, the function returns nothing and takes no arguments; hence
there are two voids.
5-4
CHAPTER 5: FUNCTION IT202
Example:
Function prototype, note
void func(void ); that there is semicolon at
the end.
The key thing to remember about the prototype is that the data type of the return value
must agree with that of the declarator in the function definition, and the number of
arguments and their data types must agree with those in the function definition.
We could declare variables in our function, these variables are known as local variables,
whereby they are only known within the function, and other functions are not allowed to
access them. A local variable will be visible to the function it is defined in, but not to
others. A local variable used in this way is known as automatic variable, because it is
automatically created when a function is called and destroyed when the function returns.
The length of time a variable lasts is called lifetime.
Example:
void func(void)
5-5
CHAPTER 5: FUNCTION IT202
A function that uses no arguments but returns a value is a slightly more complicated kind
of function: one that returns a value. When the function is called, it gets a certain piece of
information and returns it to you. The function getche( ) operates in just this way, when it
is called – without giving it any information – and it returns the value of the first
character typed on the keyboard.
Example:
int funct(void);
void main(void)
{ int y;
….
….
y = funct( );
….
}
int funct(void)
{ int x;
…
…
return (x);
}
The return statement has two purposes. First, executing it immediately transfers control
from the function back to the calling program. Second, whatever is inside the parentheses
following return is returned as a value to the calling program. The return statement need
not be at the end of the function; as soon as it’s encountered, control will return to the
calling program. The return statement can also be used without a value following it, and
no value would be returned to the calling program. The return statement can only be used
to return a single value.
5-6
CHAPTER 5: FUNCTION IT202
The mechanism used to convey information to a function is the argument. In the function
definition, a variable name could be placed in the parentheses. This ensures that the value
included between parentheses in the main program is assigned to the variable between
parentheses in the function definition. This is shown schematically in Figure 5-2.
We can pass as many arguments as we like to function. The process of passing two
arguments is similar to one. The value of the first actual argument in the calling program
is assigned to the first formal argument in the function, and the value of the second actual
argument is assigned to the second formal argument, as shown in Figure 5-3.
5-7
CHAPTER 5: FUNCTION IT202
10
20
void main(void)
{
……
…… void funct(int x, int y)
{
funct(10, 20); ……
……
……. ……
……. }
}
Function
Calling program
Sometimes, it is desirable to use a variable known to all the functions in a program, rather
then just one. This is true when many different functions must read or modify a variable,
making it clumsy or impractical to communicate the value of the variable from function
to function using arguments and return values. In this case, we use an external variable,
or sometimes also known as global variable. The use of external variables should be
limited, due to some reasons such as, first, external variables are not protected from
accidental alteration by functions that have no business modifying them. Second, external
variables use memory less efficiently than local variables.
5-8
CHAPTER 5: FUNCTION IT202
Example:
#include <stdio.h>
void func1(void);
void main(void)
…..
…..
5-9
CHAPTER 5: FUNCTION IT202
#include <stdio.h>
void info(void);
void main(void)
{ double gross, tax;
int dependents;
void info(void)
{ int emp_id, emp_num, dept;
5 - 10
CHAPTER 5: FUNCTION IT202
Program 5-2
#include <stdio.h>
void info(void);
double gross_pay(void);
void main(void)
{ double gross, tax;
int dependents;
double gross_pay(void)
{ double hours, rate, gross;
printf("Hours? ");
scanf("%lf", &hours);
printf("Rate? ");
scanf("%lf", &rate);
gross = hours * rate;
printf("Gross pay: %7.2f\n", gross);
return gross;
}
void info(void)
{ int emp_id, emp_num, dept;
5 - 11
CHAPTER 5: FUNCTION IT202
Program 5-3
#include <stdio.h>
void main(void)
{
printf("\nThis message was displayed in the Main function");
Sub( );
printf("\nBack to Main function again");
}
5 - 12
CHAPTER 5: FUNCTION IT202
Program 5-4
#include <stdio.h>
#include <conio.h>
float Value1, Value2; // global variables (for all the functions to access)
void main(void)
{
float Result; // local variable (access within main( ) only)
Display( );
Enter( );
Result = Calculate(Value1, Value2);
printf("\n\tThe addition result is: %g",Result);
}
5 - 13
CHAPTER 5: FUNCTION IT202
Program 5-5
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
char Gender, Mode; // global variables (for all the functions to access)
void main(void)
{
enterGender( );
enterMode( );
printf("\n\tBye!");
}
void enterGender(void)
{
int Okay;
do{
gotoxy(10,10);
printf("Enter gender [F/M]: ");
gotoxy(35,10);
scanf(" %c", &Gender);
Okay = Validate(Gender,'F', 'M');
if (!Okay)
{
gotoxy(10, 15);
printf("Invalid!");
getch( );
gotoxy(10, 15);
clreol( ); // clear end of line at col 10, row 15
}
}while (!Okay);
}
void enterMode(void)
{
int Okay;
do{
gotoxy(10,11);
5 - 14
CHAPTER 5: FUNCTION IT202
5 - 15
CHAPTER 5: FUNCTION IT202
1. Create a function whose job is to print a page heading. It should print the next
page number passed to it. Use the following driver – Main( ) function segment –
to test your function.
Driver
void main(void)
{
int p;
for (p = 1; p <= 5; ++p)
page(p);
}
Output
5 - 16
CHAPTER 5: FUNCTION IT202
2. Write a program that accepts any number from the keyboard and tells you whether
it is a nonnegative integer. The number should be sent to the function int_test( ),
which returns either the integer value, or –1 if the number is negative, or zero if it
is nonnegative but not an integer. Inputs should continue until zero is input.
int_test( )
value (from main( ) function)
result (value to return)
Output
Your number: 48
The number is 48,
Your number: -14.3
The number is negative
Your number: 12.562
The number is not an integer
Your number: 0
3. Write a program to make change in coins. The main( ) function should accept
input of the purchase and amount tendered, and the change( ) function should
print the number of dollars, fifty cents, twenty cents, ten cents and one cent.
main( )
purchase
tendered
change(amount)
cents -- convert from the float amount to the int cents.
5 - 17
CHAPTER 5: FUNCTION IT202
Output
Purchase: 2.50
Amount tendered: 4
Dollars: 1
Fifty cents: 5
Twenty cents: 0
Five cents: 0
One cents: 0
4. Write a simple calculator so that you can input an expression with two values
separated by an operator and the computer will print out the proper result. Your
calculator should include the ^operator for exponentiation. All calculations should
be done in an appropriate function (the function will be small) and the results
printed in main( ).
add( )
subtract( )
multiply( )
divide( )
exponentiation( )
a, b ---- Local variables for each function return
Output
Enter expression (q to quit): 50 + 45.20
95.20
5 - 18
CHAPTER 5: FUNCTION IT202
#include <stdio.h>
int funct (int);
void main(void)
{
int x;
for (x = 1; x < 10; ++x)
printf(“%4i”, funct(x));
}
int funct(int y)
{
return y * y;
}
9. The following program accepts two numeric values and displays the
multiplication result on the screen. Calculate( ) is a user-defined function that
performs multiplication and returns the result to main program body. Answer
questions (i) through (v) by using the following C program
#include <stdio.h>
void main(void)
{
int v1, v2, v3;
printf("Enter value 1 and value 2 ");
scanf("%i %i", &v1, &v2);
v3 = Calculate(v1, v2);
5 - 19
CHAPTER 5: FUNCTION IT202
10. Answer questions (i) to (v) by using the following C program segment
#include <stdio.h>
int funct (int);
void main(void)
{
int a, x;
for (x = 1; x < 10; ++x)
{
a = funct(x);
printf(“%4i”, a);
}
}
int funct(int y)
{
return y * y;
}
5 - 20
CHAPTER 5: FUNCTION IT202
11. Use the following C code to answer questions (i) through (x).
ii. If n is 2 and x is 3.0, what would get returned by the above function?
iii. How many times does the loop in the above code executed?
12. Choose the best answer for each of the situation described below function
definitions.
a. void sample(void)
b. char sample(int quantity)
c. int sample(void)
5 - 21
CHAPTER 5: FUNCTION IT202
ii. A function called root accepts two integer arguments and returns a
floating-point result.
a. float root(int a, b)
b. float root(int a, int b)
c. void root(void)
a. void convert(char a)
b. int convert(char)
c. char convert(char a)
5 - 22
CHAPTER 6: ARRAYS IT202
Chapter 6 – Arrays
Objectives
Array is a consecutive storage location in computer’s memory that stores similar type of
data. The array implementation and application is important if a list of elements/items or
records were to be manipulated. At the end of this chapter, students would have learned
what is array and how to include array in program as follow.
6-1
CHAPTER 6: ARRAYS IT202
Array Declaration
int SalesArray[10];
Array Initialization
Once an array is declared, individual slot could be used for storage and these slots are
referenced via index. The first slot starts at zero for example if an array contain ten slots
the last slot’s index would be nine. The following Figure 6-1 represents the organization
of array and the indices.
?? ?? ?? ?? ?? ?? ?? ?? ?? ??
0 1 2 3 4 5 6 7 8 9
Indices (0 – 9)
Each slot in the array could be referred by specifying the array name and the index. For
example, the statement SalesArray[2] would refer to third slot’s stored value (if any).
6-2
CHAPTER 6: ARRAYS IT202
printf(“%i”,SalesArray[0]);
printf(“%i”,SalesArray[1]);
…… ……. ….
…… ……. ….
printf(“%i”,SalesArray[98]);
printf(“%i”,SalesArray[99]);
6-3
CHAPTER 6: ARRAYS IT202
Program 6-1
#include <stdio.h>
#define DAYS_IN_WEEK 6
void main(void)
{ short sales[DAYS_IN_WEEK] = {3806, 28, 4522, 1183, 47, 12};
short day;
Output
Sales for day 1 = 3806
Sales for day 2 = 28
Sales for day 3 = 4522
Sales for day 4 = 1183
Sales for day 5 = 47
Sales for day 6 = 12
6-4
CHAPTER 6: ARRAYS IT202
Program 6-2
#include <stdio.h>
#define FLEET 5
int truck_in(void);
void main(void)
{ float weights[FLEET] = {0};
int truck;
int tot_trucks = 0;
float tot_weight = 0;
truck = truck_in();
while (truck) { printf("Weight? ");
scanf("%f", &weights[truck - 1]);
truck = truck_in();
}
printf("\nShipping Report\n");
printf(" Truck Weight\n");
for (truck = 1; truck <= FLEET; ++truck)
if (weights[truck - 1])
{ printf(" %5i %6.1f\n", truck, weights[truck - 1]);
++tot_trucks;
tot_weight += weights[truck - 1];
}
printf(" ----- ------\n");
printf("Total %5i %6.1f\n", tot_trucks, tot_weight);
}
int truck_in(void)
{ int truck;
do
{ printf("Truck (1 to %i, 0 to quit)? ", FLEET);
scanf("%i", &truck);
}while (truck < 0 || truck > FLEET);
return truck;
}
6-5
CHAPTER 6: ARRAYS IT202
Output
Truck (1 to 5, 0 to quit)? 7
Truck (1 to 5, 0 to quit)? 4
Weight? 1825.8
Truck (1 to 5, 0 to quit)? 72
Weight? 883.5
Truck (1 to 5, 0 to quit)? 1
Weight? 829.4
Truck (1 to 5, 0 to quit)? 0
Shipping Report
Truck Weight
1 829.4
2 883.5
3 1825.8
------- ---------
Total 4 3538.7
6-6
CHAPTER 6: ARRAYS IT202
Program 6-3
#include <stdio.h>
#define SIZE 5
void main(void)
{
int List[5]={0}, idx;
Output
Enter an integer value 1: 67
Enter an integer value 2: 58
Enter an integer value 3: 67
Enter an integer value 4: 48
Enter an integer value 5: 98
List
67
58
67
48
98
6-7
CHAPTER 6: ARRAYS IT202
Program 6-4
#include <stdio.h>
#define SIZE 5
void main(void)
{
int List[5]={0}, idx, Target, Found;
idx = 0;
do{
if (Target == List[idx])
{
printf("\nTarget %i found at index %i", Target, idx);
Found = 1;
}
else
Found = 0;
++idx;
} while (!Found && idx < SIZE);
if (!Found)
printf("\nNot found");
}
Output
Enter an integer value 1: 67
Enter an integer value 2: 58
Enter an integer value 3: 67
Enter an integer value 4: 48
Enter an integer value 5: 98
Enter an integer value to search: 48
Target 48 found at index 3.
6-8
CHAPTER 6: ARRAYS IT202
Program 6-5
#include <stdio.h>
#define SIZE 5
void main(void)
{
int List[5]={0}, idx ;
printf("\n\nData\tData * 2");
printf("\n----\t--------");
for (idx = 0; idx < SIZE; ++idx)
printf("\n%i\t%i", List[idx], List[idx] * 2);
}
Output
Enter an integer value 1: 67
Enter an integer value 2: 58
Enter an integer value 3: 97
Enter an integer value 4: 48
Enter an integer value 5: 98
Data Data * 2
------ -----------
67 134
58 116
97 194
48 96
98 196
6-9
CHAPTER 6: ARRAYS IT202
1. Write a program to input a set of five numbers and print them out in the reverse
order of input. Put both the input and printing in loops.
Variables
a[ ]
x
Output
Input five numbers:
0? 235
1? 256.23
2? 458
3? 265.12
4? 5
6 - 10
CHAPTER 6: ARRAYS IT202
2. Write a program that accepts input of five values from the keyboard and prints out
the values and their difference from the mean (average) value.
Variables
Value[ ]
Mean
Count
Output
Enter 5 values separated by space.
46.2 12.6 32.654 6 25.44
Number Value Difference
1 46.20 21.62
2 12.60 -11.98
3 32.65 8.08
4 6.00 -18.58
5 25.44 0.86
3. Write a program to accept five integral values into an array namely List, at the
end of data entry, the program will prompt user to enter a value to search from the
array. Your program should display appropriate message notifying the user
whether the search element is found in the array.
Variables
List[ ]
Target, counter
Output
Enter value[0]: 10
Enter value[1]: 20
6 - 11
CHAPTER 6: ARRAYS IT202
Enter value[2]: 35
Enter value[3]: 12
Enter value[4]: 8
6 - 12
CHAPTER 6: ARRAYS IT202
3. What is an array?
6. In the array declaration float stuff[10]; how many elements are allocated and
what is the index of the last allocated variable?
7. Given the declaration float stuff[5] = {1.1, 2.2, 3.3}; what will be the value of
stuff[1]? Of stuff[3]? Of stuff[5]?
10. Given the following array’s declaration statements, indicate whether valid or
invalid.
6 - 13
CHAPTER 6: ARRAYS IT202
i. C checks for subscripts that are out of range of an array’s declared size.
iii. The end of an array can easily be tracked through the use of a sentinel value.
iv. Unlike other variables, arrays must be initialized when they are declared.
ii. Given the declaration float y[100[; the highest value subscript for y would
be ________.
iii. Given the declaration float x[80[; the lowest value subscript for x would be
________.
a. Sorting
b. arranging
c. placing
6 - 14
CHAPTER 6: ARRAYS IT202
a. number
b. value
c. subscript
iii. The elements if an array are related by the fact that they ____.
a. are integers
b. contain values
c. have same name and type
6 - 15
CHAPTER 7: STRING IT202
Chapter 7 – String
Objectives
String in C is a list of alphanumeric characters declared as a character array. In chapter
7, students will learn how to incorporate string variables in C programs. Additionally,
students would learn how to manipulate string variables such as character conversion,
format string output, and validation check of string characters. At the end of this lesson,
students would be able to achieve the following objectives.
7-1
CHAPTER 7: STRING IT202
Example – Declaration:
char Name[10];
Example – Initialization:
Once a string variable is declared, characters could be stored in the allocated storage
space. Each character would be accessed/referenced via index. The first character starts at
zero and the last character is always a NULL character. The following Figure 7-1
represents the organization of a string variable for the first initialization example above.
0 1 2 3 4 5 6 7 8 9
Indices (0 – 9)
7-2
CHAPTER 7: STRING IT202
OR
gets(Name);
The scanf( ) function takes a set of characters from the input stream (from the current
position to the next whitespace and write them beginning at the address name. It will also
add a null at the end of the characters to maintain C’s concept of string.
If a character array (string variable) has 10 elements/slots for storage, we can effectively
store only 9 characters. If user enter a 15-characters to the array, it overflows the space
allocated and will mess up something else. We can limit the number of characters that will
be converted by putting a width modifier in front of the s type code.
Example:
char product[9];
scanf(“%9s”, product);
Explanation:
The above scanf( ) example will stop conversion at the first whitespace or a maximum of
9 characters. If it reaches the maximum, characters left over remain in the stream.
Whitespace is the default delimiter for scanf( ), which means that inputting a single string
with whitespace in it is not possible. If there might be two-word product names, such as
Blue Swan, we would have to use something other than scanf( ). In this case, we may use
gets( ).
The gets( ) function does not limit the number of characters assigned to the string.
Typically, scanf( ) leaves newline in the input stream after finishes. When gets( ) executes
and you are expecting the program to stop while you enter something. The gets( ) sees the
newline, which it interprets as an empty string – perfectly acceptable to it – and it assigns
7-3
CHAPTER 7: STRING IT202
the empty string to the input field. It is important to be sure that the input buffer is empty
before the call to gets( ), this could be done through flushing the input stream as below:
Example:
char Name[30];
:
:
fflush(stdin);
gets(Name);
OR
puts(Name);
7-4
CHAPTER 7: STRING IT202
char Destination[40];
char Source[40] = “Peter”;
strcpy(Destination, Source);
char Destination[40];
char Source[40] = “Peter”;
strncpy(Destination, Source, 20);
7-5
CHAPTER 7: STRING IT202
strcmp( ) – compares two strings and return a positive value if the first string is greater
than the second string, zero if both strings are equal, or negative value if first string is less
than second string.
7-6
CHAPTER 7: STRING IT202
Program 7-1
#include <stdio.h>
#define LENGTH 10
void main(void)
{ char product[LENGTH];
float price;
Output
Enter price and product: 12.98 widget
The price of a widget is 12.98
Program 7-2
7-7
CHAPTER 7: STRING IT202
#include <stdio.h>
#define LENGTH 10
void main(void)
{ char string[LENGTH];
{ int index = 0;
line[index] = getchar();
while (line[index] != '\n'&& index < max - 1)
{ ++index;
line[index] = getchar();
}
if (line[index] != '\n')
while (getchar() != '\n');
line[index] = '\0';
}
7-8
CHAPTER 7: STRING IT202
Output
Your input> Hi there
Stored: Hi there
Program 7-3
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void main(void)
{
char Name[40];
int idx;
Output
Enter your name [max 40]: rosemary reis
After conversion: Rosemary Reis
7-9
CHAPTER 7: STRING IT202
Program 7-4
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void main(void)
{
char Name[40];
int idx=0, strSize, Valid;
Output
Enter your name [max 40]: rosemary 123
Name contain invalid character!
7 - 10
CHAPTER 7: STRING IT202
Program 7-5
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void main(void)
{
char Text[20] = "C PROGRAMMING";
printf("\n*%s*", Text);
printf("\n*%20s*", Text);
printf("\n*%-20s*", Text);
printf("\n*%5.3s*", Text);
printf("\n*%8.3s*", Text);
printf("\n*%8.5s*", Text);
printf("\n*%8.6s*", Text);
}
Output
* C P R O G R A M M I N G *
* C P R O G R A M M I N G *
* C P R O G R A M M I N G *
* C P *
* C P *
* C P R O *
* C P R O G *
7 - 11
CHAPTER 7: STRING IT202
Program 7-6
#include <stdio.h>
#include <ctype.h>
void main(void)
{ int in;
do
{ printf("Type a letter and <enter>: ");
in = getchar( );
getchar( );
}while (!isalpha(in));
puts("Finally, an alpha character!");
}
Output
7 - 12
CHAPTER 7: STRING IT202
Program 7-7
#include <stdio.h>
#include <ctype.h>
void main(void)
{ char string[ ] = "23 skidoo.";
int chr = 0;
while(string[chr] != '\0')
{ if (isalpha(string[chr]))
printf("'%c'is alpha\n", string[chr]);
else
printf("'%c'is not alpha\n", string[chr]);
++chr;
}
}
Output
7 - 13
CHAPTER 7: STRING IT202
Program 7-8
#include <stdio.h>
#include <ctype.h>
void main(void)
{ char string[] = "mYRnA H. bALthAZaR, III";
int chr;
Output
7 - 14
CHAPTER 7: STRING IT202
main( ) isvowel( )
string character
pos (character position in string) result
Output
Aloysius Washington
<A>l<o>ys<i><u>s W<a>sh<I>ngt<o>n
2. In the ASCII code, an uppercase letter has a value 32 less than the corresponding
lowercase letter. Write a program that will allow you to input any string and print
in all uppercase. The function caps( ) should make the actual changes in the string.
Do not use any string function.
string[ ]
caps( )
string[ ], sub
Output
Your input? How are you?
The output: HOW ARE YOU?
7 - 15
CHAPTER 7: STRING IT202
3. Write a program to compare two strings, the program should print out which string
is greater or that they are equal.
Variables:
String1
String2
Outputs
FIRST STRING? ABNER
SECOND STRING? CRUMP
CRUMP IS GREATER THAN ABNER
4. Good people all have last name begin with the letter G through L; all the others are
normal. Write a program that differentiates the good people from normal people.
Variable
Name
Outputs
Name? Annie
Annie is a normal person
7 - 16
CHAPTER 7: STRING IT202
Name? Gary
Gary is a good person
Name? Ben
Ben is a normal person
Name? Lawrence
Lawrence is a normal person
7 - 17
CHAPTER 7: STRING IT202
5. What two functions will copy characters from one location to another? How do
they differ?
6. What two functions concatenate one string to another? How do they differ?
7. What two functions compare two strings? How do they differ? How are the
comparisons made?
iv. A null will be stored at the end of x, given the declaration – char x[3] = {‘1’,
‘2’};
vi. A string variable control string can be sent to scanf as its first argument.
7 - 18
CHAPTER 7: STRING IT202
vii. C issues an error if you assign characters beyond the memory locations
allocated for an individual string.
viii. The strlen( ) function returns the number of characters in its argument, and
does not count the null.
7 - 19
CHAPTER 8: FILE IT202
Chapter 8 – File
Objectives
So far all the data captured is temporary held in computer’s memory, and once power
is off, the data lost too. In this chapter, students would learn how to keep and store data
into a data file. There is various file manipulation techniques would be covered in this
chapter. At the end of the chapter students would learn the following.
8-1
CHAPTER 8: FILE IT202
FILE *StudentFile;
Opening File
FILE *StudentFile;
StudentFile = fopen(“c:\\Data\\Student.Dat”, “a+”);
In the Declaring File Variable example, the StudentFile is the file pointer, and it is a user-
defined name. In the second example- Opening File, the fopen( ) function takes two
arguments – the data file name and the file modes. There are three types of file modes
available in C.
“r” – Opens an existing file with file position indicator at the beginning of the file.
“w” – Creates a new, empty file with the file position indicator at the beginning. If
there is any data exist in the file, it would be erased.
“a” – Opens an existing file or, if the file does not exist, creates a new one. The file
position indicator would be placed at the end.
All the above file modes could be issued in conjunction with a plus “+” symbol to indicate
the file is for both writing and reading operations.
8-2
CHAPTER 8: FILE IT202
Closing a File
FILE *StudentFile;
….. …
….. …
fclose(StudentFile);
8-3
CHAPTER 8: FILE IT202
Both the scanf( ) and fscanf( ) have the same arguments, parameters, and return values,
but fscanf( ) has an additional argument – the pointer to the file description. Both scanf( )
and fscanf( ) have an additional conversion code that is of limited use in the keyword
input of scanf( ). When writing to a text file, some delimiters were included, the slashes,
to separate values in the file. We can use those delimiters to tell a scanf( ) string
conversion when to stop reading characters. Instead of using %s for a string conversion,
we will use the %[] code. Inside the brackets we will put a caret (^) followed by any
characters we want to be recognized as delimiters – those that end a string conversion. For
example, %[^,-] will end a string conversion at either a comma or dash, whichever comes
first. Whitespace, the usual default delimiter, becomes just another character when use
%[].
Example:
if (feof(StudentFile))
printf(“End of the file”);
8-4
CHAPTER 8: FILE IT202
void main(void)
{
char Name[40];
int ID=0;
char Gender;
float Amt;
FILE *sfile;
8-5
CHAPTER 8: FILE IT202
#include <stdio.h>
#include <ctype.h>
void main(void)
{
char Name[40];
int ID;
char Gender;
float Amt;
FILE *sfile;
8-6
CHAPTER 8: FILE IT202
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void main(void)
{
char Name[40], Target[40];
int ID, Found = 0;
char Gender;
float Amt;
FILE *sfile;
8-7
CHAPTER 8: FILE IT202
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void main(void)
{
char Name[40], Target[40];
int ID, Found = 0;
char Gender;
float Amt;
FILE *sfile, *temp;
8-8
CHAPTER 9: Record-based Data IT202
9-1
CHAPTER 9: Record-based Data IT202
9.1 Structures
A structure is a complex data type made up of other data types. For example, we could
combine the three strings (char arrays) for name, address, and phone number into one
structure. We may access the entire structure – move it into secondary storage, for
example; or we could access an individual member of the structure – change the address,
for example.
Structures are data types that we make up ourselves. Their components are the existing
data types. Working with a structure requires a step that is already done for us with the
standard data types – providing a structure definition, where we tell C the makeup of the
structure. The general format of the definition is as below:
struct tag
{
member definitions
}
The tag is the name of new data type. It is equivalent of float or int and is used in much
the same way – we will declare variables of that data type to be used in the program. In
the member definitions we will define each of the individual variables that make up the
structure.
Example:
struct emp_record
{
char name[40];
int age;
float basicPay;
};
The above example with tag of emp_record contains definitions of a 30-element char
array referred to as name, an int referred to as age and a float referred to as basicPay.
Take note that there is a semicolon after the closing brace. Any valid data type can be a
member of a structure. The structure definition only tells C the makeup of the structure. It
9-2
CHAPTER 9: Record-based Data IT202
does not allocate memory. To use the new data type, we will have to declare variables of
that type. The following is an example of the declaration:
Example:
The above example allocates memory space for the variable staff of data type
emp_record. The key word struct must be included whenever we refer to a structure data
type. Structure tags are defined externally, outside of a function, are visible globally, in
fact, the structure can be declared anywhere in the program. It is often a good idea to
define structure externally, where they are visible to all functions. C also allows us to both
define and declare structures in the same statement. The overall general form is as below:
struct tag
{
member definitions
} names;
Example:
struct emp_record
{
char name[40];
int age;
float basicPay;
}full_time, part_time;
9.1.2 Initializations
We may also explicitly initialize structures at the time of their declarations. The important
criterion for initializations is that the values are listed in the exact same order as the
members in the structure. The entire definition, declaration, and initialization could be
contained in one statement. Please take note that no initialization should be made in a
9-3
CHAPTER 9: Record-based Data IT202
Example:
The result of a sizeof operation is the number of bytes in the expression or data-type name
following sizeof. If data-type names are used, they must be enclosed in parentheses.
Defining a structure defines a data type, and we can declare variables of that data type.
The sizeof operator will give us the number of bytes in the structure data type or variable.
Example:
struct emp_record
{
char name[40];
int age;
float basicPay;
}full_time, part_time;
:
:
printf(“Employee’s name: %s”, full_time.name);
printf(“Employee’s age: %i”, full_time.age);
:
:
9-4
CHAPTER 9: Record-based Data IT202
Example:
To access the basicPay of the second staff in the array we would refer to staff[1].basicPay.
To access the third character of the name member of the second staff we would refer to
staff[1].name[2]. The array may be initialized by putting a block of values after the
declaration, the following is an example of the initialization:
Example:
9-5
CHAPTER 9: Record-based Data IT202
Example – fread( ):
9-6
CHAPTER 9: Record-based Data IT202
Program 9-1
#include <stdio.h>
#define NAME_CHRS 30
struct employee_rec
{ char name[NAME_CHRS];
int dependents;
float pay_rate;
};
void main(void)
{ struct employee_rec full_time = {"Beulah Barzoom", 4, 12.63};
Output
Employee’s name: Beulah Barzoom.
Dependents: 4.
Change pay rate from 12.63 to > 14.25
Confirm new pay rate: 14.25
9-7
CHAPTER 9: Record-based Data IT202
Program 9-2
#include <stdio.h>
#define TAX_RATE .16 /* General tax rate */
#define DEP_REDUCTION .02 /* Reduction for each dependent */
#define NAME_CHRS 30
struct employee_rec
{ char name[NAME_CHRS];
int dependents;
float pay_rate;
};
void main(void)
{ struct employee_rec employee;
float hours, gross, tax;
double net;
9-8
CHAPTER 9: Record-based Data IT202
Output
Employee name:
9-9
CHAPTER 9: Record-based Data IT202
Program 9-3
#include <stdio.h>
#include <stdlib.h>
#define CHRS 30
struct employee_rec
{ char name[CHRS];
int dependents;
float pay_rate;
};
void main(void)
{ struct employee_rec employee;
FILE *employ;
9 - 10
CHAPTER 9: Record-based Data IT202
Output
Employee name:
9 - 11
CHAPTER 9: Record-based Data IT202
Program 9-4
#include <stdio.h>
#include <stdlib.h>
#define CHRS 30
struct employee_rec
{ char name[CHRS];
int dependents;
float pay_rate;
};
void main(void)
{ struct employee_rec employee;
float hours, gross, tax;
double net;
FILE *employ;
9 - 12
CHAPTER 9: Record-based Data IT202
Output
9 - 13
CHAPTER 10: PROJECT GUIDELINES IT202
Student Information
Project Proposal
• One copy of project proposal consists of the cover page and the proposal
details (refer to appendix D) should be submitted on lesson 4.
• Marks will be awarded to project proposal approved by project supervisor.
• No project development should be started without obtaining the approval
of project proposal from respective supervisor/lecturer.
Backup
10- 1
CHAPTER 10: PROJECT GUIDELINES IT202
• Any project is found copied form either classmates or outside sources will
not be marked.
• Lecturers have the right not to accept any project is found lacking of
substance or copy from some other sources.
Sample Project
There won’t be any sample project to be given to students. Students are required
to develop their project according to the stated project specification. There is no
specific format to the project. The most important criterion is to produce all the
required parts in their project.
Project Presentation
There will be twenty percent on Project Presentation, and each student MUST
pass the Project Presentation/Viva (with minimum score of ten marks) in order to
pass this unit. Failures to do so will resultant a fail grade for this module.
All the project documentation and program should clearly indicate the file
implementation process. Candidates may either choose to implement text file or
binary file in the program. Should there is any absent of file implementation will
resultant a “D” grade regardless the quality of the project documentation.
All codes in program should be written using standard C language, should there is
any other language found in the program such as C++, or Object Oriented, etc will
resultant a “D” grade to be awarded.
Candidates must include basic file manipulation process such as Add, Delete,
Search and Delete of records in the project’s program. Failures to do so will
resultant a “D” to be awarded.
10- 2
CHAPTER 10: PROJECT GUIDELINES IT202
Project Guidelines
Students are required to document their projects based on the Suggested Table of
Content. On Lesson 14, students are required to submit only ONE original copy
on documentation and a soft copy of program. Students are reminded that the
submitted project will not be returned and students are expected to photocopy one
own reference.
1. Current System
2. New System
3. Specification
4. Program Listing
5. Testing
5.1 Test Log
5.2 Test Cases
5.3 Test Log
6. Implementation
6.1 User Manual
7. Conclusion
7.1 Strengths
7.2 Weaknesses
7.3 Enhancements
10 - 3
CHAPTER 10: PROJECT GUIDELINES IT202
1. Current System
Outline the proposed new system. Students may approach this by looking
into functions available in the proposed system. Detail description on
features available in the new system. Students are reminded to substantiate
that the proposed new system is able to solve existing problems faced by
the users.
3. Program Specification
In this section, students have to show all of the input variables that are
used in program. Information such as Item Name, Description, Data Type
and Size should be described in detail.
The CRT is used to draw individual screen as stated in the Screen Design
section. The CRT form will be distributed on the first lesson, students are
required to make some copies depends on the number of screens in Screen
Design section. The objective of using CRT form is allow the required co-
ordinate (such column and row number) to be viewed during coding.
When draw the CRT Form, try to use pencil so as to facilitate changes. A
copy of standard CRT Form is available in Appendix C.
X - alphanumeric field
9 - numeric field
10- 4
CHAPTER 10: PROJECT GUIDELINES IT202
For example:
CRT Form
Add New Student
Name: xxxxxxxxxxxxxx
Age: 99
Date of Birth: 99/99/99
Gender: x (F-female / M-male)
Address: xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx
In this section, it shows all the data processing activities involved in the program.
This can be details like how data are validated, the algorithm used for certain data
processing tasks, for e.g. checking data entry for gender type, update the quantity
field of the master file record, print a subtotal at the end of the report, calculate the
average of a set of numeric values. These are the program requirements that your
program should reflect. The following are some possible checking or validations
that you may include in the Processing Requirement section.
Suggested Calculation
10 - 5
CHAPTER 10: PROJECT GUIDELINES IT202
For example:
Name
1. The acceptable entry for name is purely letters of alphabet, otherwise error
message "Invalid! Accept letters of alphabet from A to z only." will be
displayed.
2. The maximum size allowed for name field is 20, otherwise error message
"Invalid! The maximum number of characters allowed is 20 only" will be
displayed.
3. The name field should have data entry, otherwise error message "Invalid! You
must enter the name" will be displayed.
Payment_amount
4. Program Listing
5. Program Testing
10- 6
CHAPTER 10: PROJECT GUIDELINES IT202
A proper Test Plan should be produced to test the program. Students may adopt
Top-down or Bottom-up testing strategy. Testing begins at the menu level while
Bottom-up testing focuses on individual program and follow by the menu level.
An outline of the total number of test cases included must be outlined here, for
example:
All test cases outlined in the test plan previously are carried out with the actual
running of the program. This section of the testing documentation should include
further elaboration of each test case. Each test case should have the following
components:
Test Case : 1
Test Data : Show actual test data used in this test case
Expected Test Result : Explain the expected output you expect the program
to produce if the test data are used
10 - 7
CHAPTER 10: PROJECT GUIDELINES IT202
6. User Manual
The students should include some printed copy of screen capture when guiding
the users with step by step instructions. This gives the users a better idea of how
the screen would look like and the ways to respond to such screens. The user
manual must be detail enough for a non-computer literate to operate and no
computer jargon should be included.
7. Conclusion
Briefly explain the weaknesses of the program. You may comment on the
performance of the program.
Include some comments on the strengths of the program. Specify in what ways it
benefits users.
Include some suggestions that would help to enhance the performance of the
program in the future.
10- 8
CHAPTER 10: PROJECT GUIDELINES IT202
10 - 9
CHAPTER 10: PROJECT GUIDELINES IT202
Assessments
10- 10
CHAPTER 10: PROJECT GUIDELINES IT202
Appendix D
Project Title:
Software Requirement:
Hardware Requirement:
Abstract:
Date of Approval:
Approved by:
Signature:
10 - 11
CHAPTER 10: PROJECT GUIDELINES IT202
Appendix E
Cover Page
10- 12
APPENDIX A: LESSON PLAN IT202
Reference book
The Lesson Plan and Study Guide was developed base the following reference book:
Title: The Art of C Programming
Author: Steven C. Lawlor
Publisher: ITP (1996)
A-1
APPENDIX B: Revision Exercise Answers IT202
Revision Exercise
Chapter 1
1.
2.
i. not a valid declaration because there is no such variable type as unsigned float
ii. not a valid declaration because there is no such variable type as Double (it’s capitalization)
iii. valid declaration
iv. not a valid declaration because semicolon missing
3.
i. 91 - int
ii. 45 - int
iii. 48652 – long int
iv. 16.25 – float/double
4.
i. 1 (int)
ii. 12.5 (float/double)
iii. 13.2 (float/double)
iv. 5.0 (float/double)
5.
i. 8.3
ii. 6
iii. 10
iv. 27
6.
i. A-Z, upper- or lowercase, 0-9, and underscore. A name can start with anything but a number.
ii. No, C is case-sensitive
iii. Whether it is represented by straight binary or exponential notation, and how many bits it
occupies
B- 1
APPENDIX B: Revision Exercise Answers IT202
iv. Directs C how to store values in the variable, allocates space in memory, and, possibly,
initializes the variable
v. Char and int (with the possible modifiers signed, unsigned, short, and long) are integral; float,
double, and long double are floating point.
vi. U, L, UL, F and L again for long double, but the decimal point differentiates it from a long
int.
vii. We must use the special character \”
viii. As one continuous string value
7.
i. true
ii. false
iii. false
iv. true
v. true
vi. true
vii. false
viii. There are no string variables in C.
ix. true
x. false
Chapter 2
1.
i. %-3i
ii. %6.1f
iii. %5.1f
iv. ^%06li
v. %.2f
vi. %i/%d
vii. %c
viii. %9.3E
B- 2
APPENDIX B: Revision Exercise Answers IT202
2.
i. |*65|
ii. |A|
iii. |***4.3|
iv. |425|
v. |381.7|
vi. |*016|
vii. |1.23|
viii. |***52|
3.
i. The first argument to the printf( ) function is the control string that defines the format of the
output line. Subsequent arguments provides values to fill the spaces left in the format.
ii. Conversion code begin with a %a and end with a type specifier.
iii. Size modifiers further define the data type of the type specifier. The modifiers h and l
preceding i specify short or long ints, and L preceding f specifies long double. With scanf( ),
lf specifies a double.
iv. The width parameter specifies a minimum width for the field for printf( ).
v. Precision for printf( ) states the number of decimal places for a floating-point field (or
significant digits for a %g field) and the minimum number of digits with leading zero fill for
integral fields.
vi. Prompts are reminders displayed on the screen before inputs. They are displayed using printf(
).
vii. while (getchar( ) != ‘\n’); or fflush(stdin) are used to flush the input stream of unexpected or
unwanted characters.
4.
i. false
ii. false
iii. true
iv. true
v. false
B- 3
APPENDIX B: Revision Exercise Answers IT202
5.
i. define
ii. char
iii. &a
Chapter 3
1.
i. (1 < x && x < 5)
ii. (16 >= x && x >= -7)
iii. (22.6 >= x && x >= 12.03)
iv. (36 < x && x <= y && y < 115)
2.
i. true
ii. true
iii. true
iv. true
3.
if(color == ‘r’)
printf(“stop”);
else if(color == ‘y’)
printf( “caution”);
else if (color == ‘g’)
printf(“go”);
else
printf(“weird”);
B- 4
APPENDIX B: Revision Exercise Answers IT202
4.
The two segments don’t do the same thing. In the first code statement, the second if can never be true since
it is part of the else which only gets executed if x <= 0. In the second code segment the second if is always
true when the first one is true, so it is redundant. In both segments the segment if (x > 2) could be taken out
(int the second case { } would have to be added however, to keep the functionality the same). If x’s initial
value were 2, x would get 4 in the first segment and in the second segment x would get 8.
5.
6.
i. 9
ii. 0
iii. 10
7.
i. nested
ii. condition
iii. logical operators
iv. sequence, selection & iteration
v. Pseudocode
vi. sequence
vii. selection
ix. &&
x. !
B- 5
APPENDIX B: Revision Exercise Answers IT202
Chapter 4
1.
for (x = 14; x >= 3; x -= 5)
printf(“%d\n”, x);
2.
x = 250.0;
while (x >= 100)
{
printf(“%f\n”, x);
x -= 50;
}
y = 1226;
while (y <= 1426)
{
printf(“%f\n”,yx);
x -= 2;
}
3.
11
221
3321
44321
554321
6 0
4.
a. y = y + a * c; c++;
5.
B- 6
APPENDIX B: Revision Exercise Answers IT202
i. both s and z
ii. z
iii. t
iv. not necessary
v. sentinel value
vi. yes
vii. yes
viii. yes
ix. true
x. false
6.
An accumulation process adds (or multiplies, or whatever) the value of a variable to some other values and
stores the result in the original variable.
7.
If the accumulator variable contains garbage before the accumulation, it will contain garbage after.
8.
Counting is accumulation, but with difference that it adds the same value each time instead of different
values.
9.
Any counter-controlled loop must contain an initialization, a test, a body, a counter and end.
10.
x = 20;
while (x >= 100)
{
printf(“%d\n”, x);
x -= 50;
}
B- 7
APPENDIX B: Revision Exercise Answers IT202
11.
1 2 3 4 5
x=5
12.
13.
i. 3
ii. 4
iii. 2 3 4 3 4 5
Chapter 5
1.
The function definition starts with the declaration of its return types, its name, and initialized local
variables, and it contain all of the code that makes the function operate.
2.
The function call passes values to a function and sets the function in operation.
3.
The return statement ceases execution of the function, passes the value of the expression (if any) back to
the calling point to substitute for the call, and continues program execution at the calling point.
4.
A void return type means that no value being returned by a function. A void declaration means that no
variables are being declared to be initialized by passed values. In other words, the function call can have no
arguments.
B- 8
APPENDIX B: Revision Exercise Answers IT202
5.
The lifetime of a variable is the part of the program in which memory is allocated for that variable. The
visibility of a variable (or functions) is the part of the program in which the variable can be accessed (or
function called) by name.
6.
Global lifetime or visibility is from declaration throughout the entire program. Local is within only a
certain section, such as within one function.
7.
Internal is within a function; external is outside of any function. Internal declarations are local; external
declarations are global.
8.
1 4 9 16 25 36 49 64 81
9.
i. two
ii. int
v. v3
10.
i. true
ii. true
iii. false
iv. false
v. false
B- 9
APPENDIX B: Revision Exercise Answers IT202
11.
i. two
ii. 0
iii. n times
iv. double
v. FASLE
vi. 0
vii. n, t, i
viii. FALSE
ix. TRUE
x. 0
12.
i. c
ii. b
iii. c
iv. c
v. a
Chapter 6
1.
An indexed variable, like any other variable, has its own name, its own value, and its own place in memory.
2.
3.
An array is a set of indexed elements of the same data type. In C all the elements will be contiguous in
memory.
B- 10
APPENDIX B: Revision Exercise Answers IT202
4.
One reason for using arrays is to create a large number of variables. Another is so that we can change the
variable name in our program by changing the value of the index.
5.
6.
Ten variables are allocated with; the last index being 9, that is, stuff[9].
7.
stuff[1] will be 2.2. Since only stuff[0], stuff[1], and stuff[2] have initialization values, stuff[3] will be
zero, stuff[5], while we can actually access it, is beyond the end of the array, so its value is garbage.
8.
An index will be an integral data type. If a floating-point value is given, it is truncated to an integer.
9.
i. #define SIZE 10
ii. float fractions[SIZE] = {0};
iii. fractions[3];
iv. fractions[9];
v. fractions[0];
10.
i. valid
ii. valid
iii. invalid
iv. valid
v. invalid
B- 11
APPENDIX B: Revision Exercise Answers IT202
11.
i. FALSE
ii. FALSE
iii. TRUE
iv. FALSE
v. TURE
vi. TRUE
12.
i. array
ii. 99
iii. 0
iv. sort
v. insert
13.
i. a
ii. c
iii. c
Chapter 7
1.
By using the brackets and the caret indicating the characters that are not acceptable in the conversion.
2.
B- 12
APPENDIX B: Revision Exercise Answers IT202
3.
4.
strlen( )
5.
strcpy( ) copies a string from one address to another, including the terminating null. strncpy( ) does the
same, but will not exceed a maximum number of bytes, even if the null is not copies.
6.
strcat( ) copies a string from one address to the end of a string at another address. strncat( ) does the same,
but will not copy more than a maximum number of bytes.
7.
strcmp( ) and strncmp( ) compare bytes a position at a time from each address given. The comparison is
made according to the numeric value of the ASCII codes. The comparison stops at the first difference or, in
the case of strncmp( ), at a maximum number of bytes.
8.
i. double quotes
ii. 1
B- 13
APPENDIX B: Revision Exercise Answers IT202
9.
i. FALSE
ii. FALSE
iii. FASLE
iv. TRUE
v. FALSE
vi. TRUE
vii. FALSE
viii. TRUE
B- 14
APPENDIX C: Programming Exercise Solutions IT202
Programming Exercise
Chapter 1
1.
#include <stdio.h>
void main(void)
{
printf(“NAME: Steven\n”);
printf(“MAJOR: Diploma in Informtation Technology\n”);
printf(“OTHER COMPUTER COURSE TAKEN: Web Publishing\n”);
printf(“OCCUPATION: Account Manager\n”);
}
2.
#include <stdio.h>
void main(void)
{ int v1, v2;
float v3, v4;
v1=4;
v2=42;
v3=16.7;
v4=.0045;
3.
#include <stdio.h>
void main(void)
{ float dollars = 7.73;
int cents = 773;
C- 1
APPENDIX C: Programming Exercise Solutions IT202
4.
#include <stdio.h>
void main(void)
{ float feet;
int inches = 46;
Chapter 2
1.
#include <stdio.h>
void main(void)
{ int first, second;
printf(“First number?”);
scanf(“%d”, &first);
printf(“Second number?”);
scanf(“%d”, &second);
printf(“The second goes into the first %d times\n”, first / second);
printf(“with a remainder of %d.\n”, first % second);
printf(“The quotient is %3.1f.\n”, ((float)first / second);
}
2.
#include <stdio.h>
void main(void)
{ int input;
float total = 0.0;
printf(“PARTS?”);
scanf(“%f”, &Parts);
printf(“LABOR?”);
scanf(“%d”, &Labor);
SalesTax = Parts * 0.06;
Total = Parts + Labor + SalesTax;
printf(“\n AJAX AUTO REPAIR\n SALES INVOICE\n”);
printf(“PARTS $%7.2f\n”, Parts);
printf(“LABOR $%7.2f\n”, Labor);
printf(“SALES TAX $%7.2f\n”, SalesTax);
printf(“TOTAL $%7.2f\n”, Total);
}
C- 2
APPENDIX C: Programming Exercise Solutions IT202
3.
#include <stdio.h>
void main(void)
{ int input;
flost total = 0.0;
printf(“Fifty cents?”);
scanf(“%d”, &input);
total = total + input * 0.5;
printf(“Twenty cents?”);
scanf(“%d”, &input);
total = total + input * 0.25;
printf(“Ten cents?”);
scanf(“%d”, &input);
total = total + input * 0.1;
printf(“Five cents?”);
scanf(“%d”, &input);
total = total + input * 0.05;
printf(“One cents?”);
scanf(“%d”, &input);
total = total + input * 0.01;
printf(“Your total is %7.2f”, total);
}
4.
#include <stdio.h>
void main(void)
{ long int seconds;
5.
#include <stdio.h>
#define FIT_RATE 0.15
#define FICA_RATE 0.062
#define SAVINGS_RATE 0.03
#define RETIREMENT_RATE 0.085
#define HEALTH_INS 3.75
void main(void)
{ float Hours, HourlyPay, GrossPay, FIT, FICA, Savings, Retirement, NetPay;
C- 3
APPENDIX C: Programming Exercise Solutions IT202
printf(“HOURS?”);
scanf(“%f”, &Hours);
printf(“HOURLY PAY?”);
scanf(“%f”, &HourlyPay);
Chapter 3
1.
#include <stdio.h>
void main(void)
{ float number1, number2;
2.
#include <stdio.h>
void main(void)
{ float Purchase, TaxRate;
char County;
C- 4
APPENDIX C: Programming Exercise Solutions IT202
printf(“\nCOUNTY? ”);
scanf(“%c”, &County);
if (County == ‘A’)
TaxRate = 0.07;
else
TaxRate = 0.06;
printf(“TOTAL BILL: $%5.2f\n”, Purchase + Purchase * TaxRate);
}
3.
#include <stdio.h>
void main(void)
{ char grade;
int grade_point;
4.
#include <stdio.h>
void main(void)
{ float weight;
printf(“\nWEIGHT? ”);
scanf(“%f”, &weight);
C- 5
APPENDIX C: Programming Exercise Solutions IT202
5.
#include <stdio.h>
void main(void)
{ float CurrentEarnings, PrevEarnings;
6.
#include <stdio.h>
void main(void)
{ int value1, value2;
C- 6
APPENDIX C: Programming Exercise Solutions IT202
7.
#include <stdio.h>
void main(void)
{ float car_value, premium;
int age, tickets;
if (tickets > 3)
printf(“COVERAGE DENIED\n”);
else
{
premium = 0.05 * car_value;
if (age < 25)
premium = premium + 0.15 * premium;
else if (age <= 29)
premium = premium + 0.10 * premium;
if(tickets == 1)
premium = premium + 0.10 * premium;
else if(tickets == 2)
premium = premium + 0.25 * premium;
else if(tickets == 3)
premium = premium + 0.50 * premium;
printf(“PREMIUM: $5.2f\n”, premium);
}
}
Chapter 4
1.
#include <stdio.h>
void main(void)
{ int score, a_s=0, b_s=0, c_s=0, d_s=0, f_s=0;
printf(“\nSCORE? ”);
scanf(“%d”, &score);
C- 7
APPENDIX C: Programming Exercise Solutions IT202
while(score != 0)
{
if (score >= 0 && score <= 100)
{
printf(“THE GRADE IS ”);
if(score >= 90)
{
a_s++;
printf(“A”);
}
else if(score >= 80)
{
b_s++;
printf(“B”);
}
else if(score >= 70)
{
c_s++;
printf(“C”);
}
else if(score >= 60)
{
d_s++;
printf(“D”);
}
else
{
d_s++;
printf(“F”);
}
printf(“\nSCORE?”);
scanf(“%d”, &score);
}
printf(“\n%d A’s\n”, a_s);
printf(“\n%d B’s\n”, b_s);
printf(“\n%d C’s\n”, c_s);
printf(“\n%d D’s\n”, d_s);
printf(“\n%d F’s\n”, f_s);
}
2.
#include <stdio.h>
void main(void)
{ int multiplier, multiplicand;
C- 8
APPENDIX C: Programming Exercise Solutions IT202
3.
#include <stdio.h>
void main(void)
{ int x;
4.
#include <stdio.h>
void main(void)
{ int x;
5.
#include <stdio.h>
void main(void)
{ int x, y;
do{
printf("Enter two integer values: ");
scanf("d%d", &x, &y);
printf("The multiplication result is: %d", x * y);
} while (x > 0 && y > 0);
printf(“End of run.”);
}
6.
#include <stdio.h>
void main(void)
{ int x, y;
C- 9
APPENDIX C: Programming Exercise Solutions IT202
7.
#include <stdio.h>
void main(void)
{ int x, y;
Chapter 5
1.
#include <stdio.h>
void page(int page);
void main(void)
{ int p;
2.
#include <stdio.h>
int int_test(float value);
void main(void)
{ float input;
do
{
printf(“Your number: “);
scanf(“%d”, &input);
if(input)
{
if(!int_test(input))
C- 10
APPENDIX C: Programming Exercise Solutions IT202
3.
#include <stdio.h>
void change(int amount);
void main(void)
{ float purchase, tendered;
int cents;
printf(“Purchase: “);
scanf(“%f”, &purchase);
printf(“Amount tendered: “);
scanf(“%f”, &tendered);
cents = ((tendered – purchase) * 100.0);
if(((tendered – purchase) * 100.0) – cents > 0.5)
cents++;
change(cents);
}
C- 11
APPENDIX C: Programming Exercise Solutions IT202
4.
#include <stdio.h>
#include <math.h>
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
double exponentiate(double a, double b);
void main(void)
{ char op;
double x, y;
C- 12
APPENDIX C: Programming Exercise Solutions IT202
Chapter 6
1.
#include <stdio.h>
void main(void)
{
int a[5], x;
2.
#include <stdio.h>
void main(void)
{
float value[5], mean = 0.0;
int count;
C- 13
APPENDIX C: Programming Exercise Solutions IT202
3.
#include <stdio.h>
void main(void)
{
int List[5], counter, target;
counter = 0;
while(counter <=4 && List[counter] != target)
{
if(List[counter] != target)
counter++;
}
if(List[counter] == target)
printf(“%d was found at index %d”, target, counter);
else
printf(“%d was not found in the array”, target);
}
Chapter 7
1.
#include <stdio.h>
#include <ctype.h>
#define CHRS 50
void main(void)
{
char string[CHRS];
C- 14
APPENDIX C: Programming Exercise Solutions IT202
int pos = 0;
gets(string);
while(string[pos] != ‘\0’)
{
if(isvowel(string[pos]))
{
putchar(‘<’);
putchar(toupper(string[pos]));
}
else
putchar(string[pos]);
++pos;
}
switch(toupper(character))
{
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
result = 1;
break;
default:
result = 0;
}
return result;
}
2.
#include <stdio.h>
#include <ctype.h>
#define CHRS 80
void main(void)
{
char string[CHRS];
C- 15
APPENDIX C: Programming Exercise Solutions IT202
3.
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[20], string2[20];
printf("FIRST STRING:");
fflush(stdin);
gets(string1);
printf("SECOND STRING:");
fflush(stdin);
gets(string2);
if(strcmp(string1, string2) == 0)
printf("%s EQUAL %s", string1, string2);
else if(strcmp(string1, string2) > 0)
printf("%s IS GREATER THAN %s", string1, string2);
else
printf("%s IS GREATER THAN %s", string2, string1);
}
4.
#include <stdio.h>
#include <ctype.h>
void main(void)
{ char initial, name[50];
int x = 0;
printf("Name?");
fflush(stdin);
gets(name);
initial = name[0];
while(name[x] = ‘\0’);
{
if(name[x – 1] == ‘ ’)
initial = name[x];
x++;
}
C- 16
APPENDIX C: Programming Exercise Solutions IT202
C- 17
IVC is an interactive system designed exclusively for Informatics students
worldwide! It allows students to gain online access to the wide range of
resources and features available anytime, anywhere, 24hours per day, and
7days a week!
In order to access IVC, students need to log-in with their user ID and
password.
Among the many features students get to enjoy are e-resources, message
boards, and online chat and forum. Apart from that, IVC also allows students to download assignments and
notes, print examination entry cards and even view assessment results.
With IVC, students will also be able to widen their circle of friends via the discussion and chat rooms by getting
to know other campus mates from around the world. They can get updates on the latest campus news,
exchange views, and chat about common interest with anyone and everyone, anywhere.
Among the value-added services provided through IVC are global orientation and e-revision.
Global orientation is where new students from around the world gather at the same time for briefings on the
programmes they undertake as well as the services offered by Informatics.
e-Revision on the other hand is a scheduled live text chat session where students and facilitators meet online to
discuss on assessed topics pre-exams. Students can also post questions and get facilitators to respond
immediately. Besides that, students can obtain revision notes, and explore interactive exam techniques and
test banks all from this platform.
In a nutshell, IVC is there to ensure that students receive the best academic support they can get during the
course of their education pursuit with Informatics. It could give students the needed boost to excel well beyond
expectations.
IVC at a Glance