0% found this document useful (0 votes)
20 views

C Programming Notes With Example

The document provides an overview of the system development life cycle and methodology for developing software programs. It describes the common phases of analysis, design, implementation, testing, and maintenance. It also explains the typical project phases of feasibility study, requirements definition, system design, implementation, testing, deployment, and maintenance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

C Programming Notes With Example

The document provides an overview of the system development life cycle and methodology for developing software programs. It describes the common phases of analysis, design, implementation, testing, and maintenance. It also explains the typical project phases of feasibility study, requirements definition, system design, implementation, testing, deployment, and maintenance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

lOMoARcPSD|10181059

C programming Notes With Example

Computer Programming (Universiti Teknologi MARA)

StuDocu is not sponsored or endorsed by any college or university


Downloaded by Battle Of Fierce Gaming ([email protected])
lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

C PROGRAMMING

Module: CIT 0513 COMPUTER & PROGRAMMING

(general reference material for chap 3 to chap 10)

Prepared By : ANDREW NESARAJA \ EASWARAN G

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

CHAPTER 1

System Development Methodology

Page 2
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

1.0 Life Cycle of Software Development

Analysis Design

Coding-
Implementation
Maintenance

Figure 1.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 represented project phases

2. The arrows represent inputs and outputs (working documentation) for a phase.

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 3
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

1 2
Feasibility assessment
Survey Study
project current
Project scope & system
request feasibility

Problem statement
START Facts
3
Define the
Requirements end-users’
requirements

FINISH Opinions and approvals

Requirements statement

Opinions
Delivered 4
system &
enhancements Select a
feasible
solution
( from
candidate
solutions) Request for
9 proposals

Maintain Approved
and system
5 proposal
6
improve the
system End-user Design the Acquire
training new system computer
Configuration
hardware
and
New information software
system Design specification
Proposals

8 7 Vendors

Deliver the Construct


new system the new
Computer system
software

Figure 1.1.2 System Development Life Cycle (SDLC)

Page 4
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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-user’s 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 5
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 analyst’s 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 6
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

1 2
Lot location
Survey the
Study current
situation environment
Dream
house
idea
Current environment
Land surveys, zoning laws, & constraints
START budget, neighbourhood
3
Homeowner’s requirements
Define the
end-users'
requirements

FINISH Homeowner’s opinions

Homeowner’s requirements

Architectural possibilities
Mortgage 4
& furnishing
Evaluate
architect’s
alternatives

Decision
5 6
Bid request
Design the Select
new house materials &
Configuration
sub-
contractors

Blueprints
Bids

8 7 Subcontractors
and suppliers
Move into Construct
new house the new
House house

Figure 1.1. 3 SDLC – House Building example

Page 7
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

5 6
9
Maintain Design Acquisiti-
and on
improve

8 7
Delivery Construc-
tion
Vendors

Figure 1.1. 4 Six basic principals of SDLC

Page 8
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Survey project scope and feasibility

Study and analyze the current system

Define the end user’s requirements

Select a feasibility solution


Phase

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

Page 9
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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: Off


On page page Data storage or file

Process

Source/data
Material Flow destination
Data flow

Figure 1.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.

Pa g e 10
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

· 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
Process
Customer Process shipping
order data
Order Order data

Invoice 3

Payment Process
invoice

Figure 1.1. 7 High-level DFD of an order

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

Pa g e 11
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

1 Process Order

1.3 To
4
Process
Pricing
In stock
To
2
1.1 1.2 Pricing data
Customer
Order Check
entry inventory
Out of stock

Quantities 1.4

Inventory Backorders

Backorder items

Backorder data

Figure 1.1.8 The explosion of process order

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

Pa g e 12
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 system’s application.

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

3.4.2 System Flowchart - Symbols

Process I/O
Decision
Termination

Online Document Manual Operation


Storage Manual
Input

Offline

Off-page connector

Pa g e 13
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

Record
Customer
Orders

Customer orders

Keying
operation

inventory Process customer


master file Customer order master file

sales report Shipping invoices backorders


documents

Figure 1.1.9 Example of a system flowchart

Pa g e 14
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Process I/O
Decision
Begin/Termination

Example : Coming to GMI

Go out from hostel

Y
Take a Walk to the
bus? nearest bus stop

N
Wait for the bus

Take own vehicle Y Take your


to GMI own
vehicle? Take the bus to
GMI

Walk to GMI

Pa g e 15
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

Determine the level


of lecture hall

Y
Take a Go to the lift and press a
lift? button

Wait until the door


opens
N

N Y
Lift Go inside and press the
opens? floor/level number

Take the staircase.


N
Arrived Wait
?

Go out of lift

Walk to the lecture


hall

End

Pa g e 16
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Activity
SINGLE-EXIT

Yes
SINGLE-ENTRY Decision

Activity SELECTION
SINGLE-EXIT No
Activity
Activity
SINGLE-ENTRY

Activity

SINGLE-EXIT
No
Decision ITERATION

Yes
Activity
SINGLE-EXIT

Pa g e 17
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 18
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 905


Output: RM11.50 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.

6.Gallery Smart Shop sell items as below:-

Item Code Price(RM)


1 30.00
2 35.00
3 40.00
4 90.00
5 120.00

When a customer order an item, they will give the item’s 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.

Pa g e 19
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 20
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

CHAPTER 2

Basic structures of C
language

Pa g e 21
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 + 8 = 18

Num1 Num2 Sum

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

Pa g e 22
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 indicate that there are no data type 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.

Pa g e 23
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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;

Pa g e 24
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

Example: wrtmore.c Output:

main( ) This is a line of text to output.


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

· 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:

Pa g e 25
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

[] {} <> ()

! * + = “ ‘ . ?

# / \ & % - _ ^

~ | ; : , @ $ `

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;

Pa g e 26
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

/***********************************************/
/* 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"); /*Prompt*/


scanf("%d", &integer1); /*Input using scanf( )*/
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2; /*process*/
printf("Sum is %d", sum); /*display output*/

Output

Enter first integer


23
Enter second integer
12
Sum is 35

Pa g e 27
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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
2. float
3. char

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

Pa g e 28
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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;

3) Char

· 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

Pa g e 29
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

· 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”;

Pa g e 30
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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;

Pa g e 31
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

· 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) Order of evaluation (precedence)


() Parentheses 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.
*, / , or % Multiplication Evaluated second. If there are several, they are
Division evaluated left to right.
Modulus
+ or - Addition Evaluated last. If these are several, they are
Subtraction 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 2 4 3 5

Example #2

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

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

1 2

Pa g e 32
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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) == Equal to


> Greater than (GT) != Not equal to
>= GT/ET <= 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) – result=true IF expressions=true


|| (OR) - result=true IF either expressions=true
! (NOT) - reverse the expression’s condition

Pa g e 33
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 34
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 35
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 36
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

CHAPTER 3

Function

Pa g e 37
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 38
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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.

Pa g e 39
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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); /*f.declaration of circle*/


void Cross (void); /*f.declaration of cross*/
void Base (void); /*f.declaration of Base*/
void Triangle (void); /*f.declaration of Triangle*/

void main (void) {


circle( ); /*call circle*/
Triangle( ); /*call Triangle*/
Cross( ); /*call cross*/
}

void circle(void){ /*f.definition of circle*/


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

void Triangle(void) { /*f.definition of Triangle*/


Cross( );
Base( );
}

void Cross(void) { /*f.definition of Cross*/


printf("\t /\\ \n");
printf("\t / \\ \n");
printf("\t/ \\\n");
}

void Base(void) { /*f.definition of Base*/


printf("\t------\n");
}

Pa g e 40
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

Output

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

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

Pa g e 41
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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


{

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

Pa g e 42
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

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

Pa g e 43
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

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

Pa g e 44
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 cube’s 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)

Pa g e 45
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

CHAPTER 4

Input and Output

Pa g e 46
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 47
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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.

· don’t 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

Pa g e 48
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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.

Format specifier Output Type


%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

Pa g e 49
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

Table 4.3. Scanf() conversion codes.

Character Description
%c Single character

%d Signed decimal

%e Floating-point value
in
%f Floating-point value

%h Short integer

%i Integer

%o Octal integer

%s String of characters

%u Unsigned decimal

%x Hexadecimal integer

Pa g e 50
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

#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

Pa g e 51
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 52
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 it’s 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);
}

Pa g e 53
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

CHAPTER 5

Decision Structure

Pa g e 54
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 True
condition step 1 .. k if num Odd
%2

False False

step k + 1 Even

end

Single if structure
Example : Determine an odd or
even number

Pa g e 55
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

step a

False True
step k + 1..n condition step 1 .. k

step n + 1

Multiple if structure

Start

Input mark

False True
Failed If mark Passed
>= 50

End

Example: Determine status according to mark entered

Pa g e 56
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

#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"); /*If mark >= 80 - distinction*/
else if(mark >= 50)
printf("Passed\n"); /*If mark >= 50 - Passed*/
else
printf("Failed\n"); /*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");
}

Pa g e 57
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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) /*the symbol for equal is == */


printf("You guess the number!\n");

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

Pa g e 58
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

Output
Please enter a number to guess
34
You guess too high
Press any key to continue

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

Pa g e 59
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

True
case 1 steps 1 .. k

False
True steps k+1..m
case 2

False

case n True steps n+1..p

False

steps q.. r

The switch structure flowchart

Start

True
case 1 print ‘ 1 ‘

False
True
case 2 print ‘ 2 ‘

False

case n True print ‘ n ‘

False

default

End
An example of switch structure

Pa g e 60
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

/*Demonstrating simple switch*/

#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"); /*print Two if number == 2*/


break;

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;

Pa g e 61
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

/*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");

Pa g e 62
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 63
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 64
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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)

Pa g e 65
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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)

Pa g e 66
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

CHAPTER 6

Loop Structure

Pa g e 67
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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)

Pa g e 68
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

initial value i

checks
condition
True
steps 1 .. n update i value
of i

False

The for structure flowchart

Start

i=0

if
i >= 10
True print the
value of i i++

False

End

Example : Printing the value of i

Pa g e 69
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

/*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 3 4 5 6 7 8 9 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
* * *
* * *
* * *
* * *
* * *

Pa g e 70
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 - True Steps 1 .. n


dition

False

The while loop structure flowchart

Start

n=1

n >= True print the


5 value of n

False

End

Example : printing 1 to 5 using while loop

Pa g e 71
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

/*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 2 3 4 5 6 7 8 9 10

Pa g e 72
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

1.3 The do…while 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
do…while loop checks its condition at the end of the loop.

· this means that a do…while 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

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

Pa g e 73
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

/*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 2 3 4 5 6 7 8 9 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”);
}

Pa g e 74
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 75
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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 10
Used continue to skip printing the value 5

Pa g e 76
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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. (6 Marks)
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;

Pa g e 77
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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)

Pa g e 78
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

CHAPTER 7

Array

Pa g e 79
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

1.0 A r r a y
o A group of items of the same type under one variable name.

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

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

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

1 .1 O n e - di m e n si o na l a r r a y
· 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.

Pa g e 80
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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

Pa g e 81
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

1 .2 M ul t id im e ns io na l a r r ay
· 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

Pa g e 82
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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?

Pa g e 83
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])


lOMoARcPSD|10181059

GE RMAN- MALAYS IAN INST ITUT E

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;

Pa g e 84
HLZ /RE V 2

Downloaded by Battle Of Fierce Gaming ([email protected])

You might also like