Вы находитесь на странице: 1из 111

GERMAN-MALAYSIAN INSTITUTE

SPG 0412
PROGRAMMING IN C

GERMAN-MALAYSIAN INSTITUTE

COURSE OUTLINE IN GENERAL


Module
Module Code

SPG

Submodule

PROGRAMMING IN C

Submodule Code

SPG 0412

Pre requisites

NIL

Semester

Weightage

Hours

72 hours

Laboratory / Workshop

Computer Lab.

Machines / Equipments

Prepared By

1)
2)
3)
4)

Personal Computer
LCD Projeector
Scanner
Printer

Hasneeza Liza binti Zakaria

Page 1
G M I/ I SC /C L5 /R E V00 /0 2

HANDOUT

SPG 0412

PROGRAMMING IN C

SUMMARY OF COURSE OBJECTIVES :

1.

Students should be able to explain the concept of structured programming.

2.

Students should be able to understand all the syntax in C.

3.

Students should be able to use the correct C syntax.

4.

Students should be able to write programs in C.

REFERENCES :
1.

C How to Program, 2nd Edition, H.M Deitel & P.J. Deitel, Prentice Hall,
1994

2.

Introduction to C and C++ for Technical Students A Skill Building


Approach, Timothy Ramteke, Prentice Hall, 1998

3.

C by Disecction The Essentials of C Programming, 2nd Edition, All Kelly


& Ira Pohl, The Benjamin/ Cummings Publishing, 1992

Page 2
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 1

System Development Methodology

Page 3
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 Life Cycle of Software Development

Analysis

Design

CodingImplementation

Maintenance

Figure 1.1 Life Cycle of Software Development

2.0 What is a System?

A set of things or processes that are linked together by rules to form a unified
process.

A system has boundaries & interacts with the universe beyond the boundary,
by passing data across the boundary

As a disciplined approach to developing information system

To document project phases, inputs and outputs, boundaries (people /


organization).

2.1 Life Cycle of System Development (SDLC)


1. The rounded rectangles
2. The arrows
a phase.

represented project phases

represent inputs and outputs (working documentation) for

3. The person
figures are people and organizations with whom the
analyst may interact.
4. The shaded diamonds
indicate checkpoints at which the end-user
should reevaluate feasibility.

Page 4
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C
1

2
Feasibility assessment

Project
request

Study
current
system

Survey
project
scope &
feasibility

Problem statement
Facts

START

3
Define the
end-users
requirements

Requirements

Opinions and approvals

FINISH

Requirements statement
Opinions

Delivered
system &
enhancements

Select a
feasible
solution
( from
candidate
solutions)

9
Maintain
and
improve the
system

New information
system

Approved
system
proposal

5
End-user
training

Design the
new system

Configuration

Design specification

Request for
proposals

6
Acquire
computer
hardware
and
software
Proposals

Deliver the
new system
Computer
software

Construct
the new
system

Figure 1.2 System Development Life Cycle (SDLC)

Page 5
GM I/ IE/ C L5/ REV00/05

Vendors

HANDOUT

SPG 0412

PROGRAMMING IN C

Given the project request (e.g to develop a software program, to build a house, etc.)
The
phases of a SDLC are:
1. Survey project scope and feasibility

This is also called a preliminary investigation or feasibility study.


It determines the scope of the project, perceived problems and
opportunities, business and technical constrains, perceived project goals
and possible solutions.
Output : feasibility assessment ( the findings and recommendations)

2. Study and analyze the current system

You need to understand the existing system, manual or computerized,


before you design and build a new system.
During the study phase you want to address the causes and effect of
problems, opportunities and directives.
Output : problem statement

3. Define the end-users requirements

You go to the end-users (the ones who are/will be using the system)
and find out what they need or want out of the new system.
Essentially, the purpose of the definition phase is to define the inputs,
files, processing and outputs for the new system.
Output : requirement statement.

4. Select a feasibility solution (from candidate solutions)

The selection phase determines how the new system is to be designed


but only at a very high level no details included.
After defining candidates, each candidates is evaluated for
Technical feasibility Do we have the technical know-how?
Operational feasibility Can the new system be accepted by
end-users?
Economic feasibility Is the solution cost-effective?
Output : approved system proposal.

5. Design the new system


Traditionally, computer outputs are designed first because output
design can affect the design of inputs, files and methods.
Then the analyst designs files (or databases) and inputs.
Finally, methods and procedures that maintain files (or databases) and
transform inputs into outputs must be designed.
Output : design specification

Page 6
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

6. Acquire computer hardware and software

You need to determine which specifications are important for the


equipment and software to be purchased.
Output ( to vendors) : request for proposals (RPF) or request for
information(RPI)
Input (from vendors) : proposals ( after this, you should acquire the
proposed hardware and software configuration that best meets your
needs at a reasonable cost.
Output : proposal of configuration ( hardware and software)

7. Construct the new system

The construction phase is the most time consuming and tedious phase.
If the preceding phases were hastily done ( example specifications are
unclear, incomplete, etc.) this phase should be even longer.
Alternatively or additionally, the construction phase may involved the
installation and modification of purchased software packages.
The principal person here is the programmer ( not the analyst)
Output : software

8. Deliver the new system

The new systems solution represents a departure from the way things
are currently done.
The analyst must provide for a smooth transitions from the old system
to the new system.
Help the users cope with normal start-up problems, training and writing
of manuals.

9. Maintain and improve the system

The analysts role changes from development to support and to


respond to request for maintenance and improvement.
Maintenance is the correction of errors and omissions that is essential
to the system usefulness.
Improvements are the addition of new capabilities such as reports, new
interfaces with other systems, and new features such as better screen
or report layouts.
All changes should be documented. Well maintain documentation can
significantly accelerate the study phase when the system is due for
overhaul.

Page 7
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

2
Lot location

Survey the
situation

Study current
environment

Dream
house
idea

Current environment
& constraints

Land surveys, zoning laws,


budget, neighbourhood

START

3
Homeowners requirements

Define the
end-users'
requirements

Homeowners opinions

FINISH

Homeowners requirements

Architectural possibilities

Mortgage
& furnishing

Evaluate
architects
alternatives

Decision

Design the
new house

Select
materials &
subcontractors

Bid request
Configuration

Blueprints
Bids

Move into
new house
House

Construct
the new
house

Figure 1. 3 SDLC House Building example

Page 8
GM I/ IE/ C L5/ REV00/05

Subcontractors
and suppliers

HANDOUT

SPG 0412

PROGRAMMING IN C

2.2 Six basic principals apply to all systems development projects


1. We should actively involved the end-users in system development
2. We should use a phased approach to systems development
3. We should recognize that phases can overlap and that we need to backtrack
from time to time.
4. We need to appreciate that systems are capital investments and should be
justified as such
5. We should establish checkpoints to allow us the option of canceling the
project if it has become infeasible.
6. We should document a system while we develop that system.
1

2
Study

Survey

3
Definition

4
Selection

9
Maintain
and
improve

6
Acquisition

Design

Delivery

Construction
Vendors

Figure 1. 4 Six basic principals of SDLC

Page 9
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Please be informed that the phases are not really sequential. A non-sequential
view of the life cycle is illustrated in figure 1. 5

Survey project scope and feasibility


Study and analyze the current system
Define the end users requirements

Phase

Select a feasibility solution


Design the new system
Acquire hardware and software
Construct the new system
Deliver the new system
Maintain and improve the system

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

Time(Week)
Figure 1.5 Gantt Chart

2.3 Gantt chart.

The chart demonstrates how phases might be overlapped.

Although the SDLC is not strictly sequential, most phases do have some
prerequisites.

Examples : the survey phase determines project feasibility, it is shown as a


strict prerequisite for the study.

And because end-user requirements should address verified problems and


opportunities, the study phase is suggested as a prerequisite to the definition
phase.

P a g e 10
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3.0 System Documentation Models


3.1 Models

Abstraction / representation of reality


The simplification of the real thing
Are built as a design technique

3.2 Why do we need models?

Procedures for personnel to follow


Analyze and document the system
To convert data into information.

3.3 Data Flow Diagram (DFD)

a model that describes the flows of data & the process that change/transform
data throughout the system

DFD properties:
On page

Off
page

Data storage or file

Process

Material Flow

Source/data
destination
Data flow

Figure 1.6 DFD properties

The process symbols are used to indicate those places within the system at
which incoming data flows are processed or transformed into outgoing data flows.

The name of the process is generally written inside the block.

Numbers can also be used for reference and sequencing.

Materials flows are shown by the broad arrow.

Data flows are shown by arrows marking the movement of the data through
the system.

P a g e 11
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

A data flow can be thought of as a pipeline transporting packets of data from


source to destination.
An open-ended rectangle represents a logical file where data are added or
retrieved.

The origin of data is called a source and the recipient is called a sink.

Sources and sinks can be a person, organization, or even another computer


system.

Examples :
4
Materials
Process
shipment
Shipping documents
Shipping data
2

1
Customer
Order

Process
order

Order data

Process
shipping
data

Invoice

Payment

Process
invoice

Figure 1.7 High-level DFD of an order processing


The order processing system is a top-down model. The DFD represents the
system boundaries, external interactions, processes and data flow. The DFD is a
logical model and therefore does not identify disks, tapes, printers, computers or any
other physical devices.

P a g e 12
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

The model below is an explosion of the process order box.


1 Process Order
1.3

In stock

To
4

Process
Pricing

To
2
Customer

1.1

1.2

Order
entry

Check
inventory

Quantities

Pricing data

Out of stock
1.4

Inventory

Backorders

Backorder items
Backorder data

Figure 1.8 The explosion of process order

Process boxes can be repeatedly exploded or decomposed until each lowestlevel process box represents functions equivalent to a module of programming code
(i.e 50 to 100 lines of programming instructions).

P a g e 13
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3. 4 Flowchart

Flowcharts graphically illustrate how input, processes and output interact with
each other

Flowcharts

System

Program

3.4.1 System Flowchart

The general model of the whole systems application.

As a physical summarization of all the input & output involved.

3.4.2 System Flowchart - Symbols

Decision

Online
Storage

Process

Document

I/O

Termination

Manual Operation

Manual
Input

Offline

Off-page connector

P a g e 14
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Record
Customer
Orders

Customer orders

Keying
operation

inventory
master file

sales report

Process
Customer order

Shipping
documents

customer
master file

invoices

Figure 1. 9 Example of a system flowchart

P a g e 15
GM I/ IE/ C L5/ REV00/05

backorders

HANDOUT

SPG 0412

PROGRAMMING IN C

3.4.3 Program Flowchart

A program flowchart models the program logic, in sequence.

A guide by programmers to code the program, as well as for documentation.

Illustrates flow of data flow of data and how they are processed.

3.4.4 Program Flowchart - Symbols


Decision

Process

I/O

Begin/Termination

Example : Coming to GMI


Start

Go out from hostel

Y
Take a
bus?
N
Take own vehicle
to GMI

Walk to the
nearest bus stop

Wait for the bus


Take your
own
vehicle?

N
Walk to GMI

1
P a g e 16
GM I/ IE/ C L5/ REV00/05

Take the bus to


GMI

HANDOUT

SPG 0412

PROGRAMMING IN C

Determine the
level of lecture
hall

Go to the lift and


press a button

Take
a lift?

Wait until the door


opens

N
N

Lift
open

Go inside and
press the

Take the
N
Arriv
ed?
Y
Go out of lift
Walk to the
lecture hall

End

P a g e 17
GM I/ IE/ C L5/ REV00/05

Wait

HANDOUT

SPG 0412

PROGRAMMING IN C

4.0 Structured Programming

A well-structured program includes various combinations of 3 restricted


control structures, and exhibits a single-entry & single-exit property.

The 3 restricted control structures are:


A sequence of instructions
A selection of instructions based on certain criteria
An iteration (repetition) of instructions based on certain criteria

SINGLE-ENTRY

Activity
SMALL SEQUENCE

SINGLE-EXIT

SINGLE-ENTRY

SINGLE-EXIT

Activity

Yes

Decision

Activity

No

SELECTION

Activity
Activity

SINGLE-ENTRY

Activity
SINGLE-EXIT

No

Decision

Yes
SINGLE-EXIT

Activity

P a g e 18
GM I/ IE/ C L5/ REV00/05

ITERATION

HANDOUT

SPG 0412

PROGRAMMING IN C

5.0 Introduction to C language & C++ Compiler

Invented by Dennis Ritchie in 1970s.

Flexible & powerful, to create software products. but then it reached its limits.

Turbo C/C++ provides integrated programming features for programmers to


carry out programming tasks in DOS base operating system.

Today, the window base operating system enable programmers to carry out
programming tasks by using Borland C++ or Microsoft Visual C++.

Exercise
1. Describe all the phases of system development life cycle on how to develop a
GMI Student information System that can give information about the students
information by using DFD.
2. Draw a flowchart on how to buy a drink from a vending machine.
3. Draw a flowchart that can accept input in cent and change it to Ringgit as
output.
Example:
Input : 1150
Output: RM11.50

905
RM9.05

4. Draw a flowchart for College ABC. In order to enroll for a new semester a
student needs to choose 6 subjects, if its less than six the students cannot
enroll for a new semester. At the end of the semester the student need to sit
for an examination. The result later on will be verified and will be awarded with
PASS or FAIL. If the result is FAIL the student is required to reseat for the
exam. For those that PASS the exam, their results will be printed.
5. A program let the user input 2 integer and 1 code a for add, s for subtract,
m for multiply and d for divide.
When the user input the code, the program will do an operation . If the code
inputted is a then the program will add the 2 integer that have been inputted.
So, if you input s then the 2 integer will be subtract. Draw a flowchart for this
problem.

P a g e 19
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

7. Gallery Smart Shop sell items as below:Item Code


1
2
3
4
5

Price(RM)
30.00
35.00
40.00
90.00
120.00

When a customer order an item, they will give the items code to the operator
and
its quantity. .After that the price sub_total will be calculated.Then, the
customer
can order other item. Lastly, the total will be calculated by adding all the
subtotal.
Draw a flowchart for the transaction above.

8. Fill in the correct phases for each box if you want to build a bar code system
for GMI library. The system will enable students to borrow and return books.

P a g e 20
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 2

P a g e 21
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Basic structures of C
language

P a g e 22
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 Elements of a C Program

ELEMENTS OF C PROGRAM

Preprocessor Directives

Variable declaration

Functions

main( )

1) Preprocessor Directives

Begin with a pound sign(#) and give instructions to the C compiler

They are carried out before the compiler compiles the code

Example :

#include<stdio.h>
#include<math.h>
#define Area Width * Length
#define PI 3.1415

2) Variable declaration

A variable is simply a memory location (inside the computer) where you can
temporarily store data.

The user at the keyboard may enter the data, it may be read from a file or it
may be the result of a calculation made by the computer.

All variables must be declared before they are used and they must have:i.
an appropriate name or identifier.
ii.
a data type
iii.
value

For example if you want to add 2 numbers of type integer, you can store the
first value into variable Num1, the second value into variable Num2 and the
result of the calculation into variable Sum.
10
Num1

Num2

18
Sum

The reason memory locations are called variables is that their contents can
change(vary) as the program is running.

P a g e 23
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3) Functions

Every C program consists of one or more functions (collection of functions).

Each function contains one or more C statements.

A function usually carries out a single tsk and each has a name and a list of
values that the function receives.

Built-in function e.g. printf( ), scanf( )

4) main( ) function

the main( ) function indicates the body of the program

it receives control from the OS when the program begins to run.

use left brace { and right brace } to indicate the beginning and the end of the
program.

Example: trivia.c
Output:
void main(void)
{
}

You are looking at the simplest possible C program. Unfortunately, the


program doesn't do anything.

The word "main" is very important, and must appear once, and only once in
every C program. This is the point where execution is begun when the program
is run.

The words void indicates that there are no data types specified.

Following the "main" program name is a pair of parentheses which are an


indication to the compiler that this is a function.

The two curly brackets({ }), properly called braces, are used to define the limits
of the program itself. The actual program statements go between the two
braces and in this case, there are no statements because the program does
absolutely nothing.

P a g e 24
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.1 Parts of the Program


1) Displaying output

to display text on the current output device e.g monitor, printf( ) function is
being used.
e.g: printf(Welcome to GMI);
output: Welcome to GMI

2) Getting input

to get input from the user keyboard the scanf( ) function is being used.

e.g: scanf(%f, &Number);

%f format specifier

ampersand sign(&) address operator

the input is stored in the variable Number.

3) Body of program

It contains the main calculation of program or statements.

All statements must be in between the two braces ( { } ).

e.g
void main( ) { printf(Hello World!); }

4) Returning

The return statement exits the current function.

In the case, the statement returns the program to the operating system, then
passes a return value to the operating system.

can also indicate the function is successfully performed.

e.g: return 0;

P a g e 25
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Example: wrtmore.c

Output:

main( )
{
printf("This is a line of text to output.\n");
printf("And this is another ");
printf("line of text.\n\n");
printf("This is a third line.\n");
}

This is a line of text to output.


And this is another line of text.
This is a third line.

You will see that there are four program statements in this program, each one
being a call to the function "printf".

The top line will be executed first, then the next, and so on, until the fourth line
is complete. The statements are executed in order from top to bottom.

Notice the funny character near the end of the first line, namely the backslash( \
). The backslash is used in the printf statement to indicate that a special control
character is following. In this case, the "n" indicates that a "newline" is
requested.

This is an indication to return the cursor to the left side of the monitor and move
down one line. It is commonly referred to as a carriage return/line feed.

Any place within text that you desire, you can put a newline character and start
a new line. You could even put it in the middle of a word and split the word
between two lines. The C compiler considers the combination of the backslash
and letter n as one character.

1.2 General syntax of C program


1) Case sensitivity

uppercase and lowercase are treated as separate characters.

for example TOTAL, total, Total or totaL are treated as different identifiers.

2) The C Character Set

C uses letters A-Z, a z, digits 0 9 and the following special characters:

P a g e 26
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

[]

{}

<> ()

! * + = . ?
# / \ & % - _ ^
~ | ; : , @ $ `

3) Comments

Comments help the person writing a program(programmer) and anyone else


who must read the source file to understand what is happening.

Begin with /* and terminated by */.

Everything within the markers is ignored.

e.g:
/* This is and introduction to c */

4) Semicolon
Every statement in a C program is terminated with a semicolon( ; ), a character

that seperates one line from the next on the screen.


e.g:

area = PI * radius * radius;

P a g e 27
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/***********************************************/
/* THIS IS COMMENTS FOR COMMENTS.CPP FILE */
/***********************************************/
#include <stdio.h>
int main( )
{
printf("This program demonstrates comments\n");
/*"\n" is newline*/
return 0;
}
Output
This program demonstrates comments

/*********************************************/
/* addition program
*/
/********************************************/
#include <stdio.h>

void main( )
/*there is no return if using void */
{
int integer1, integer2, sum;
printf("Enter first integer\n");
scanf("%d", &integer1);
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2;
printf("Sum is %d", sum);

/*Prompt*/
/*Input using scanf( )*/

/*process*/
/*display output*/

}
Output
Enter first integer
23
Enter second integer
12
Sum is 35

P a g e 28
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

2.0 Elementary data structures

It can be discussed into 4 main areas:


1. variables and data types
2. constant
3. Arrays
4. Operators

2.1 Variables and data types

A variable is a symbolic name to which different value can be assigned.

E.g : int salary, float total, char name[80]

Data type is a set of values that represent a particular variable in memory

C has 3 basic data types:


1. integer variables
2. floating-point variables
3. character variable

2.1.1 Integer variables

integers consist of any valid combination of digits along with a plus or minus
sign.

An integer is a number that does not contains a decimal point.

E.g : 1676, -23, +10, 778888

Examples integer variable declarations include:


int counter;
int x = 1;
int center, radius;

C uses 3 types of integers; int, short, long

Every int variable requires 2 bytes of memory & hold numbers in the range
32,768 to 32, 767

P a g e 29
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

2.1.2 Floating-point variables

Represents numbers with a decimal place.

E.g: 3.1414927, .005, 79.88

C uses 3 basic types of floating-point numbers; float, double, long double

1) Float

Variables defined as float can be in the range 3.4 X 10 to 3.4 X 10 and can
occupy 4 bytes of memory.

Precision is set to seven digits of accuracy

E.g: float diameter; float principal; float distance = 25.05;

2) Double

Variables of type double required 8 bytes of memory to be stored and can


hold numbers in the range of 1.7 X 10 to 1.7 X 10

Example : double value; double PI = 3.1415927;

2.1.3 Character variable

A character is a single letter surrounded by single quotation


marks(apostrophes)

Character variables are used to hold eight-bit ASCII characters such as


A, P, I or any other eight-bit quantity.

E.g: char letter1, letter2;

2.2 Constant Values

Constants are identifiers that cannot change during execution of your


program.

A program can have constants of any of five basic data types.

C has 3 types of constants:


1. integer constants
2. floating-point constants
3. character constants

P a g e 30
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

e.g :
const int SPEED = 75;
const float PI = 3.1415927;
const double DIAMETER = 899.567;
const char CH = P;

2.3 String variables

The general definition of a character array looks like this:


char string[size];

In this example, size is the length of the string. Each character occupies one byte
of memory. You always make a space for the terminating null character. If you
know a string will be 10 character long you must define it as 11 characters long.

2.3.1 Initializing strings

Just as numerical arrays can be initialized, so can character arrays.

You can specify each character in the string like this:


char name[ ] = { A, L, I, \0};

Alternatively, you can specify the characters as a single string, using quotation
marks, as follows:
Char name[ ] = Ali;

P a g e 31
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

2.4 Operators

Operators work so closely with variables that just as it is hard to imagine a program
without variables, it is difficult to create a useful C program that does not use
operators.

Operators are words or symbols that cause a program to do something to its


variables.

2.4.1 Assignment operator

Example:
int num; \* num is an identifier with type int *\
num = 1; \*Assigning the variable a value *\

In assignment expressions, identifier usually represents a variable, and


expression represents a constant, a variable, or a more complex expression.
identifier = expression;

2.4.2 Arithmetic operator

To perform basic mathematical operations.


Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Remainder/Modulus operator (%)

The operands must represent numeric values, so the operands can be


integer, floating-point or character.
Example:

result = 365/5;
value = 99 previous;

P a g e 32
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

The rules of operator precedence are guidelines that enable C to evaluate


expressions in correct order. Fig. 1.1 summarizes these rules of operator
precedence.

Operator(s)
()

Operation(s)
Parentheses

*, / , or %

Multiplication
Division
Modulus
Addition
Subtraction

+ or -

Order of evaluation (precedence)


Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first.
If there are several pairs of parentheses on the
same level (i.e. not nested), they are evaluated
from left to right.
Evaluated second. If there are several, they are
evaluated left to right.
Evaluated last. If these are several, they are
evaluated left to right.

Fig. 1.1 Precedence of arithmetic operators


Example #1

Algebra:

z=pr%q+w/x-y

c:

z = p * r % q + w / x y;
1

Example #2

Algebra:

m= a + b + c + d + e
5

c:

m = (a + b + c + d + e) / 5;
1

P a g e 33
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

2.4.3 Relational operators

Relational operators compare 2 values, if the result of comparison is correct, the


expression is considered to be true, else it is false.

The resulting expressions is an integer-type expression, where 1=true and 0=false

< Less than(LS)


> Greater than (GT)
>= GT/ET

== Equal to
!= Not equal to
<= LS/ET

2.4.4 Unary Operators

Increment operator increases its operand by one, whereas decrement operator


decreases its operand by one.

Both operators work only with a single operand.

E.g: x++, x--

2.4.5 Logical operators

C contains three logical operators:

&& (AND)
||
(OR) !
(NOT) -

result=true IF expressions=true
result=true IF either expressions=true
reverse the expressions condition

P a g e 34
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3.0 PREPROCESSOR DIRECTIVES

instructions, processed before the code is compiled.

3.1 File inclusion

one of the most common preprocessor directives used C.

when file is included, the contents of the include file are inserted at the the
current location of source file.

Example :

#include <stdio.h>
#include <math.h>

3.2 Macro definition

usually associated with word processing and spreadsheet programs.

save your time in carrying out your tasks.

The define directives

when the preprocessor encounters a macro name, it replaces the macro


name with another string that previously defined.
general format
#define identifier replacement_string

Example :

#define PI 3.15
#define square x * x

3.3 Rules apply to creating macros

Macro name cannot contain spaces

Macro definition should not be terminated by a semicolon

Macro cannot be used inside quotation marks

Backslash character(\) can be used at the end of each line to extend the
macro definition to more than one line

P a g e 35
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise
1. Fill in the blanks with the correct answer.
a) Every C program begins execution at function _______________.
b) The _____________standard library function displays information on the
screen.
c) A function is invoked with a ______________________.
d) A variable declared inside a function and can only be used by statements
inside the function is called a ______________ variable.
e) The keyword ______________ is used in a function header to indicate that a
function does not return a value or to indicate that a function contains no
parameter.
(5 Marks)
2. Identify and correct errors in each of the following statements.
a) */ Program to determine the largest of three integers /*

b) printf (The value you entered is: %d\n, &value);

c) Scanf (%d, anInteger);

d) firstNumber + secondNumber = sumOfNumbers


(4 Marks)

3. Find the error in the following program segments and explain how the error
can be corrected.
void product (void) {
int a, b, c, result;
printf (Enter three integers: )
scanf (%d%d%d, &a, &b, &c);
result = a* b * c;
printf(Result is %d, result);
return result; }

P a g e 36
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

4. Debug the program below and briefly identify and correct the errors in it.
Hint : There are 6 errors in the program below
/* Program that calculate 2 numbers and verify the correct answer/*
#include <stdio.h>
void main( ) {
int num1, num2, add;
int answer;
printf (***Maths Excercise***\n)
printf ( \n\n);
printf(Enter first number : );
scanf ( %d, &num1);
printf(Enter second number : );
scanf ( %d, num2);
num1 + num2 = add;
printf ( \nWhat is the answer? );
scanf( %d, &answer);
if (answer = add)
printf( You are right\n);
else {
printf (You are wrong. Try again\n);
printf (The correct answer is %d\n, &add);
}

P a g e 37
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 3

Function

P a g e 38
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 Functions

1.1 The Concept of Functions

A function is a means of separating program logic into small parts.

Separates each section of code that performs a specific task.

You can call the same function several times to accomplish certain tasks.

A function is given its own name & accessed by that name. Data can be
passed to a function to operate on that data.

Built-in library function such as printf( ) & scanf( ) comes with the compiler.

User-defined function is named by the user himself, to carry out certain tasks.

1.2 Using the Standard Library

The standard C function library provides routine for the most common
programming tasks.

For example, the standard I/O library includes functions that control computer
input & output.

1.3 A Simple Function

A program can contain multiple functions, and each is considered to be a


separate program.

Benefits of using functions:

Functions make programs more organized

reducing the memory required in a program

Enable to reuse code

P a g e 39
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

2.0 Parts of functions

2.1 Function Declaration

The function usually is declared at the beginning of the program.

The declaration informs the compiler that you plan to create the function.

type function_name(type varname1,


type varname2,
..);

type: data type the function returns. Use void if the function does not return
any value.

type varname1 : arguments passed to the function.

ends with a semicolon.

2.2 The Function Body


type function_name(type varname1, type varname2, ..)
{
/*function body*/
}

The first line of the function is virtually a copy of the function declaration,
without semicolon.

The statements that form the body of the function are enclosed in braces.

P a g e 40
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

2.3 Calling the Function

After it is written, the function can be used in the program.


void main( )
{
/*other statements*/
function_name(varname1, varname2, ..);
/*more statements*/
}

If the function returns a value, put the function on the right side of an
assignment statement.

To return a value from the function to the main program

/*Printing with different functions*/


#include <stdio.h>
void circle (void);
void Cross (void);
void Base (void);
void Triangle (void);

/*f.declaration of circle*/
/*f.declaration of cross*/
/*f.declaration of Base*/
/*f.declaration of Triangle*/

void main (void) {


circle( );
/*call circle*/
Triangle( );
/*call Triangle*/
Cross( );
/*call cross*/
}
void circle(void){
printf("\t ** \n");
printf("\t* *\n");
printf("\t ** \n");
}
void Triangle(void) {
Cross( );
Base( );
}
void Cross(void) {
printf("\t /\\ \n");
printf("\t / \\ \n");
printf("\t/ \\\n");
}
void Base(void) {
printf("\t------\n");
}

/*f.definition of circle*/

/*f.definition of Triangle*/

/*f.definition of Cross*/

/*f.definition of Base*/

Output

P a g e 41
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

**
*

**
/\
/ \
/ \
-----/\
/ \
/ \

3.0 Visibility & Lifetime of Variables


3.1 Local variable

Variable declared inside a function can be used only by statement in the


function.

To return a value from the function to the main program

3.2 Global variable

Variable declared outside of a function.

can be used by all functions defined in a program

P a g e 42
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/* functions with return values */


#include <stdio.h>
#include <math.h>
int add(void);

/* prototype/declaration*/

int result; /* global variable - can be access by all function*/


int add( ) /* function definition with no argument/parameter*/
{
int num1, num2; /* Local variables - can be use only in function add()*/
printf("Enter number 1 : ");
scanf("%d", &num1);
printf("Enter number 2 : ");
scanf("%d", &num2);
result = num1 + num2; /*formula*/
return result;
}
int main( )
{
add( );

/* call add */

printf("The sum of 2 numbers is %d \n",result);


return 0;
}

Output
Enter number 1 : 12
Enter number 2 : 34
The sum of 2 numbers is 46

P a g e 43
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*Demonstrating function with arguments*/


/*Calculate the hypotenuse of right-angled triangle*/
#include <stdio.h>
#include <math.h>
float hypotenuse(float, float); /*f.declaration with 2 arguments/parameters*/
int main( )
{
float base, side, hypot;
printf("\nPlease enter the base and side of\n");
printf(" the right-angled triangle to calculate\n");
printf(" the hypotenuse\n");
printf("Base : "); scanf("%f",&base);
printf("Side : "); scanf("%f",&side);
hypot = hypotenuse(base, side);
printf("\nThe hypotenuse of a triangle with base = %.2f\n",base);
printf(" and side = %.2f is = %.2f\n",side,hypot);
return 0;
}
float hypotenuse(float bas, float sid) /*f.definition with 2 arguments*/
{
float hypo = sqrt(bas*bas + sid*sid);
return hypo;
}

Output
Please enter the base and side of
the right-angled triangle to calculate
the hypotenuse
Base : 3
Side : 4
The hypotenuse of a triangle with base = 3.00
and side = 4.00 is = 5.00
P a g e 44
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*Demonstrating function with no argument*/


/*Calculate the hypotenuse of right-angled triangle*/
#include <stdio.h>
#include <math.h>
float hypotenuse( );

/*f.declaration with no argument/parametter*/

int main( )
{
hypotenuse( ); /*f.call*/
return 0;
}
float hypotenuse( ) /*f.definition with no argument*/
{
float base, side, hypot;
printf("\nPlease enter the base and side of\n");
printf(" the right-angled triangle to calculate\n");
printf(" the hypotenuse\n");
printf("Base : "); scanf("%f",&base);
printf("Side : "); scanf("%f",&side);
hypot = sqrt(base*base + side*side);
printf("\nThe hypotenuse of a triangle with base = %.2f\n",base);
printf(" and side = %.2f is = %.2f\n",side,hypot);
}

Please enter the base and side of


the right-angled triangle to calculate
the hypotenuse
Base : 3
Side : 4
The hypotenuse of a triangle with base = 3.00
and side = 4.00 is = 5.00

P a g e 45
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise
1. Write and compile a program that does the following:
a) Convert the value of temperature in Celcius to Fahrenheit. The formula is:
Fahrenheit = Celcius x 9/5 + 32

b) Compute the volume of a cube. The formula is : volume = length*width*height

Output
Converting Celcius to Fahrenheit
=======================
Please enter the temperature in Celcius: 100
Celcius is equal to 212 Fahrenheit

Calculate the volume of a cube


======================
Please enter the cube length : 2
Please enter the cube width : 4
Please enter the cube height : 2
The volume of the cube is 16 square meter.
You must use function temperature( ) to make the temperature conversion and
function volume( ) to calculate the cubes volume.

2. Design and implement an interactive program that reads the year of birth and the
current year then calculate the age of the person. For example; if year of birth is
1991 and the current year is 1998 then age is 7. Write a function to calculate the
age. Lastly print all the input and the output.

3. Write an interactive program that reads width and length of a rectangle in meter.
Write a function to calculate the time needed to mow a lawn with the rate of 2
square meter per minute. Display the input and the result on the screen.
(5 Marks)

P a g e 46
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 4

Input and Output

P a g e 47
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 INPUT AND OUTPUT FUNCTIONS

C does not directly provide for input and output operations.

instead, I/O are accomplished through the list of library functions.

for input and output you can use:a. Buffered I/O


b. Unbuffered I/O
c. Formatted I/O

1.1 Buffered I/O

collecting and storing characters you typed in an area of temporary memory


called a buffer.

you must press ENTER after typing because the character will only be sent to
the input routine after you press ENTER.

the buffered character I/O are:


a. getchar( ) - for input
b. putchar( ) - for output

getchar( ) and putchar ( ) function are part of STDIO.H

EXAMPLE : CHARIO.C (BUFFERED I/O)

#include <stdio.h>
int main( )
{
char c;
c = getchar( );
putchar(c);
return 0;
}

Output
A
A

P a g e 48
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.2 UNBUFFERED I/O

a program that immediately echoes input characters uses a form of


unbuffered input.

the characters entered by the user are immediately available to your


program.

dont need to press ENTER.

Unbuffered character I/O are:a. getch()


- does not echoes the character to display
b. getche()
- echoes character to display

EXAMPLE OF UNBUFFERED I/O

#include <stdio.h>
#include <conio.h>
int main( ) {
char c;
c = getch( );
c = getche( );
return 0;
}

Output
A

P a g e 49
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.3 FORMATTED I/O

streams are portable way to handle input/output tasks.

They are use for all types of input and output, including manipulators of data files.

the powerful aspect of using streams with C is that the code is transferable to
different compilers on different computer platforms.

2 basic methods of formatted I/O :a. scanf( )


b. printf( )
Table 4.1 Format specifiers for printf( ) function.
Output Type

Format specifier
%d

Signed decimal integer

%f

Floating point

%e

Floating Point with xponential

%c

Single character

%s

Character string

Table 4.2 Special escape sequences.

Code

Description

\\

Backslash

\b

Backspace

\r

Carriage return

Double

\f

Formfeed

\n

Newline

\0

Null value

Single quotation

\t

Tab

\v

Vertical tab

P a g e 50
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Table 4.3. Scanf() conversion codes.


Character

Description

%c

Single character

%d

Signed decimal

%e

Floating-point value

%f

in

Floating-point value

%h

Short integer

%i

Integer

%o

Octal integer

%s

String of characters

%u

Unsigned decimal

%x

Hexadecimal integer

#include <stdio.h>
int main( ) {
int octal,hexa;
float ex;
printf("Enter a number : ");
scanf("%d", &octal);
printf("The octal number is %o\n", octal);
printf("Enter another number : ");
scanf("%d", &hexa);
printf("The hexadecimal number is %x\n", hexa);
printf("Enter a float number : ");
scanf("%f", &ex);
printf("The number in exponent is %e\n", ex);
return 0;
}
Output
Enter a number : 10
The octal number is 12
Enter another number : 23
The hexadecimal number is 17
Enter a float number : 5.00
The number in exponent is 5.000000e+00

P a g e 51

GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/* Precise.c Using precision with printf()*/


#include <stdio.h>
int main( )
{
int i = 777;
float y = 123.456;
printf("%d\n%2d\n%8d\n", i, i, i);
printf("%7f %7.3f %7.1f\n", y, y, y);
printf("%12e %12.5e %12.3e", y, y, y);
return 0;
}
Output
777
777
777
123.456001 123.456 123.5
123456e+02 123456e+02
123456e+02

P a g e 52
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise
1. Given these initialization:
int i;
int c;

Write down the output that the printf( ) generate:


i = 36;
c = 64;
printf(%d %c\n, i, c);
printf(%c %d\n, I, c);

2. #include <stdio.h>
void main( ) {
char a, b, c, d, e, f,

scanf("%c%c%c%c%c%c", &a, &b, &c, &d, &e, &f);


printf("%c%c%c%c%c%c", a,b,c,d,e,f);
printf ("%c%c%c%c%c%c", a,b,c,d,f,e);

}
Write down the output for the program above if the input is ANSI C.

3.Look at the program below. What is its output?


#include <stdio.h>
void main( ) {
int i = 777;
float x = 12.345678;
float y = 555.55555;

printf(%d\n%2d\n%8d\n, i, i, i);
printf(%f\n%6.1f\n%.4f\n%8.3f\n, x, x, x, x);
printf(%f\n%6.1f\n%.4f\n%8.3\n, y, y, y, y);
}

P a g e 53
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 5

Decision Structure

P a g e 54
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 The if Statement

general sintax
if (expression)
statement;

the if statement enables you to test an expression and act according to how the
expression is evaluated.

if expression evaluate is true(1), statement is executed

if expression evaluate is false(0), statement is not executed

for real-time or interactive application.

start

step a

Input num

True
condition

False

True

step 1 .. k

if num
%2

False

step k + 1

Even

end
Single if structure

Example : Determine an odd or


even number

P a g e 55
GM I/ IE/ C L5/ REV00/05

Odd

HANDOUT

SPG 0412

PROGRAMMING IN C

step a

step k + 1..n

True

False
condition

step 1 .. k

step n + 1

Multiple if structure

Start

Input mark

Failed

True

False
If mark
>= 50

Passed

End

Example: Determine status according to mark entered

P a g e 56
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

#include <stdio.h>
/*Printing distinction / Passed / Failed according to mark*/
#include <stdio.h>
void main( )
{
int mark;
printf("Enter marks : ");
scanf("%d", &mark);
if (mark >= 80)
printf("Distinction\n");
else if(mark >= 50)
printf("Passed\n");
else
printf("Failed\n");

/*If mark >= 80 - distinction*/


/*If mark >= 50 - Passed*/
/*If mark < 50 = Failed*/

}
Output
Enter marks : 55
Passed

/*Determine the character category using mantic expression*/


#include <stdio.h>
void main( )
{
char charac;
printf(Input a character : );
scanf("%c", &charac);
if ((charac >= 'a') && (charac <= 'z'))
printf("Lowercase\n");
else if ((charac >= 'A') && (charac <= 'Z'))
printf("Uppercase\n");
else if ((charac >= '0') && (charac <= '9'))
printf("Digit\n");
else
printf("This is a special character\n");
}

P a g e 57
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Output
Input a character : #
This is a special character

1.1 Nested if Statement

general syntax
if (expression)
if (another expression)
statement;

you will see that the second if statement is actually part of the body of the first if
statement.

the inner if statement is not executed unless the outer one evaluates to true

the statement is executed unless both if statements evaluate to true.

#include <stdio.h>
int main( )
{
int number, secretnumber = 25;

/* the symbol for assignment operator = */

printf("Please enter a number to guess\n");


scanf("%d", &number);
if(number == secretnumber)
printf("You guess the number!\n");

/*the symbol for equal is == */

if (number != secretnumber)
/* the symbol for not equal != */
{
if(number > secretnumber)
/*nested if*/
printf("You guess too high\n");
else
printf("You guess too low\n");
}
return 0;
}

P a g e 58
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Output
Please enter a number to guess
34
You guess too high

2.0 The switch Statement


-general syntax
switch (expression)
{
case constant1 :
statement1;
break;
case constant2;
statement2;
break;
.
.
.
case constantX;
statementX;
break;
default :
default statement;
}

In the switch statement, the computer tests a a variable consecutively against a list of
integer or character constants.

After finding a match, the computer executes the statement or block of statements
that are associated with the specified constant.

the default statement is executed if the compiler does not find a match in the list of
constants.

each case must end with a break statement

P a g e 59
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

True

case 1

steps 1 .. k

False
case 2

True

steps k+1..m

True

steps n+1..p

False

case n

False
steps q.. r

The switch structure flowchart

Start

case 1

True

print 1

False
case 2

True

print 2

False

case n

True

print n

False
default

End
P a g e 60
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*Demonstrating simple switch*/

An example of switch structure

#include <stdio.h>
void main( )
{ int number;
printf("Enter a number : "); scanf("%d", &number);
switch(number)
{
case 1 : printf("One\n"); /*print One if number == 1*/
break;
case 2 : printf("Two\n");
break;

/*print Two if number == 2*/

case 3 : printf("Three\n");/*print Three if number == 3*/


break;
default:
printf("Others\n");/*print Others if number is not 1,2 or 3*/
}
}
Output
Enter a number : 2
Two

2.1 Nested switch statements

general syntax :switch (expression)


{
case constant1 :
statement1;
break;
case constant2 :
statement2;
break;
default :
default statement;
}
case constant2;
statement2;
break;

P a g e 61
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*Using nested switch to print and choose a menu */


#include <stdio.h>
void main( )
{
int choice; /*choice represents number 1, 2 , 3*/
char pilih; /* pilih represents character 1, 2, 3*/
int minute;
float hour, feet, meter;
int celcius, fahrenheit;
do{
printf("Welcome to this unit converter\n");
printf("\t\t===================================\n");
printf("\t\tI CHOOSE UNIT TO CHANGE
I\n");
/* The outer menu*/
printf("\t\tI=================================I\n");
printf("\t1. Time : minute -> hour\n");
printf("\t2. Distance : feet -> meter\n");
printf("\t3. Temperature \n");
printf("\t4. End\n");
printf("\tChoice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Input time in minute: ");
scanf("%d", &minute);
hour = (float)minute/60;
printf("%d Minute = %.2f Hour\n", minute, hour);
break;
case 2:
printf("Input distance in feet: ");
scanf("%f", &feet);
meter = feet * 0.3048;
printf("%.2f Feet = %.4f Meter\n", feet, meter);
break;
case 3:
do{
printf("\n\t\tCHOOSE UNIT TO CHANGE\n");
/*The inner/nested menu*/
printf("\t\t=====================\n");
printf("\t1. Celcius -> Fahrenheit\n");
printf("\t2. Fahrenheit -> Celcius\n");
printf("\t3. End\n");

P a g e 62
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

printf("\tChoice: ");
scanf("%s", &pilih);

switch(pilih) { /* The nested switch*/


case '1':
printf("Input temperature in celcius: ");
scanf("%d", &celcius);
fahrenheit = (celcius) * 9/5 + 32;
printf("%d Celcius = %d fahrenheit\n",
celcius, fahrenheit);
break;
case '2':
printf("Input temperature in fahrenheit: ");
scanf("%d", &fahrenheit);
celcius = ((fahrenheit)- 32) * 5/9;
printf("%d fahrenheit = %d celcius\n",
fahrenheit,celcius);
break;
case '3':
printf("End\n");
default:
printf("Invalid selection\n");
}
break;
}while(pilih != 3);
case 4: printf("Thank you for using this program\n");
break;
default: printf("Invalid selection\n");
}
}while (choice != 4);
}

P a g e 63
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Output
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 1
Input time in minute: 120
120 Minute = 2.00 Hour
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 2
Input distance in feet: 100
100.00 Feet = 30.4800 Meter
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 3
CHOOSE UNIT TO CHANGE
=====================
1. Celcius -> Fahrenheit
2. Fahrenheit -> Celcius
3. End
Choice: 1
Input temperature in celcius: 100
100 Celcius = 212 fahrenheit
Thank you for using this program
Welcome to this unit converter
===================================
I CHOOSE UNIT TO CHANGE
I
I=================================I
1. Time : minute -> hour
2. Distance : feet -> meter
3. Temperature
4. End
Choice: 4
Thank you for using this program

P a g e 64
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise
1. What is the output for each of the following programs below:-

a) #include <stdio.h>
void main( ) {
int i;
i = 14;
if (i % 2 == 0)
printf (Odd number\n);
else
printf (Even number\n);
}
b) #include <stdio.h>
void main( ) {
int code;
code = 2;
if ( code = = 1)
printf ( Male\n);
else
printf ( Female\n);
}
c) #include <stdio.h>
void main( ) {
int weight;
weight = 55;
if (weight <= 55)
printf( Average\n);
else
printf( Obese\n);
}
(3 Marks)
2. Find the error in each of the following code segments and explain how to correct it.

a) switch (n) {
case 1:
printf(The number is 1\n);
case 2:
printf(The number is 2\n);
break;
default:
printf(The number is not 1 or 2\n);
break;
}
(3 Marks)

P a g e 65
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3. There are two catagories of character; vocal and consonan.a, e, i, o and u


are vocal. Write a C program using the switch statement to determine wheather an
input character is a vocal or consonan.
Example output:-

Input a character (a z) : a
a is a vocal
(5 Marks)

P a g e 66
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 6

Loop Structure

P a g e 67
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 LOOP STRUCTURE

many programs require that a group of instructions be executed repeatedly, until a


logical condition has been satisfied.

This condition is known as looping.

looping statements are used to control program flow.

one of the strengths of a computer is its capability to perform repeated tasks rapidly,
accurately and without complaint.

you can instruct the computer to do the same thing over and over again, millions of
times, if necessary.

-there are 3 major loop statements in the C programming language:a) for loop
b) while loop
c) do while loop

1.1 The for Loop

the for loop is the fundamental looping statement in C.

It is often used for situations in which you want to execute a specific task number of
times.

general syntax:for (variable initialization ; number of loop; increment)

P a g e 68
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

initial value i

checks
condition
of i

True

steps 1 .. n

update i value

False

The for structure flowchart

Start

i=0

if
i >= 10

True

print the
value of i

False
End

Example : Printing the value of i

P a g e 69
GM I/ IE/ C L5/ REV00/05

i++

HANDOUT

SPG 0412

PROGRAMMING IN C

/*Simple for statement to print numbers*/


#include <stdio.h>
int main( )
{
for(int counter = 1; counter <=10; counter++) /*The syntax of*/
/*for statement*/
printf("%d\t",counter);
return 0;
}
Output
1
2

10

/*Printing in rows and colums using for statement*/


#include <stdio.h>
int main( ) {
for (int row = 1; row <= 5; row++)

/*Loop from 1 to 5*/

{
for(int column = 1; column <=3; column++) /*Loop from 1 to 3*/
{
printf(" \t");
/*print the asterisk*/
}
printf("\n");

/*go to a new line after each column*/

}
return 0;
}
Output
*
*
*
*
*

*
*
*
*
*

*
*
*
*
*

P a g e 70
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.2 The while Loop

in the while loop, the body of the loop is executed as long as the expression is true.

when the expression become false, program control passes to the line that follows
the loop.

Con dition

True

Steps 1 .. n

False

The while loop structure flowchart

Start

n=1

n >=
5

True

print the
value of n

False
End

Example : printing 1 to 5 using while loop

P a g e 71
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*Using while loop to print number 1 to 10*/


#include <stdio.h>
int main( )
{
int x = 1;
while(x <= 10 )
/*Checking the condition before loop*/
printf("%d\t", x++);
return 0;
}
Output
1

10

P a g e 72
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.3 The dowhile Loop

this loop structure is similar to the while loop.

unlike the for and while loops, which test the loop condition at the top of the
loop, the dowhile loop checks its condition at the end of the loop.

this means that a dowhile loop will always execute at least once.

the do keyword marks the beginning of the loop.

the while keyword marks the end of the loop and contains the loop
expression.

Steps 1 .. n

True
Conditio
-n

False
The do while loop structure

Start

n=1

Print the value of n

True
n > 10

False
Example: printing 1 to 9 with do..while loop

End

P a g e 73
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*Using do...while loop to print number 1 to 10*/


#include <stdio.h>
int main( )
{
int x = 1;
do {
printf("%d\t", x++);
}while(x <= 10);

/*Checking the condition at the end of the loop*/

return 0;
Output
1

10

2.0 Infinite Loops

infinite loops are loops that continue forever.

the only way to it is to abort the program in an unnatural way.


e.g. By pressing Ctrl + Alt + Del.

infinite loops are useful at times to force a program to continue running for an
extended length of time.

it is a quick way to force the instructions to be repeated several times.

Examples of infinite statements :

for (; ; ;)
printf (this will continue to print forever\n);
while(1)
{
printf (this will continue to print forever\n);
}
do
{
printf (this will continue to print forever\n);
}

P a g e 74
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3.0 The break statement

the use of break statement is to :


i) terminate a case statement
ii) force immediate termination of a loop

when the compiler encounters the break statement inside a loop, the computer
terminates the loop and program control resumes at the statement that follows the
loop.

/* Using the break statement in a for structure*/


#include <stdio.h>
int main( )
{
int x;
for (x=1; x <= 10; x++) {
if( x == 5)
break;

/*break loop only if x == 5*/

printf("%d ", x);


}
printf("\nBroke out of loop at x == %d\n", x);
return 0;
}
Output
1234
Broke out of loop at x == 5

P a g e 75
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

4.0 The continue Statement

is used to bypass the remainder of a pass through the loop.

forces the iteration of the loop to take place and skips any code in between.

/*Using the continue statement in a for structure*/


#include <stdio.h>
int main( )
{
int x;
for (x = 1; x <= 10; x++) {
if (x == 5)
continue;

/*skip remaining code in loop only if x == 5*/

printf("%d", x);
}
printf("\nUsed continue to skip printing the value 5\n");
return 0;
}
Output
1
2
3
4
6
7
8
9
Used continue to skip printing the value 5

10

P a g e 76
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise

1. What is the output for each of the following programs below:a) #include <stdio.h>
main( ) {
int x;
for (x = 1; x < 10; x++) {
if (x == 8)
break;
printf(%d, x);
}
return 0;
}
(2 Marks)

2. Debug the program below and briefly identify and correct the errors in it.
Hint : There are 6 errors in the program below

/* Calculating odd and even number /*


#include <stdio.h>
int main( ) {
int value, odd, even;
even = odd = 0;
printf ( Enter a positive number (negative to end) );
scanf (%d, value);
while (value > = 0) {
if (value %2 == 0)
Even++;
else
odd++;
printf ( Enter a positive number (negative to end) )
scanf (%d, value);
printf ( The number of even value %d\n, even);
printf ( The number of odd value %d\n, odd);
return 0;
}

P a g e 77
GM I/ IE/ C L5/ REV00/05

(6 Marks)

HANDOUT

SPG 0412

PROGRAMMING IN C

3. Find the error in each of the following code segments and explain how to correct it.

a. x = 1;
while (x <= 10);
x++;
b) for (y = .1; y != 1.0; y += .1)
printf (%f\n, y);
(2 Marks)

P a g e 78
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 7

Array

P a g e 79
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 Array
o

A group of items of the same type under one variable name.

An individual item in an array is accessed by an array index.

The grouped data items can be of type int, float or char.

The common array operation e.g are scanning, sorting and writing vector.

1.1 One-dimensional array

an ordered set of elements where each element is of the same type.

The general format of a one dimensional array is

Data type variable_name[size];

Example of array initialization

int age = { 19, 20, 21, 22, 23};

Another example is:


float marks[MAX];
or
float marks[5];

To define the one-dimensional array age in the example, the number of


elements in the array(or size of the array) is not specify because we can refer
to the number of elements in the { };

To define marks we use square bracket [ ] to write the number of elements that
it will contains.

P a g e 80
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*array.c*/
/* calculate the average of an array of numbers*/
#include <stdio.h>
const int MAX = 5; /*size of array*/
int main( )
{
int age[ ] = {19,17,18,20,22}; /*initialization of an
array*/
for(int i =0; i <MAX; i++)
printf("\nElement [%d] = %d\n",i,age[i]); /*output all
the array elements of age[ ] with its array index*/
float marks[MAX]; /*define array of 5 elements*/
float sum = 0.0;
for(int j=0; j <MAX; j++)
{
printf("\nEnter Mark %d: ", j+1);
scanf("%f", &marks);
sum += marks[j];
/*sum the marks*/
}
float average = sum/MAX;
printf("\nThe average of the marks is = %.2f",
average);
return 0;
}
Output:
Element[0] = 19
Element[1] = 17
Element[2] = 18
Element[3] = 20
Element[4] = 22
Enter mark 1 = 10
Enter mark 2 = 20
Enter mark 3 = 10
Enter mark 4 = 20
Enter mark 5 = 40
The average of the marks is 20.00

P a g e 81
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.2 Multidimensional array

Array dimensions can be of any dimension.

A table or a matrix can be two-dimensional array.

Two-dimensional array is the simplest form of multi-dimensional array.

You can initialize two-dimensional arrays by using 2 brackets [ ][ ].

E.g : int matrix[3][5] =

{{ 1,2,3,4,5 },
{ 6,7,8,9,10 },
{ 11,12,13,14,15,16}};

/*matintro.c*/
/*introduction to 2-dimensional arrays(matrices)*/
#include <stdio.h>
const int ROWS = 2, COLS = 3;
int main( )
{
int mat1[ROWS][COLS]; /*Defining a matrix of size 2 X 3*/
int mat2[ROWS][COLS] = {{1,2,3},
{4,5,6}}; /*Initialization of a matrix*/
for(int i=0; i <ROWS; ++i)
{
printf( "\n");
/*start a new line for each row*/
for(int j=0; j<COLS;j++)
{
mat1[i][j] = mat2[i][j];
/*Assigning values to
mat1 matrix*/
printf(" %d " , mat1[i][j]);
}
}
return 0;
}
Output
123
456

P a g e 82
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise

1. Given this definition:


#define N 3
int a[N] = {2, 4, 5};
int b[N] = {6, 2, 3};
int c[N], d[N][N];
int i, j;

a) What is the value of c after running the segment below:


for ( i = 0; i < N; i++)
c[ i ] = a[ i ] * b[ i ];

b) What is the value of d after running the segment below:


for(i = 0; i < N; i++)
for(j = 0; j < N; j++)
d[ i ][ j ] = a[ i ] * b[ j ];

2. #include <stdio.h>
#define N10

void main( ) {
int value[N] = {1, 1};
int i;

for (i = 1; i < N-2; i++) {


value[ i+1 ] = value[ i ] + value [ i 1];
}
}

What is the value of value[N] after running the segment above?

P a g e 83
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C
3. Use a one dimensional array to solve the following problem. Read in 20
numbers, each of which is between 10 and 100, inclusive. As each number is
read, print it only if it is not a duplicate of a number already read. Provide the
worst case in which all 20 numbers are different. Use the smallest possible
array to solve this problem.

4. Find the error in each of the following program segments and correct the
error.

a) #define SIZE 100;


b) SIZE = 10;
c) Assume int b[10] = {0}, i;
For ( i = 0; i <=10; i++)
B[ i ] = 1;
d) Assume int a [2][2] = {1,2}, {3,4}};
A[1,1] = 5;

P a g e 84
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 8

Pointer

P a g e 85
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0

POINTER

1.1

Pointer variable declarations and initialization

pointers are variables that contain memory addresses as their values.

Normally a variable directly contains a specific value.

A pointer, on the other hand, contains an address of a variable that contains a


specific value.

Like other variable, it must be declared before they can be used. E.g: int *aPtr. It
means that the variable *aPtr to be of type int *(i.e. a pointer to an integer value) and
is read as aPtr is a pointer to int or aPtr points to an object of type integer.

2.0 Pointer Operators

The &(address operator) is a unary operator that returns the address of its
operand. For example, assuming the declarations
int y = 5;
int *yPtr;
yPtr = &y;

The statement yPtr = &y; assigns the address of variable y to pointer


variable yPtr. Variable yPtr is then said to point to y.

The operator * returns the value of the object to which the pointer points to.

5
yPtr

Assume that the int variable y is stored at location 600000, and pointer
variable yPtr is stored at location 500000.
yPtr
500000

600000

y
600000

P a g e 86
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

#include <stdio.h>
/*This program tells you about simple pointer*/
int main( )
{
int ali = 100;
int *aliPtr;

/* ali has the value 100*/


/* pointer to ali*/

aliPtr = &ali;

/* aliPtr points to the address of ali*/

printf("The address of ali is %d and the address of aliPtr


is %d\n", &ali, &aliPtr);
printf("The value of ali is %d and the value of aliPtr is
%d", ali, *aliPtr);
return 0;
}
Output
The address of ali is 1245064 and the address of aliPtr is 1245060
The value of ali is 100 and the value of aliPtr is 100

/* Using the & and * operators */


#include <stdio.h>
int main( )
{
int a; /* a is an integer */
int *aPtr;
/*aPtr is a pointer to an integer*/
a = 7;
aPtr = &a;

/*aPtr set to address of a*/

printf("The address of a is %d\n"


"The value of aPtr is %d\n\n", &a, aPtr);
printf("The value of a is %d\n"
"The value of aPtr is %d\n\n", a, *aPtr);
printf("Proving that * and & are compliments of "
"each other.\n&*aPtr = %d\n*&aPtr = %d\n",
&*aPtr, *&aPtr);
return 0;
}

P a g e 87
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Output
The address of a is 1245064
The value of aPtr is 1245064
The value of a is 7
The value of aPtr is 7
Proving that * and & are compliments of each other.
&*aPtr = 1245064
*&aPtr = 1245064

/*converting lowercase letters to uppercase letters*/


/*using a non-constant pointer to non-constant data*/
#include <stdio.h>
void convertToUppercase(char *);
void convertToUppercase (char *s)
{
while (*s != '\0') {
if(*s >= 'a' && *s <= 'z')
*s -= 32; /*convert to ASCII uppercase letter*/
++s; /*increment s to point to the next character*/
}
}
int main ( )
{
char string[ ] = "characters";
printf("The string before conversion is: %s\n", string);
convertToUppercase(string);
printf("The string after conversion is: %s\n", string);
return 0;
}
Output
The string before conversion is: characters
The string after conversion is: CHARACTERS

P a g e 88
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

#include <stdio.h>
void printCharacters(const char *);
int main( ){
char string[] = "print characters of a string";
printf("the string is:\n");
printCharacters(string);
putchar('\n');
return 0;
}
void printCharacters(const char *s)
{
for(;*s != '\0'; s++)
putchar(*s);
}
Output
the string is:
print characters of a string

3.0 What is dynamic allocation?

Dynamically allocated variables are variables that do not exist when the program is
loaded, but are created dynamically as they are needed.

It is possible, using these techniques, to create as many variables as needed, use them,
and deallocate their space for use by other variables.

In the example dynlist.c below, we do not define any variables of this type, only three
pointers.

If you search through the remainder of the program, you will find no variables defined so
have nothing to store data in.

All we have to work with are three pointers, each of which point to the defined structure.

In order to do anything, we need some variables, so we will create some dynamically.

P a g e 89
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

// dynlist.c
#include<stdio.h>
#include <string.h>
#include<malloc.h>
void main( )
{
struct animal {
char name[25];
char breed[25];
int age;
} *pet1, *pet2, *pet3;
pet1 = (struct animal *)malloc(sizeof(struct animal));
strcpy(pet1->name,"General");
strcpy(pet1->breed,"Mixed Breed");
pet1->age = 1;
pet2 = pet1; /* pet2 now points to the above data structure */
pet1 = (struct animal *)malloc(sizeof(struct animal));
strcpy(pet1->name,"Frank");
strcpy(pet1->breed,"Labrador Retriever");
pet1->age = 3;
pet3 = (struct animal *)malloc(sizeof(struct animal));
strcpy(pet3->name,"Krystal");
strcpy(pet3->breed,"German Shepherd");
pet3->age = 4;
/* now print out the data described above */
printf("%s is a %s, and is %d years old.\n", pet1->name,
pet1->breed, pet1->age);
printf("%s is a %s, and is %d years old.\n", pet2->name,
pet2->breed, pet2->age);
printf("%s is a %s, and is %d years old.\n", pet3->name,
pet3->breed, pet3->age);
pet1 = pet3; /* pet1 now points to the same structure that
pet3 points to
*/
free(pet3); /* this frees up one structure
*/
free(pet2); /* this frees up one more structure
*/
}

P a g e 90
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

output
Frank is a Labrador Retriever, and is 3 years old.
General is a Mixed Breed, and is 1 years old.
Krystal is a German Shepherd, and is 4 years old.

4.0 Dynamic variable creation

The first program statement, which assigns something to the pointer "pet1" will create a
dynamic structure containing three variables.

The heart of the statement is the "malloc" function buried in the middle of the statement.

This is a "memory allocate" function that needs the other things to completely define it.

The "malloc" function, by default, will allocate a piece of memory on a "heap" that is "n"
characters in length and will be of type character. The "n" must be specified as the only
argument to the function.

4.1 What is a heap ?

A heap is an area which can be accessed by the program to store data and variables.

The data and variables are put on the "heap" by the system as calls to "malloc" are
made.

The system keeps track of where the data is stored. Data and variables can be
deallocated as desired leading to holes in the heap.

The system knows where the holes are and will use them for additional data storage as
more "malloc" calls are made.

The structure of the heap is therefore a very dynamic entity, changing constantly.

4.1.1 The new and delete operator

The keywords new and delete can be used to allocate and deallocate memory. They are
much more easier to use than the functions malloc and free from standard C. new []
and delete [] are used for arrays:

P a g e 91
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

#include <stdio.h>
#include <string.h>
int main ()
{
double *d;

// d is a variable whose purpose is to contain the address of a


// zone where a double is located

d = new double;

// new allocates a zone of memory


// large enough to contain a double
// and returns its address.
// That address is stored in d.

*d = 45.3;

// The number 45.3 is stored


// inside the memory zone
// whose address is given by d.

*d = *d + 5;
printf("Result: %.2f\n", *d);
delete d;

// delete deallocates the


// zone of memory whose address
// is given by pointer d.
// Now we can no more use that zone.

//Testing with string


char *s;
s = new char[100];
strcpy (s, "Hello!");
printf( "%s\n",s);
delete [ ] s;
return 0;
}
output
Result: 50.30
Hello!

P a g e 92
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

4.1.2 malloc( )

malloc( ) function will allocates memory dynamically when you run the program.
the function prototype is as follows :
void *malloc ( size_t size);

size is the size of memory that you want to allocate.


this function will return the adress for the allocated address. If failed, the function will
return a NULL value.

4.1.3 free( )

free function will free the memory that has been allocated for malloc( ) function.
the function prototype :
void free (void *ptr);

*ptr is the memory adress that we want to free.


Here is another example that receives input and creates an array. Then random
numbers will be generated and be the element of the array.

/* Creating an array dynamically */


#include <stdio.h>
#include <stdlib.h>
#include < alloc.h>
void main( ) {
int *list;
int i, num;

/* a pointer that will points to the dynamic memory */

printf( Enter the number of data that you want: );


scanf(%d, &num);
if (num < 1) {
/* Exit if num < 1*/
printf(Number of data < 1: End\n);
exit(1);
}
/* Allocate the space*/
list = (int *) malloc(num * sizeof(int));
if(list = = NULL) {
printf(Error in allocating memory\n);
exit(1);
}

P a g e 93
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

/*generates random number*/


for (i = 0; i < num; i++)
list[i] = rand( ) % 100;
/* display ascending data*/
for(i = num 1; i > = 0; i--)
printf(%d\n, list[i]);
/* free the memory space */
free(list);
}

Output
Enter the number of data that you want: 5
69
0
34
67
41

P a g e 94
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise
1. Give the output for the program below:-

(6 Marks)

/* Using pointer */
#include <stdio.h>
main( )
{
int a, b;
int *aPtr, *bPtr;
a = 7;
aPtr = &a;
b = 5;
bPtr = &b;

/* a and b is an integer */
/* aPtr and bPtr is a pointer to an integer */

/* aPtr set to address of a */


/* bPtr set to address of b */

printf (The value of a is %d\n


The value of *aPtr is %d\n\n, a, *aPtr);
printf ( The value of *bPtr is %d\n\n, *bPtr);
return 0;
}
2. a) Label the function declaration, function definition and function call by using comments.

b) Write down the output after running the program.

/* Using pointer and function in C */


#include <stdio.h>
int Add (int, int);
int Multiply(int, int);
int main( )
{
int *AddPtr, *MulPtr, x = 5, y = 10;
AddPtr = &x;
MulPtr = &y;
x = Add(x,y);
printf(The output for Add is %d, *AddPtr);
y = Multiply(x,y);
printf(\nThe output for Multiply is %d, *MulPtr);
return 0;
}

P a g e 95
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

int Add (int x, int y)


{
int total;
return total = x + y;
}
int Multiply (int x, int y)
{
int total;
return total = x * y;
}
3. Write the output of the following program. Assume that the address of aPtr is

123455, bPtr is 123456, a is 123457 and b is 123458.

#include <stdio.h>
int main( ) {
int a = 8;
int b = 10;
int aPtr = &a;
int bPtr = &b;
printf (\nThe address of a is %d\n, aPtr);
printf(The address of bPtr is %d\n, &bPtr);
printf(The value that aPtr pointed to is %d\n, *aPtr);
printf(The value that bPtr pointed to is %d\n, *bPtr);
return 0;
}
(4 Marks)

P a g e 96
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 9

Fail Manipulation

P a g e 97
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 FILE INPUT OUTPUT

Disk is used to store data. Text editor can edit data file.

Data that has been saved can be read, edited, deleted or appended by using C
program.

The advantage of data file is the same program or another program can use it
repeatedly.

1.1 DATA FILE

C Language can process 2 types of files; text file and binary file.

Text file is a file created from text editor or word processing software. The size of text
files varies. It depends to the number of characters in that file.

Text files have the extension .dat, .txt or .doc etc.

To mark the end of file, computer will put a special end-of-file character <eof>.

Data file can be accessed sequentially or randomly.

The way of accessing data determines how we read, write, edit and deleting data.

1.2 SEQUENTIAL FILE

Data in a file will be accessed sequentially like in a cassette player.

We play the music according to the sequence of recording.

Its hard to add or access data in the middle of a file. However, many applications
used this type of accesses.

1.3 RANDOM FILE

Data can be accessed in any sequence. You can imagine a CD player.

We can play any song that we want without forwarding like in a cassette player.

P a g e 98
GM I/ IE/ C L5/ REV00/05

HANDOUT

1.0

SPG 0412

PROGRAMMING IN C

OPENING AND CLOSING A SEQUENTIAL FILE

A file must be opened before you create, write or read it.


If you want to open a file, you must named the file and specify its task ( to read, write
or append).
Syntax for opening a file:
FILE *fileptr;
fileptr = fopen(filename, access_mode)

fileptr is a special ponter that points to that file. It was declared as FILE *fileptr.
Below is a table showing the file access mode.

String

Meaning

Open file for reading only. File must already exist.

Create file for writing. If a file by that name already


exists, it is overwritten

Append, open for writing at end of file, or create for


writing if the file does not exist.

r+

Opening an existing file for update (both for reading


and writing)

w+

Creating a new file for update (reading and writing). If a


file by that name already exists, it is overwritten.

a+

Open for append, open for update at the end of the file,
or create if the file does not exist.

if you wanted to open a file to retrieve information, you would use


a statement similar to this one:

FILE *fptr;
fptr = fopen(C:\\TEST.DAT, w);

if you want to test the return value to ensure the file was open correctly, use the
following code segment:

FILE *fptr
If ((fileptr = fopen(C:\\TEST.DAT, r)) == NULL)
{
printf(Error: Cannot open input file\n);
exit(0);
}

P a g e 99
GM I/ IE/ C L5/ REV00/05

HANDOUT

2.0

SPG 0412

PROGRAMMING IN C

WRITING CHARACTERS TO A SEQUENTIAL FILE

the function that writes a single character to the file is putc( ).


General syntax:

int putc(int c; FILE fileptr);

Example:

FILE *fptr;
fptr = fopen(FILE.TXT, w);
putc(p, fptr);
fclose(fptr);
/*Writer.c - writing to a text file*/
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
int main( ){
char ch, filename[85];
FILE *fileptr;
printf("\nEnter filename: ");
gets(filename);

/*create a filename*/

printf("\n\nType # on a blank line to end\n\n"); /*Type characters into file*/


if ((fileptr = fopen(filename, "w")) == NULL) /*Open file for writing*/
{
printf("Error: Cannot open input file\n");
exit(0);
}
while((ch=getchar()) != '#') /*type character into file and stop by typing #*/
{
putc(ch, fileptr); /*putc for writing to file*/
}
fclose(fileptr); /*close the file*/
return 0;
}
Output

Enter filename: Myfile.dat


Type # on a blank line to end
Ali likes to play football. Everyday Ali plays football in the field behind his
house.
#

P a g e 100
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3.0 READING CHARACTERS FROM A


SEQUENTIAL FILE

fgetc() function can be used to get the character from file,


and displays that character on screen with the putchar() function.
Example:
while (!feof(fileptr))
{
ch = fgetc(fileptr);
/*get next char from file*/
putchar(ch); /*Display character on screen*/
}

/*typer.c - sends character from file to the display*/


#include <stdio.h>
#include <stdlib.h>
int main( )
{
char ch, filename[85];
FILE *fileptr;
printf("\nPlease enter filename: "); /*Input filename*/
gets(filename);
if ((fileptr = fopen(filename, "r")) == NULL) /* Open file for reading*/
{
printf("Error: cannot open input file\n");
exit(0);
}
printf("\n\n.***Listing of: %s***\n", filename);
while(!feof(fileptr))
{
ch = fgetc(fileptr); /*Get the next character from file* by using fgetc*/
putchar(ch); /*Display character on screen by using putchar*/
}
fclose(fileptr);
return 0;

P a g e 101
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Please enter filename: MyFile.dat


.***Listing of: MyFile.dat***
Ali likes to play football. Everyday Ali plays football in the field behind his
house.

4.0 READING AND WRITING STRINGS TO A SEQUENTIAL FILE

The fputs() function is use to write an entire strings at once from file.

/*Strwrite.c - writing to a text file*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLINELEN 135
int main( ){
char ch, filename[85], strline[MAXLINELEN];
FILE *fileptr;
printf("\nPress Enter on a blank line to exit.");
printf("\nEnter filename to write to: "); /*create a filename*/
gets(filename);
if ((fileptr = fopen(filename, "w")) == NULL) /*Open file for writing*/
{
printf("Error: Cannot open input file\n");
exit(0);
}
while(strlen(gets(strline))>0) /*type character into
file and stop by typing #*/
{
fputs(strline, fileptr);
fputs("\n", fileptr);
}
fclose(fileptr); /*close the file*/
return 0;
}

P a g e 102
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Output
Press Enter on a blank line to exit.
Enter filename to write to: Example.dat
Today is a beautiful day. Mary strolls in the park with her friend, Don.

fgets( ) function is used to read strings from file.


the general syntax is:
fgets(strline, MAXLINELEN, fileptr);

/*Strread.c - writing to a text file*/


#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#define MAXLINELEN 135
int main( ){
char ch, filename[85], strline[MAXLINELEN];
int line = 0;
FILE *fileptr;
printf("\nEnter filename to read from: "); /*create a
filename*/
gets(filename);
if ((fileptr = fopen(filename, "r")) == NULL) /*Open
file for reading*/
{
printf("Error: Cannot open input file\n");
exit(0);
}
while(!feof(fileptr))
{
fgets(strline, MAXLINELEN,fileptr); /*strline ( )
function is used to count the lines in the file*/
printf("%s", strline);
line++;
}
fclose(fileptr); /*close the file*/
printf("\n***There were %d lines in that file\n", line);
return 0;
}

P a g e 103
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Output

Enter filename to read from: Example.txt


Today is a beautiful day. Mary strolls in the park with her friend, Don.
***There were 1 lines in that file

P a g e 104
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Exercise

1. Fill in the blanks in each of the following:


a) The ___________ function closes a file
b) The ___________ statement reads data from a file in a manner similar to
how scanf reads from stdin.
c) The ___________ function reads a character from a specified file.
d) The ___________ functions reads a line from a specified file.
e) The ___________ function opens a file.
f) The ___________ function is normally used when reading data from a file in
random access applications.

2. Find the error in each of the following program segments. Explain how the error
can be corrected.
a) The file referred to by fPtr(payables.dat) has not been open.
fprintf (fPtr, %d%s%d\n, account, company, amount);
b) open(receive.dat, r+);
c) The file tools.dat should be opened to add data to the file without discarding the
current data.
if ((tfPtr = fopen(tools.dat, w)) != NULL)
d) The file courses.dat should be opened for appending without modifying the
contents of the file.
if ((cfPtr = fopen(courses.dat, w+)) != NULL)

P a g e 105
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

CHAPTER 10

Structure

P a g e 106
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

1.0 Advanced data structure

A structure is a user defined data type.

You have the ability to define a new type of data considerably more complex than the
types we have been using.

A structure is a combination of several different previously defined data types,


including other structures we have defined.

An easy to understand definition is, a structure is a grouping of related data in a way


convenient to the programmer or user of the program.

2.0 Defining a structure

A structure can be defned with the keyword struct.


Struct defined a new data type that can be used by the programme.
Here is the general format of writing a structure:
struct structure_name {
data_definition_1;
data_definition_2;
:
data_definition_n;
};

this can be applied to the examples below:


struct student {
char name[30];
char icNo[15];
char matrix[7];
};

struct date {
int day;
int month;
int year;
};

P a g e 107
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

#include <stdio.h>
void main( )
{
struct {
char initial; /* last name initial */
int age;
/* childs age
*/
int grade;
/* childs grade in school */
} boy,girl;
boy.initial = 'R';
boy.age = 15;
boy.grade = 75;
girl.age = boy.age - 1; /* she is one year younger */
girl.grade = 82;
girl.initial = 'H';
printf("%c is %d years old and got a grade of %d\n",
girl.initial, girl.age, girl.grade);
printf("%c is %d years old and got a grade of %d\n",
boy.initial, boy.age, boy.grade);
}

Output
H is 14 years old and got a grade of 82
R is 15 years old and got a grade of 75
Press any key to continue

P a g e 108
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

3.0 Referring to the element of a structure.

Each element of a structure can be refered by using dot operator ( . )


The format is :
variable.data_definition

e.g boy.age = 15

4.0 Local / Global structure

struct students /* global structure */


{
char name[25];
int age;
float average;
};
int main( )
{
students student1, student2; /* local structure */
/* .... the rest of the program .... */
}
5.0
Array of structures
#include <stdio.h>
struct personal_detail
{
int id_number;
char name[50];
char town[50];
};
int main( )
{ struct personal_detail student[20];
printf(Id-No : );
scanf(%i, &student[1]. id_number);
printf(Name : );
scanf(%s, &student[1]. name);
printf(Town: );
scanf(%s, &student[1]. town);
printf(\nThe student is %s with id# %d from %s,
student[1].name, student[1].id_number, student[1].town);
return 0;
}

P a g e 109
GM I/ IE/ C L5/ REV00/05

HANDOUT

SPG 0412

PROGRAMMING IN C

Output
Id-No : 1234
Name : Aminah
Town: KL
The student is Aminah with id# 1234 from KL

Exercise
1. Write a structure definition struct for a student with the following information:
a) name
b) date of birth
c) new identity card number
d) telephone number

2. Look at the following segment:


struct node {
int x, y;
};
struct nod A, B, C, D;
int l, t;

scanf(%d, %d, %d, %d, %A.x, &A.y, &l, &t);


B.x = A.x + 1;

B.y = A.y;

C.x = B.x;

C.y = A.y + t;

D.x = A.x;

D.y = C.y;

printf(Nod A: %d, %d\n, A.x, A.y);


printf(Nod B: %d, %d\n, B.x, B.y);
printf(Nod C: %d, %d\n, C.x, C.y);
printf(Nod D: %d, %d\n, D.x, D.y);

What is the output if the input read is:


a)

10

b)

100

20

100

55

c)

333

222

P a g e 110
GM I/ IE/ C L5/ REV00/05

Вам также может понравиться