Download as pdf or txt
Download as pdf or txt
You are on page 1of 281

Introduction to

Computer Programming
(DCE2364)

Penang Skills Development Centre. All rights reserved.


Any reproduction of this handbook is prohibited without prior written agreement from the PSDC.
All text and graphics published are copyrighted and/or trademarked by their respective copyright holders. Every effort has
been made to respect the copyrights of others - please contact us if you have concerns as to the use of ny materials here.

Rev 1, Feb 2006

Outcome 1

Outcome 1

Computer Systems,

Computer Systems,

Programming Languages and

Programming Languages and

Problem Solving Using Programming

Problem Solving Using Programming

Content

Content

Introduction and Objectives

1-1

Introduction and Objectives

1-1

Computer and Their Uses

1-3

Computer and Their Uses

1-3

Operating System

1-7

Operating System

1-7

Computer Hardware

1-11

Computer Hardware

1-11

Outcome 2

Outcome 2

History of Compiler,

History of Compiler,

Interpreter and 4GL

Interpreter and 4GL

Content

Content

Introduction and Objectives

2-1

Introduction and Objectives

2-1

Compiler & Interpreter

2-2

Compiler & Interpreter

2-2

Computer Programs and Programming Languages

2-4

Computer Programs and Programming Languages

2-4

Basic Keywords of Programming

2-8

Basic Keywords of Programming

2-8

Outcome 3

Outcome 3

Programming Tools and Concepts

Programming Tools and Concepts

Content

Content

Introduction and Objectives

3-1

Introduction and Objectives

3-1

Development of Algorithms

3-2

Development of Algorithms

3-2

Pseudocode

3-5

Pseudocode

3-5

Flow Charting

3-17

Flow Charting

3-17

Summary

3-24

Summary

3-24

Outcome 4

Outcome 4

Variables, Operators and

Variables, Operators and

Fundamental of Input and Output

Fundamental of Input and Output

Content

Content

Introduction and Objectives

4-1

Introduction and Objectives

4-1

Programming Concepts

4-2

Programming Concepts

4-2

The Structure of C Program

4-8

The Structure of C Program

4-8

Statements

4-14

Statements

4-14

A First Look at Function

4-15

A First Look at Function

4-15

Introduction to MS Visual C/C++ 6.0

4-17

Introduction to MS Visual C/C++ 6.0

4-17

Operators

4-23

Operators

4-23

Summary

4-27

Summary

4-27

Outcome 5

Outcome 5

Basic Program Control Structures

Basic Program Control Structures

Content

Content

Controlling Programs Execution

5-1

Controlling Programs Execution

5-1

Outcome 6

Outcome 6

Selection Control Structures

Selection Control Structures

Content

Content

Introduction and Objectives

6-1

Introduction and Objectives

6-1

Selection Control Structures

6-2

Selection Control Structures

6-2

Summary

6-14

Summary

6-14

Outcome 7

Outcome 7

Array, Pointer and Character String

Array, Pointer and Character String

Content

Content

Introduction and Objectives

7-1

Introduction and Objectives

7-1

Definition

7-2

Definition

7-2

1-Dimensional Array

7-3

1-Dimensional Array

7-3

2-Dimensional Array

7-7

2-Dimensional Array

7-7

Examples

7-12

Examples

7-12

Pointers

7-14

Pointers

7-14

Character Strings

7-19

Character Strings

7-19

Summary

7-23

Summary

7-23

Outcome 8

Outcome 8

Structure and Function

Structure and Function

Content

Content

Introduction and Objectives

8-1

Introduction and Objectives

8-1

Introduction to Structure

8-2

Introduction to Structure

8-2

Function

8-9

Function

8-9

Summary

8-17

Summary

8-17

Appendix
Content

Appendix
Content

C Keywords / Reserved words

C Keywords / Reserved words

Appendix Outcome 4

Appendix Outcome 4

Appendix Outcome 5

14

Appendix Outcome 5

14

Appendix Outcome 6

22

Appendix Outcome 6

22

Appendix Outcome 7

35

Appendix Outcome 7

35

Appendix Outcome 8

67

Appendix Outcome 8

67

Outcome 1

Outcome 1

Computer Systems,

Computer Systems,

Programming Languages and

Programming Languages and

Problem Solving Using

Problem Solving Using

Programming

Programming

Introduction and Objectives

Introduction and Objectives

Chapter

In this chapter, you will learn about

Chapter

In this chapter, you will learn about

Objectives

What computer is

Objectives

What computer is

Types of computers

Types of computers

o Special Purpose computers

o Special Purpose computers

o General-purpose computers

o General-purpose computers

o Microcomputers

o Microcomputers

o Minicomputers, mainframes and

o Minicomputers, mainframes and

supercomputers

Computing modes

supercomputers

Computing modes

o Standalone computing

o Standalone computing

o Multiprogramming and timesharing

o Multiprogramming and timesharing

o Distributed and client/server computing

o Distributed and client/server computing

Computer hardware & software

Computer hardware & software

Fundamental capabilities of computer hardware

Fundamental capabilities of computer hardware

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-1

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-1

Introduction and Objectives


Introduction

Today, computers are used for solving problems in most all

Introduction and Objectives


Introduction

Today, computers are used for solving problems in most all

fields and professions. No matter what your major, you should

fields and professions. No matter what your major, you should

develop the ability to solve problems, and its very likely that

develop the ability to solve problems, and its very likely that

you will need to use computers problem solving. In our

you will need to use computers problem solving. In our

studies, we will learn how to identify problems that can be

studies, we will learn how to identify problems that can be

solved using computers, how to specify such problems,

solved using computers, how to specify such problems,

analyze them, design a method of solutions for them,

analyze them, design a method of solutions for them,

implement the method of solution using a computer

implement the method of solution using a computer

programming language, and get solutions using a computer.

programming language, and get solutions using a computer.

To develop this problem-solving ability, we must have three

To develop this problem-solving ability, we must have three

tools:

tools:

1. A knowledge of computer fundamentals

1. A knowledge of computer fundamentals

2. An understanding of problem-solving strategies and

2. An understanding of problem-solving strategies and

techniques
3. A programming language

techniques
3. A programming language

The programming language we will study is C. C is a general-

The programming language we will study is C. C is a general-

purpose, state-of-the art language that is powerful and

purpose, state-of-the art language that is powerful and

versatile. But before we can begin learning C, we should

versatile. But before we can begin learning C, we should

become knowledgeable about computers, programming, and

become knowledgeable about computers, programming, and

programming languages. Thats what this chapter is all about.

programming languages. Thats what this chapter is all about.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-2

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-2

Computer and Their Uses

Computer and Their Uses

What is a

A computer is an electronic device that can input and store a

What is a

A computer is an electronic device that can input and store a

computer?

set of instructions designed to perform a specific task, input

computer?

set of instructions designed to perform a specific task, input

and store data, process the stored data according to the

and store data, process the stored data according to the

instructions, and produce output to be relayed to its user.

instructions, and produce output to be relayed to its user.

Some computers are designed to process a permanent set of

Some computers are designed to process a permanent set of

instructions, and therefore perform one specific task; others

instructions, and therefore perform one specific task; others

are more flexible and can execute various instructions.

are more flexible and can execute various instructions.

Accordingly, computers are classified as either special-

Accordingly, computers are classified as either special-

purpose or general-purpose computers.

purpose or general-purpose computers.

Special-Purpose

A special-purpose computer is a computer designed for a

Special-Purpose

A special-purpose computer is a computer designed for a

Computers

particular function, executing the same stored set of

Computers

particular function, executing the same stored set of

instructions whenever requested.

instructions whenever requested.

General-purpose

Computers that can be used for solving many different types

General-purpose

Computers that can be used for solving many different types

computers

of problems are called general-purpose computers. All

computers

of problems are called general-purpose computers. All

computers can store instructions in their memory, can input

computers can store instructions in their memory, can input

and store data, can process data and can produce data.

and store data, can process data and can produce data.

A set of instructions that perform a specific task is called a

A set of instructions that perform a specific task is called a

program. Computer programs are written by computer

program. Computer programs are written by computer

programmers using special languages called programming

programmers using special languages called programming

languages. A programmer takes a problem, analyze it and

languages. A programmer takes a problem, analyze it and

design a program that, it correct, will produce the desired

design a program that, it correct, will produce the desired

solutions to the problem. The program must be written in a

solutions to the problem. The program must be written in a

computer language so that the computer can understand the

computer language so that the computer can understand the

instructions that make up the program.

instructions that make up the program.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-3

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-3

Microcomputers

Computer and Their Uses

Computer and Their Uses

General-purpose computers are available in many sizes and

General-purpose computers are available in many sizes and

have a wide range of capabilities. They can be classified as

have a wide range of capabilities. They can be classified as

follows:

follows:

Microcomputers

Microcomputers

o Laptop computers

o Laptop computers

o Desktop computers

o Desktop computers

o Workstation

o Workstation

Minicomputers

Minicomputers

Mainframe Computers

Mainframe Computers

Supercomputers

Supercomputers

Microcomputers are widely used for many applications

Microcomputers

Microcomputers are widely used for many applications

ranging from computer games, to word processing, to solving

ranging from computer games, to word processing, to solving

quite complex problems. Because one person commonly uses

quite complex problems. Because one person commonly uses

them at a time, microcomputers are also called personal

them at a time, microcomputers are also called personal

computers.

computers.

The smallest microcomputers are known as laptop or

The smallest microcomputers are known as laptop or

notebook computers. These computers can run on battery

notebook computers. These computers can run on battery

power. Desktop computers are compact microcomputer

power. Desktop computers are compact microcomputer

systems that fit on a desk and designed for use by individuals.

systems that fit on a desk and designed for use by individuals.

And a workstation is the largest type of microcomputer and

And a workstation is the largest type of microcomputer and

is generally used in scientific and engineering applications.

is generally used in scientific and engineering applications.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-4

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-4

Computer and Their Uses


Minicomputers,
Mainframes

and

Supercomputers

Computing modes

Computer and Their Uses

These are computers that are more powerful and substantially

Minicomputers,

more expensive than microcomputers. They can store more

Mainframes

data

Supercomputers

and

operate

at

significantly

faster

speeds.

These are computers that are more powerful and substantially


and

more expensive than microcomputers. They can store more


data

and

operate

at

significantly

faster

speeds.

Minicomputers are smaller and cheaper compared to

Minicomputers are smaller and cheaper compared to

mainframes.

mainframes.

Mainframes

computers

are

large-scale

Mainframes

computers

are

large-scale

computers that are used to process large volumes of data.

computers that are used to process large volumes of data.

Supercomputers are very powerful computers that can

Supercomputers are very powerful computers that can

process enormous amounts of data at very high speed. They

process enormous amounts of data at very high speed. They

are used in many areas of scientific research, weather

are used in many areas of scientific research, weather

prediction, aircraft design, nuclear weapons research, and so

prediction, aircraft design, nuclear weapons research, and so

on.

on.

Depending on their capabilities and the number of users they

Computing modes

Depending on their capabilities and the number of users they

can support concurrently, computers are used in several

can support concurrently, computers are used in several

computing modes. These include:

computing modes. These include:

1.

Standalone computing

1.

Standalone computing

2.

Multiprogramming and timesharing

2.

Multiprogramming and timesharing

3.

Distributed computing

3.

Distributed computing

4.

Client/server computing

4.

Client/server computing

Standalone

When used by one person at a time, a microcomputer is said

Standalone

When used by one person at a time, a microcomputer is said

Computing

to be in a standalone-computing mode. In this mode, all

Computing

to be in a standalone-computing mode. In this mode, all

computing resources, including the machine, programs, and

computing resources, including the machine, programs, and

data are at the disposal of only one user.

data are at the disposal of only one user.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-5

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-5

Computer and Their Uses

Computer and Their Uses

Multiprogramming

Minicomputers, mainframes and supercomputers are designed

Multiprogramming

Minicomputers, mainframes and supercomputers are designed

and Time Sharing

to be share by many different users in educational and

and Time Sharing

to be share by many different users in educational and

scientific institutions, businesses and government agencies.

scientific institutions, businesses and government agencies.

One minicomputer, mainframe, or supercomputer can be used

One minicomputer, mainframe, or supercomputer can be used

to simultaneously execute many programs.

to simultaneously execute many programs.

This mode of operation for a computer system is called

This mode of operation for a computer system is called

multiprogramming. A special form of multiprogramming is

multiprogramming. A special form of multiprogramming is

timesharing, in which a single computer system is accessed

timesharing, in which a single computer system is accessed

by many users through terminals.

by many users through terminals.

Distributed

In many computing labs in colleges, industry and business,

Distributed

In many computing labs in colleges, industry and business,

Computing

several microcomputers are linked together in computer

Computing

several microcomputers are linked together in computer

networks. This mode of computing is referred to as distributed

networks. This mode of computing is referred to as distributed

computing, in which each user of the system may have access

computing, in which each user of the system may have access

to programs and/or data stored anywhere in the network. In

to programs and/or data stored anywhere in the network. In

general, a distributed computer system can consist of one or

general, a distributed computer system can consist of one or

more computers or any type. It may include many

more computers or any type. It may include many

microcomputers linked to one or more minicomputers,

microcomputers linked to one or more minicomputers,

mainframes or supercomputers. It may also include input-

mainframes or supercomputers. It may also include input-

output devices such as printers, plotters and so on, which are

output devices such as printers, plotters and so on, which are

linked to computers located elsewhere.

linked to computers located elsewhere.

Client/Server

In some distributed computer systems, or one or more

Client/Server

In some distributed computer systems, or one or more

Computing

computers, called file servers, store programs and data, and

Computing

computers, called file servers, store programs and data, and

other computers, connected to then by a network, called

other computers, connected to then by a network, called

clients, can make use of these programs and data. This type of

clients, can make use of these programs and data. This type of

distributed computing is known as client/server computing.

distributed computing is known as client/server computing.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-6

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-6

Operating System

Operating System

The Operating

The operating system is the main collection of programs that

The Operating

The operating system is the main collection of programs that

System

manages a computer systems operations.

System

manages a computer systems operations.

NOS

Primary function to manage and control computers

Primary function to manage and control computers

resources. E.g. the allocation of hardware, programs and data

resources. E.g. the allocation of hardware, programs and data

resources to users.

resources to users.

Example of Operating System

Example of Operating System

MS-DOS

MS-DOS

Windows 95/98/2000/ME

Windows 95/98/2000/ME

Windows NT

Windows NT

Unix

Unix

Linux

Linux

The 3 common components found on operating systems are:

The 3 common components found on operating systems are:

Command Language Translator transforms the needs of

Command Language Translator transforms the needs of

users into actions that the operating system takes. Operating

users into actions that the operating system takes. Operating

system has its own language called the command language

system has its own language called the command language

which users and programmers issue command.

which users and programmers issue command.

Input/output control system (IOCS) interacts with input

Input/output control system (IOCS) interacts with input

and output hardware devices.

and output hardware devices.

Librarian software elements that catalogs and manages

Librarian software elements that catalogs and manages

data, programs, file space and users.

data, programs, file space and users.

A NOS is a network operating system. Network

NOS

A NOS is a network operating system. Network

operating systems implement protocol stacks as well

operating systems implement protocol stacks as well

as device drivers for networking hardware.

as device drivers for networking hardware.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-7

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-7

Operating System

Operating System

Some operating systems, like Windows 98 Second Edition,

Some operating systems, like Windows 98 Second Edition,

also add custom networking features like Internet Connection

also add custom networking features like Internet Connection

Sharing (ICS).

Sharing (ICS).

Network operating systems have existed for more than thirty

Network operating systems have existed for more than thirty

years. UNIX was designed from the beginning to support

years. UNIX was designed from the beginning to support

networking. In its early forms, Windows did not support

networking. In its early forms, Windows did not support

networking, so Novell NetWare became the first popular NOS

networking, so Novell NetWare became the first popular NOS

for the personal computer (Windows 95 and Windows for

for the personal computer (Windows 95 and Windows for

Workgroups were Microsoft's first NOS products). Today,

Workgroups were Microsoft's first NOS products). Today,

nearly any consumer operating system qualifies as NOS due

nearly any consumer operating system qualifies as NOS due

to the popularity of the Internet and the obvious need to

to the popularity of the Internet and the obvious need to

support Internet Protocol (IP) at a minimum.

support Internet Protocol (IP) at a minimum.

Unlike operating systems, such as DOS and Windows95,

Unlike operating systems, such as DOS and Windows95,

which are designed for single users to control one computer,

which are designed for single users to control one computer,

network operating systems (NOS) coordinate the activities of

network operating systems (NOS) coordinate the activities of

multiple computers across a network. The network operating

multiple computers across a network. The network operating

system acts as a director to keep the network running

system acts as a director to keep the network running

smoothly.

smoothly.

The two major types of network operating systems are:

The two major types of network operating systems are:

Peer-to-Peer

Peer-to-Peer

Client/Server

Client/Server

Windows for Workgroups are examples of programs that can

Windows for Workgroups are examples of programs that can

function as peer-to-peer network operating systems.

function as peer-to-peer network operating systems.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-8

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-8

Operating System

Peer to Peer

Client Server

Peer-to-peer network operating systems allow users to share

Operating System

Peer to Peer

Peer-to-peer network operating systems allow users to share

resources and files located on their computers and to access

resources and files located on their computers and to access

shared resources found on other computers.

shared resources found on other computers.

In a peer-to-peer network, all computers are considered equal;

In a peer-to-peer network, all computers are considered equal;

they all have the same abilities to use the resources available

they all have the same abilities to use the resources available

on the network. Peer-to-peer networks are designed primarily

on the network. Peer-to-peer networks are designed primarily

for small to medium local area networks. AppleShare and

for small to medium local area networks. AppleShare and

Client/server network operating systems allow the network to

Client Server

Client/server network operating systems allow the network to

centralize functions and applications in one or more dedicated

centralize functions and applications in one or more dedicated

file servers. The file servers become the heart of the system,

file servers. The file servers become the heart of the system,

providing access to resources and providing security.

providing access to resources and providing security.

Individual workstations (clients) have access to the resources

Individual workstations (clients) have access to the resources

available on the file servers. The network operating system

available on the file servers. The network operating system

provides the mechanism to integrate all the components of the

provides the mechanism to integrate all the components of the

network and allow multiple users to simultaneously share the

network and allow multiple users to simultaneously share the

same resources irrespective of physical location. Novell

same resources irrespective of physical location. Novell

Netware and Windows NT Server are examples of

Netware and Windows NT Server are examples of

client/server network operating systems.

client/server network operating systems.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-9

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-9

Operating System

Operating System

Examples of

The following list includes some of the more popular peer-to-

Examples of

The following list includes some of the more popular peer-to-

network operating

peer and client/server network operating systems.

network operating

peer and client/server network operating systems.

systems

o Microsoft Windows 95 / 98

systems

o Microsoft Windows 95 / 98

o Microsoft Windows NT Server

o Microsoft Windows NT Server

o Microsoft Windows NT Work Station

o Microsoft Windows NT Work Station

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-10

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-10

Computer Hardware

Computer Hardware

Since a computer consists of many components that function

Since a computer consists of many components that function

together to do an assigned task, it is a system. A computer

together to do an assigned task, it is a system. A computer

system is made up of hardware and software. Tangible or

system is made up of hardware and software. Tangible or

physical computer equipment is known as hardware.

physical computer equipment is known as hardware.

Components of

Hardware for a typical computer system include the following

Components of

Hardware for a typical computer system include the following

computer

components:

computer

components:

hardware

Main Memory

hardware

o Main memory

o Main memory

o Central Processing Unit (CPU)

o Central Processing Unit (CPU)

o Input devices

o Input devices

o Output devices

o Output devices

o Secondary memory devices

o Secondary memory devices

A computers main memory is an electronic device that stores

Main Memory

A computers main memory is an electronic device that stores

information necessary for a program to run. The information

information necessary for a program to run. The information

that can be stored in main memory can be the machine code

that can be stored in main memory can be the machine code

representations

representations

for

program

instructions,

numeric

or

for

program

instructions,

numeric

or

nonnumeric data values, pictures, sound, and so on. Each unit

nonnumeric data values, pictures, sound, and so on. Each unit

of information is stored in memory cell.

of information is stored in memory cell.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-11

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-11

Computer Hardware

Computer Hardware

Central Processing

The central processing unit (CPU), also called the processor,

Central Processing

The central processing unit (CPU), also called the processor,

Unit

is the hardware component that does most of the work in

Unit

is the hardware component that does most of the work in

Input Devices

executing a program. The processor consists of two functional

executing a program. The processor consists of two functional

units (a control unit and an arithmetic-logic unit), and a set of

units (a control unit and an arithmetic-logic unit), and a set of

registers. It retrieves each instruction and the corresponding

registers. It retrieves each instruction and the corresponding

data from the main memory and executes the instruction using

data from the main memory and executes the instruction using

the data as its operands.

the data as its operands.

The control unit of the processor supervises all activities of

The control unit of the processor supervises all activities of

the computer systems. It accesses and fetches each instruction

the computer systems. It accesses and fetches each instruction

of a program from the main memory in correct order and

of a program from the main memory in correct order and

writes it to an instruction register. It analyzes the instruction,

writes it to an instruction register. It analyzes the instruction,

determines its type, and breaks it into a series of simple

determines its type, and breaks it into a series of simple

actions. Then it sends coordinating signals to the appropriate

actions. Then it sends coordinating signals to the appropriate

computer components.

computer components.

The arithmetic-logic unit (ALU) is the electronic circuitry

The arithmetic-logic unit (ALU) is the electronic circuitry

capable of performing arithmetic operations (addition,

capable of performing arithmetic operations (addition,

subtraction, multiplication and division) and comparison

subtraction, multiplication and division) and comparison

operation.

operation.

We use input devices to communicate programs, data and

Input Devices

We use input devices to communicate programs, data and

special instructions to the computer. An input device accepts

special instructions to the computer. An input device accepts

information and transforms it to digital codes that the

information and transforms it to digital codes that the

computer can process. The keyboard is the common input

computer can process. The keyboard is the common input

device used in developing application programs for problem

device used in developing application programs for problem

solving.

solving.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-12

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-12

Computer Hardware
Output Devices

An output device communicates the solutions of problems

Computer Hardware
Output Devices

An output device communicates the solutions of problems

produces by using computers to the user. Computer output

produces by using computers to the user. Computer output

comes in three forms; hard copy, soft-copy, and machine-

comes in three forms; hard copy, soft-copy, and machine-

readable. Hard-copy output is produced on a hard medium

readable. Hard-copy output is produced on a hard medium

such as paper or film. Soft-copy output is temporarily

such as paper or film. Soft-copy output is temporarily

displayed on a surface, typically a video screen. Output in

displayed on a surface, typically a video screen. Output in

machine-readable form is sent to a secondary memory device,

machine-readable form is sent to a secondary memory device,

which can be a magnetic disk or a magnetic tape drive.

which can be a magnetic disk or a magnetic tape drive.

Secondary

A secondary memory device uses a permanent, nonvolatile

Secondary

A secondary memory device uses a permanent, nonvolatile

Memory Devices

medium on which information can be stored and from which

Memory Devices

medium on which information can be stored and from which

information can be retrieved. The most common secondary

information can be retrieved. The most common secondary

memory devices are magnetic disk drive and magnetic tape

memory devices are magnetic disk drive and magnetic tape

drives. Microcomputers may have floppy disk drive and hard

drives. Microcomputers may have floppy disk drive and hard

disk drives. Floppy disks are removable, transportable, and

disk drives. Floppy disks are removable, transportable, and

inexpensive. However, they have limited storage capacity. On

inexpensive. However, they have limited storage capacity. On

the other hand, hard disks have substantially larger capacity;

the other hand, hard disks have substantially larger capacity;

but they are fixed, cannot be removed, and are more

but they are fixed, cannot be removed, and are more

expensive.

expensive.

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-13

Outcome 1: Computer Systems, Programming Languages and Problem Solving Using


Programming
1-13

Outcome 2

Outcome 2

History Of Compiler,

History Of Compiler,

Interpreter and 4GL

Interpreter and 4GL

Introduction and Objective


Introduction

Introduction and Objective

Computer usage is increasing in almost every field of

Introduction

Computer usage is increasing in almost every field of

endeavor. In an era of steadily rising costs, computing costs

endeavor. In an era of steadily rising costs, computing costs

have been decreasing dramatically due to rapid developments

have been decreasing dramatically due to rapid developments

in both hardware and software technology.

in both hardware and software technology.

Software technology is based on programming languages. In

Software technology is based on programming languages. In

order to understand programming languages better, it is

order to understand programming languages better, it is

important to understand its fundamentals.

important to understand its fundamentals.

The fundamentals involve terminology like compiler,

The fundamentals involve terminology like compiler,

translator

translator

and

4GL.

The

history

and

evolution

of

and

4GL.

The

history

programming languages also helps,

programming languages also helps,

The objectives of this module are

The objectives of this module are

and

evolution

1. Differentiate between the compiler and translator

1. Differentiate between the compiler and translator

2. Explain what is programming language and its

2. Explain what is programming language and its

evolution
3. Understand

evolution
the

basic

terminology

used

programming
. 4. Understand the Operation System & Multi-tasking

Outcome 2: History of Compiler, Interpreter and 4GL


2-1

in

3. Understand

the

basic

terminology

used

programming
. 4. Understand the Operation System & Multi-tasking

Outcome 2: History of Compiler, Interpreter and 4GL


2-1

in

of

Compiler & Interpreter


Compiler

A compiler translates a computer program written in a human-

Compiler & Interpreter


Compiler

A compiler translates a computer program written in a human-

readable computer language (like Java) into a form that a

readable computer language (like Java) into a form that a

computer can execute. You have probably seen EXE files on

computer can execute. You have probably seen EXE files on

your computer. These EXE files are the output of compilers.

your computer. These EXE files are the output of compilers.

They contain executables -- machine-readable programs

They contain executables -- machine-readable programs

translated from human-readable program.

translated from human-readable program.

A compiler translates the code into machine code (1s and 0s),

A compiler translates the code into machine code (1s and 0s),

and saves it in an executable file format with extensions

and saves it in an executable file format with extensions

.COM or .EXE.

.COM or .EXE.

A compiler translates source code into object code. The

A compiler translates source code into object code. The

compiler derives its name from the way it works, looking at

compiler derives its name from the way it works, looking at

the entire piece of source code and collecting and

the entire piece of source code and collecting and

reorganizing the instructions. Thus, a compiler differs from an

reorganizing the instructions. Thus, a compiler differs from an

interpreter, which analyzes and executes each line of source

interpreter, which analyzes and executes each line of source

code in succession, without looking at the entire program. The

code in succession, without looking at the entire program. The

advantage of interpreters is that they can execute a program

advantage of interpreters is that they can execute a program

immediately. Compilers require some time before an

immediately. Compilers require some time before an

executable program emerges. However, programs produced

executable program emerges. However, programs produced

by compilers run much faster than the same programs

by compilers run much faster than the same programs

executed by an interpreter.

executed by an interpreter.

Outcome 2: History of Compiler, Interpreter and 4GL


2-2

Outcome 2: History of Compiler, Interpreter and 4GL


2-2

Compiler & Interpreter


Interpreter

4GLs

An interpreter translates program a line at a time as they are

Compiler & Interpreter


Interpreter

An interpreter translates program a line at a time as they are

being run.

being run.

The interpreter translates each line of code as it is read and

The interpreter translates each line of code as it is read and

executes that line before translating the next line. No

executes that line before translating the next line. No

executable file is created or used. Because of this, if a line is

executable file is created or used. Because of this, if a line is

to be repeated, as in iteration, it must be re-translated every

to be repeated, as in iteration, it must be re-translated every

time it is used. Obviously, interpreted languages are much

time it is used. Obviously, interpreted languages are much

slower than compiled languages. However, there are

slower than compiled languages. However, there are

advantages to interpretation. JavaScript scripts in Web pages

advantages to interpretation. JavaScript scripts in Web pages

on the Internet, for example, are interpreted so that the

on the Internet, for example, are interpreted so that the

executable code does not have to be downloaded from a host

executable code does not have to be downloaded from a host

machine. The interpretation is accomplished by the user's

machine. The interpretation is accomplished by the user's

browser. The advantages here are:

browser. The advantages here are:

o Downloaded scripts are smaller in size than codes.

o Downloaded scripts are smaller in size than codes.

o They are usually easier to program.

o They are usually easier to program.

The can be quickly modified since compilation steps are not

The can be quickly modified since compilation steps are not

necessary.

necessary.

Features of 4GLs are

4GLs

Features of 4GLs are

1. Many are easy to learn and use

1. Many are easy to learn and use

2. Developed for use by end-users

2. Developed for use by end-users

3. Designed to use in database environments

3. Designed to use in database environments

4. Require fewer instruction to perform the same tasks,

4. Require fewer instruction to perform the same tasks,

programming time shorter


5. Commands are very English like.

Outcome 2: History of Compiler, Interpreter and 4GL


2-3

programming time shorter


5. Commands are very English like.

Outcome 2: History of Compiler, Interpreter and 4GL


2-3

Computer Program and Programming Language

Computer Program and Programming Language

Computer

A computer program is a set of step-by-step instructions that

Computer

A computer program is a set of step-by-step instructions that

Program and

tells the computer how to solve a problem or complete a task.

Program and

tells the computer how to solve a problem or complete a task.

Programming

Subcategories of System Software

Programming

Subcategories of System Software

Language

Language

So programming language is a sub category of system

So programming language is a sub category of system

software.

software.

Programming Languages allow programmers to program

Programming Languages allow programmers to program

computers using English-like instructions that are translated

computers using English-like instructions that are translated

into the 1s and 0s (binary code) of machine language.

into the 1s and 0s (binary code) of machine language.

There are four general groups of programming languages:

There are four general groups of programming languages:

1. Machine Language

1. Machine Language

2. Assembly Language

2. Assembly Language

3. Procedural Languages; Fortran BASIC, C, Pascal, Turing,

3. Procedural Languages; Fortran BASIC, C, Pascal, Turing,

etc.
4. Functional,

etc.
Object

Oriented

and

Declarative

Languages Miranda; Java, VRML, Oracle, etc.

Outcome 2: History of Compiler, Interpreter and 4GL


2-4

4. Functional,

Object

Oriented

and

Declarative

Languages Miranda; Java, VRML, Oracle, etc.

Outcome 2: History of Compiler, Interpreter and 4GL


2-4

Computer Program and Programming Language

Computer Program and Programming Language

History of

1957 FORTRAN

History of

1957 FORTRAN

Programming

1958 ALGOL

Programming

1958 ALGOL

Language

1960 LISP

Language

1960 LISP

1960 COBOL

1960 COBOL

1962 APL

1962 APL

1962 SIMULA

1962 SIMULA

1964 BASIC

1964 BASIC

1964 PL/I

1964 PL/I

1966 ISWIM

1966 ISWIM

1970 Prolog

1970 Prolog

1972 C

1972 C

1975 Pascal

1975 Pascal

1975 Scheme

1975 Scheme

1977 OPS5

1977 OPS5

1978 CSP

1978 CSP

1978 FP

1978 FP

1980 dBASE II

1980 dBASE II

1983 Smalltalk-80

1983 Smalltalk-80

1983 Ada

1983 Ada

1983 Parlog

1983 Parlog

1984 Standard ML

1984 Standard ML

1986 C++

1986 C++

1986 CLP(R)

1986 CLP(R)

1986 Eiffel

1986 Eiffel

1988 CLOS

1988 CLOS

1988 Mathematica

1988 Mathematica

1988 Oberon

1988 Oberon

1990 Haskell

1990 Haskell

Outcome 2: History of Compiler, Interpreter and 4GL


2-5

Outcome 2: History of Compiler, Interpreter and 4GL


2-5

Computer Program and Programming Language

Computer Program and Programming Language

The Origins of C

The 'C' programming language was originally developed for

The Origins of C

The 'C' programming language was originally developed for

and C++:

and implemented on the UNIX operating system, on a DEC

and C++:

and implemented on the UNIX operating system, on a DEC

PDP-11 by Dennis Ritchie. One of the best features of C is

PDP-11 by Dennis Ritchie. One of the best features of C is

that it is not tied to any particular hardware or system. This

that it is not tied to any particular hardware or system. This

makes it easy for a user to write programs that will run

makes it easy for a user to write programs that will run

without any changes practically on all machines. C is often

without any changes practically on all machines. C is often

called a middle-level computer language as it combines the

called a middle-level computer language as it combines the

elements of high-level languages with the functionalism of

elements of high-level languages with the functionalism of

assembly language.

assembly language.

C allows the manipulation of bits, bytes and addresses- the

C allows the manipulation of bits, bytes and addresses- the

basic elements with which the computer functions. Another

basic elements with which the computer functions. Another

good point about C is its portability, which makes it possible

good point about C is its portability, which makes it possible

to adapt software written for one type of computer to another.

to adapt software written for one type of computer to another.

C was created, influenced, and field-tested by working

C was created, influenced, and field-tested by working

programmers.

programmers.

C++ is an enhanced version of the C language. C++ includes

C++ is an enhanced version of the C language. C++ includes

everything that is part of C and adds support for object-

everything that is part of C and adds support for object-

oriented programming (OOP). In addition, C++ also contains

oriented programming (OOP). In addition, C++ also contains

many improvements and features that make it a "better C",

many improvements and features that make it a "better C",

independent of object-oriented programming. C++ is actually

independent of object-oriented programming. C++ is actually

an extendible language since we can define new types in such

an extendible language since we can define new types in such

a way that they act just like the predefined types which are

a way that they act just like the predefined types which are

part of the standard language.

part of the standard language.

Outcome 2: History of Compiler, Interpreter and 4GL


2-6

Outcome 2: History of Compiler, Interpreter and 4GL


2-6

Computer Program and Programming Language

Computer Program and Programming Language

Released in 1985, C++ is an object-oriented programming

Released in 1985, C++ is an object-oriented programming

language created by Bjarne Stroustrup. It maintains almost all

language created by Bjarne Stroustrup. It maintains almost all

aspects of the C language, while simplifying memory

aspects of the C language, while simplifying memory

management. In addition, Stroustrup added classes and

management. In addition, Stroustrup added classes and

several other features to allow object-oriented programming.

several other features to allow object-oriented programming.

While having features allowing low-level access to memory,

While having features allowing low-level access to memory,

it also containing high level features which simplify the

it also containing high level features which simplify the

programming.

programming.

Outcome 2: History of Compiler, Interpreter and 4GL


2-7

Outcome 2: History of Compiler, Interpreter and 4GL


2-7

Basic Keywords for Programming

Basic Keywords for Programming

Basic keyword for

1. Source Code

Basic keyword for

1. Source Code

programming

Program instructions in their original form. The word source

programming

Program instructions in their original form. The word source

differentiates code from various other forms that it can have

differentiates code from various other forms that it can have

(for example, object code and executable code).

(for example, object code and executable code).

Initially, a programmer writes a program in a particular

Initially, a programmer writes a program in a particular

programming language. This form of the program is called the

programming language. This form of the program is called the

source program, or more generically, source code. To execute

source program, or more generically, source code. To execute

the program, however, the programmer must translate it into

the program, however, the programmer must translate it into

machine

machine

language,

the

language

that

the

computer

language,

the

language

that

the

computer

understands. The first step of this translation process is

understands. The first step of this translation process is

usually performed by a utility called a compiler. The compiler

usually performed by a utility called a compiler. The compiler

translates the source code into a form called object code.

translates the source code into a form called object code.

Sometimes the object code is the same as machine code;

Sometimes the object code is the same as machine code;

sometimes it needs to be translated into machine language by

sometimes it needs to be translated into machine language by

a utility called an assembler.

a utility called an assembler.

Source code is the only format that is readable by humans.

Source code is the only format that is readable by humans.

When you purchase programs, you usually receive them in

When you purchase programs, you usually receive them in

their machine-language format. This means that you can

their machine-language format. This means that you can

execute them directly, but you cannot read or modify them.

execute them directly, but you cannot read or modify them.

Some software manufacturers provide source code, but this is

Some software manufacturers provide source code, but this is

useful only if you are an experienced programmer.

useful only if you are an experienced programmer.

2. Program

2. Program

An organized list of instructions that, when executed, causes

An organized list of instructions that, when executed, causes

the computer to behave in a predetermined manner. Without

the computer to behave in a predetermined manner. Without

programs, computers are useless.

programs, computers are useless.

Outcome 2: History of Compiler, Interpreter and 4GL


2-8

Outcome 2: History of Compiler, Interpreter and 4GL


2-8

Basic Keywords for Programming

Basic Keywords for Programming

3. Instruction

3. Instruction

A basic command. The term instruction is often used to

A basic command. The term instruction is often used to

describe the most rudimentary programming commands. For

describe the most rudimentary programming commands. For

example, a computer's instruction set is the list of all the basic

example, a computer's instruction set is the list of all the basic

commands in the computer's machine language.

commands in the computer's machine language.

4. Variables

4. Variables

A symbol or name that stands for a value. For example, in the

A symbol or name that stands for a value. For example, in the

expression x + y, x and y are variables. Variables can

expression x + y, x and y are variables. Variables can

represent numeric values, characters, character strings, or

represent numeric values, characters, character strings, or

memory addresses.

memory addresses.

Variables play an important role in computer programming

Variables play an important role in computer programming

because they enable programmers to write flexible programs.

because they enable programmers to write flexible programs.

Rather than entering data directly into a program, a

Rather than entering data directly into a program, a

programmer can use variables to represent the data. Then,

programmer can use variables to represent the data. Then,

when the program is executed, the variables are replaced with

when the program is executed, the variables are replaced with

real data. This makes it possible for the same program to

real data. This makes it possible for the same program to

process different sets of data.

process different sets of data.

Every variable has a name, called the variable name, and a

Every variable has a name, called the variable name, and a

data type. A variable's data type indicates what sort of value

data type. A variable's data type indicates what sort of value

the variable represents, such as whether it is an integer, a

the variable represents, such as whether it is an integer, a

floating-point number, or a character.

floating-point number, or a character.

The opposite of a variable is a constant. Constants are values

The opposite of a variable is a constant. Constants are values

that never change. Because of their inflexibility, constants are

that never change. Because of their inflexibility, constants are

used less often than variables in programming.

used less often than variables in programming.

Outcome 2: History of Compiler, Interpreter and 4GL


2-9

Outcome 2: History of Compiler, Interpreter and 4GL


2-9

Basic Keywords for Programming

Basic Keywords for Programming

5. Computer Program

5. Computer Program

A computer program is a set of instructions that tell a

A computer program is a set of instructions that tell a

computer exactly what to do. The instructions might tell the

computer exactly what to do. The instructions might tell the

computer to add up a set of numbers, or compare two numbers

computer to add up a set of numbers, or compare two numbers

and make a decision based on the result, or whatever. But a

and make a decision based on the result, or whatever. But a

computer program is simply a set of instructions for the

computer program is simply a set of instructions for the

computer, like a recipe is a set of instructions for a cook or

computer, like a recipe is a set of instructions for a cook or

musical notes are a set of instructions for a musician. The

musical notes are a set of instructions for a musician. The

computer follows your instructions exactly and in the process

computer follows your instructions exactly and in the process

does something useful -- like balancing a checkbook or

does something useful -- like balancing a checkbook or

displaying a game on the screen or implementing a word

displaying a game on the screen or implementing a word

processor.

processor.

6. Programming language

6. Programming language

In order for a computer to recognize the instructions you give

In order for a computer to recognize the instructions you give

it, those instructions need to be written in a language the

it, those instructions need to be written in a language the

computer understands -- programming language. There are

computer understands -- programming language. There are

many computer programming languages -- Fortran, Cobol,

many computer programming languages -- Fortran, Cobol,

Basic, Pascal, C, C++, Java, Perl -- just like there are many

Basic, Pascal, C, C++, Java, Perl -- just like there are many

spoken languages. They all express approximately the same

spoken languages. They all express approximately the same

concepts in different ways.

concepts in different ways.

Outcome 2: History of Compiler, Interpreter and 4GL


2-10

Outcome 2: History of Compiler, Interpreter and 4GL


2-10

Outcome 3

Outcome 3

Programming Tools

Programming Tools

and Concepts

and Concepts

Introduction and Objective


Introduction

Introduction and Objective

Before writing a program to solve a problem, it is essential to

Introduction

Before writing a program to solve a problem, it is essential to

have a thorough understanding of the problem and a carefully

have a thorough understanding of the problem and a carefully

planned approach to solve the problem.

planned approach to solve the problem.

The objectives of this module are

The objectives of this module are

1. Understand the basic concepts in programming

1. Understand the basic concepts in programming

2. Pseudocode

2. Pseudocode

3. Flow Chart

3. Flow Chart

Outcome 3: Programming Tools and Concepts

Outcome 3: Programming Tools and Concepts


3-1

3-1

Development of Algorithms
Algorithm

Development of Algorithms

An algorithm is a sequence of a finite number of steps

Algorithm

An algorithm is a sequence of a finite number of steps

arranged in a specific logical order which, when executed,

arranged in a specific logical order which, when executed,

produces the solution for a problem.

produces the solution for a problem.

Stated somewhere differently, an algorithm is a procedure that

Stated somewhere differently, an algorithm is a procedure that

takes a set of values as input, and transform them into a set of

takes a set of values as input, and transform them into a set of

values as output. Obviously, not any arbitrarily constructed

values as output. Obviously, not any arbitrarily constructed

series of steps can be regarded as algorithms. An algorithm

series of steps can be regarded as algorithms. An algorithm

must satisfy some requirements:

must satisfy some requirements:

1. Input it must have input. It is conceivable that an

1. Input it must have input. It is conceivable that an

algorithm may have no input. An example could be one

algorithm may have no input. An example could be one

that generates a fixed report form. However, such

that generates a fixed report form. However, such

algorithms are rather trivial, and quite rare.

algorithms are rather trivial, and quite rare.

2. Output it must produce at least one output. An

2. Output it must produce at least one output. An

algorithm that does not produce anything is worthless.

algorithm that does not produce anything is worthless.

3. Unambiguousness it must be unambiguous. In most

3. Unambiguousness it must be unambiguous. In most

cases, we develop an algorithm so that it can be translated

cases, we develop an algorithm so that it can be translated

into a computer program to be executed by computers.

into a computer program to be executed by computers.

Computers cannot cope with ambiguities. Therefore, every

Computers cannot cope with ambiguities. Therefore, every

step in an algorithm must be clear as to what it is

step in an algorithm must be clear as to what it is

supposed to do, and how many times it is expected to be

supposed to do, and how many times it is expected to be

executed.

executed.

4. Generality it must have generality. A procedure that

4. Generality it must have generality. A procedure that

prints the message One inch is 2.54 centimeters is not

prints the message One inch is 2.54 centimeters is not

an algorithm; however; one that converts a supplied

an algorithm; however; one that converts a supplied

number of inches to centimeters is an algorithms.

number of inches to centimeters is an algorithms.

5. Correctness it must be correct and must solve the


problem for which it is designed.

Outcome 3: Programming Tools and Concepts

5. Correctness it must be correct and must solve the


problem for which it is designed.

Outcome 3: Programming Tools and Concepts


3-2

3-2

Development of Algorithms

Development of Algorithms

6. Finiteness it must execute its steps and terminate in

6. Finiteness it must execute its steps and terminate in

finite time. An algorithm that never terminates is

finite time. An algorithm that never terminates is

unacceptable.

unacceptable.

7. Efficiency it must be efficient. An algorithm that is

7. Efficiency it must be efficient. An algorithm that is

designed for a specific computer is not worth much if it

designed for a specific computer is not worth much if it

takes days to solve a relatively simple problem or if it

takes days to solve a relatively simple problem or if it

requires more memory than what is available on that

requires more memory than what is available on that

computer.

computer.

There

are

techniques

developed

expressly

for

the

There

are

techniques

developed

expressly

for

the

representation of algorithms. We will discuss two of them in

representation of algorithms. We will discuss two of them in

this chapter: Pseudocoding and flowcharting.

this chapter: Pseudocoding and flowcharting.

Example of

Let's say that you have a friend arriving at the airport, and

Example of

Let's say that you have a friend arriving at the airport, and

Algorithm

your friend needs to get from the airport to your house. Here

Algorithm

your friend needs to get from the airport to your house. Here

are four different algorithms that you might give your friend

are four different algorithms that you might give your friend

for getting to your home:

for getting to your home:

The taxi algorithm:

The taxi algorithm:

1. Go to the taxi stand.

1. Go to the taxi stand.

2. Get in a taxi.

2. Get in a taxi.

3. Give the driver my address.

3. Give the driver my address.

The call-me algorithm:

The call-me algorithm:

1. When your plane arrives, call my cell phone.

1. When your plane arrives, call my cell phone.

2. Meet me outside baggage claim.

2. Meet me outside baggage claim.

Outcome 3: Programming Tools and Concepts

Outcome 3: Programming Tools and Concepts


3-3

3-3

Development of Algorithms
The rent-a-car algorithm:

Development of Algorithms
The rent-a-car algorithm:

1. Take the shuttle to the rental car place.

1. Take the shuttle to the rental car place.

2. Rent a car.

2. Rent a car.

3. Follow the directions to get to my house.

3. Follow the directions to get to my house.

The bus algorithm:

The bus algorithm:

1. Outside baggage claim, catch bus number 70.

1. Outside baggage claim, catch bus number 70.

2. Transfer to bus 14 on Main Street.

2. Transfer to bus 14 on Main Street.

3. Get off on Elm Street.

3. Get off on Elm Street.

4. Walk two blocks north to my house.

4. Walk two blocks north to my house.

All four of these algorithms accomplish exactly the same goal,

All four of these algorithms accomplish exactly the same goal,

but each algorithm does it in completely different way. Each

but each algorithm does it in completely different way. Each

algorithm also has a different cost and a different travel time.

algorithm also has a different cost and a different travel time.

Taking a taxi, for example, is probably the fastest way, but

Taking a taxi, for example, is probably the fastest way, but

also the most expensive. Taking the bus is definitely less

also the most expensive. Taking the bus is definitely less

expensive, but a whole lot slower. You choose the algorithm

expensive, but a whole lot slower. You choose the algorithm

based on the circumstances.

based on the circumstances.

Outcome 3: Programming Tools and Concepts

Outcome 3: Programming Tools and Concepts


3-4

3-4

Pseudocode
Introduction

Pseudocode
An outline of a program, written in a form that can easily be

Introduction

An outline of a program, written in a form that can easily be

converted into real programming statements. For example, the

converted into real programming statements. For example, the

pseudocode for a bubble sort routine might be written:

pseudocode for a bubble sort routine might be written:

while not at end of list

while not at end of list

compare adjacent elements

compare adjacent elements

if second is greater than first

if second is greater than first

switch them

switch them

get next two elements

get next two elements

if elements were switched

if elements were switched

repeat for entire list

repeat for entire list

Pseudocode cannot be compiled nor executed, and there are

Pseudocode cannot be compiled nor executed, and there are

no real formatting or syntax rules. It is simply one step - an

no real formatting or syntax rules. It is simply one step - an

important one - in producing the final code.

important one - in producing the final code.

The benefit of pseudocode is that it enables the programmer to

The benefit of pseudocode is that it enables the programmer to

concentrate on the algorithms without worrying about all the

concentrate on the algorithms without worrying about all the

syntactic details of a particular programming language. In

syntactic details of a particular programming language. In

fact, you can write pseudocode without even knowing what

fact, you can write pseudocode without even knowing what

programming

programming

language

you

will

use

for

the

final

implementation.

language

you

will

use

for

the

final

implementation.

A pseudocode is a semiformal, English-like language with


a limited vocabulary that can be used to design and
describe algorithms

Outcome 3: Programming Tools and Concepts

A pseudocode is a semiformal, English-like language with


a limited vocabulary that can be used to design and
describe algorithms

Outcome 3: Programming Tools and Concepts


3-5

3-5

Pseudocode
Usage of
Pseudocode

A pseudocode can be used in:


1. Designing algorithms

Pseudocode
Usage of
Pseudocode

A pseudocode can be used in:


1. Designing algorithms

2. Communicating algorithms to users

2. Communicating algorithms to users

3. Implementing algorithms as programs

3. Implementing algorithms as programs

4. Debugging logic errors in programs

4. Debugging logic errors in programs

5. Documenting programs for future maintenance and

5. Documenting programs for future maintenance and

expansion purposes.

expansion purposes.

In order to succeed in accomplishing its objectives, a

In order to succeed in accomplishing its objectives, a

pseudocode must

pseudocode must

1. Have a limited vocabulary

1. Have a limited vocabulary

2. Be easy to learn

2. Be easy to learn

3. Produce simple, English-like narrative notation

3. Produce simple, English-like narrative notation

4. Be capable of describing all algorithms, regardless of

4. Be capable of describing all algorithms, regardless of

their complexity

their complexity

In 1966, two researches, C. Bohm and G. Jacopini,

In 1966, two researches, C. Bohm and G. Jacopini,

demonstrated that any algorithm can be described using only

demonstrated that any algorithm can be described using only

three control structures: sequence, selection and repetition.

three control structures: sequence, selection and repetition.

Therefore, a pseudocode must have constructs that correspond

Therefore, a pseudocode must have constructs that correspond

to these control structures in its vocabulary. There are no

to these control structures in its vocabulary. There are no

universally accepted standards for pseudocodes.

universally accepted standards for pseudocodes.

The Sequential

The sequential control structure is a series of steps or

The Sequential

The sequential control structure is a series of steps or

Control Structure

statements that are executed in the order they are written in an

Control Structure

statements that are executed in the order they are written in an

algorithm.

algorithm.

Outcome 3: Programming Tools and Concepts

Outcome 3: Programming Tools and Concepts


3-6

3-6

Pseudocode

Pseudocode

Following is an example of a sequential control structure:

Following is an example of a sequential control structure:

Read taxable income


Read filing status
Computer income tax
Print income tax

Read taxable income


Read filing status
Computer income tax
Print income tax

The four statements in this pseudocode algorithm are executed

The four statements in this pseudocode algorithm are executed

one after another in the order they are written. Sequential

one after another in the order they are written. Sequential

structures are essentially built into computers. Unless we use

structures are essentially built into computers. Unless we use

other control structures, the computer executes all statements

other control structures, the computer executes all statements

in a program one after another.

in a program one after another.

You can also mark the beginning and end of a block of

You can also mark the beginning and end of a block of

statement in an algorithm. Example:

statement in an algorithm. Example:

Begin

Begin
Read taxable income
Read filing status
Computer income tax
Print income tax

Read taxable income


Read filing status
Computer income tax
Print income tax

End

End

The Selection

The selection control structure defines two courses of action

The Selection

The selection control structure defines two courses of action

Control Structure

depending on the outcome of a condition. A condition is an

Control Structure

depending on the outcome of a condition. A condition is an

expression that is either true or false.

expression that is either true or false.

The selection structure requires the use of keywords if and

The selection structure requires the use of keywords if and

else. Its format is given below:

else. Its format is given below:

If condition
Then part
Else
Else part
End if

Outcome 3: Programming Tools and Concepts

If condition
Then part
Else
Else part
End if

Outcome 3: Programming Tools and Concepts


3-7

3-7

Pseudocode

Pseudocode

The meaning of selection structure is as follows: if the value

The meaning of selection structure is as follows: if the value

computed for the condition is true, the statements that make

computed for the condition is true, the statements that make

up the then-part are executed. After this, the statement that

up the then-part are executed. After this, the statement that

follows the selection structure in the pseudocode will be

follows the selection structure in the pseudocode will be

considered.

considered.

If the condition evaluates to false, the then-part will be

If the condition evaluates to false, the then-part will be

bypassed, and the statements in the block called the else-part

bypassed, and the statements in the block called the else-part

will be executed. The then-part and the else-part can each be

will be executed. The then-part and the else-part can each be

single statements, or a series of statements.

single statements, or a series of statements.

Example:

Example:

if income is less than or equal to 82,150


begin
compute tax = 5100.00 + 0.28 x (income 34000.00)
print tax rate is 28%
end
else
begin
compute tax = 18582.00 + 0.31 x (income 82150.00)
print Tax rate is 31%
end
end if

if income is less than or equal to 82,150


begin
compute tax = 5100.00 + 0.28 x (income 34000.00)
print tax rate is 28%
end
else
begin
compute tax = 18582.00 + 0.31 x (income 82150.00)
print Tax rate is 31%
end
end if

print tax

print tax

In certain decision-making situations, the else-part may be

In certain decision-making situations, the else-part may be

missing, in this case, the format of the selection structure

missing, in this case, the format of the selection structure

becomes:

becomes:
if condition
then part
end if

if condition
then part
end if

This means that if the condition is true, the statements that

This means that if the condition is true, the statements that

make up the then-part are executed; otherwise, the statement

make up the then-part are executed; otherwise, the statement

that follows the selection statement will be considered.

that follows the selection statement will be considered.

Outcome 3: Programming Tools and Concepts

Outcome 3: Programming Tools and Concepts


3-8

3-8

Pseudocode

Pseudocode

Here is an example:

Here is an example:

if status is equal to 1
print Single
end if

if status is equal to 1
print Single
end if

The if-else selection structure is useful for two-way decision-

The if-else selection structure is useful for two-way decision-

making. In case we have more than two courses of action in

making. In case we have more than two courses of action in

an algorithm, we can use nested selection structures.

an algorithm, we can use nested selection structures.

Nested Selection

A nested selection structure is a basic selection structure that

Nested Selection

A nested selection structure is a basic selection structure that

Structure

contains other if-else structure in its then-part or else-part.

Structure

contains other if-else structure in its then-part or else-part.

Look at this example:

Look at this example:

if status is equal to 1
print Single
else
if status is equal to 2
print Married filing jointly
else
if status is equal to 3
print Married filing separately
else
print Error in status code
end if
end if
end if

if status is equal to 1
print Single
else
if status is equal to 2
print Married filing jointly
else
if status is equal to 3
print Married filing separately
else
print Error in status code
end if
end if
end if

Nested selection structures are useful for multi-way decision-

Nested selection structures are useful for multi-way decision-

making. However, they can get to be confusing for most

making. However, they can get to be confusing for most

programmers if they are in excess of three levels. You should

programmers if they are in excess of three levels. You should

exercise restraint in using them in your algorithm designs.

exercise restraint in using them in your algorithm designs.

The Repetition

The repetition control structure specifies a block of one or

The Repetition

The repetition control structure specifies a block of one or

Control Structure

more statements that are repeatedly executed until a condition

Control Structure

more statements that are repeatedly executed until a condition

is satisfied.

is satisfied.

Outcome 3: Programming Tools and Concepts

Outcome 3: Programming Tools and Concepts


3-9

3-9

Pseudocode

Pseudocode

This enables us to define loops, which are repeated execution

This enables us to define loops, which are repeated execution

of blocks of statements. There are several forms of repetition

of blocks of statements. There are several forms of repetition

control structures that can be used in algorithm design.

control structures that can be used in algorithm design.

The format of the while repetition structure is:

The format of the while repetition structure is:

while condition
loop-body
end while

while condition
loop-body
end while

Here, the loop-body is a single statement or a block of

Here, the loop-body is a single statement or a block of

statements that is executed as long as the condition written

statements that is executed as long as the condition written

after the keyword while is true. The keyword end_while

after the keyword while is true. The keyword end_while

indicates the end of the repetition structure. The repeated

indicates the end of the repetition structure. The repeated

execution of the loop-body terminates once the condition

execution of the loop-body terminates once the condition

becomes false. Obviously, there must be something in the

becomes false. Obviously, there must be something in the

loop-body that changes the component of the condition such

loop-body that changes the component of the condition such

that it eventually becomes false and the algorithm drops out of

that it eventually becomes false and the algorithm drops out of

the loop-body. Otherwise, we will have a perpetual loop and

the loop-body. Otherwise, we will have a perpetual loop and

the algorithm will never terminate.

the algorithm will never terminate.

An example of the while repetition structure is shown in the

An example of the while repetition structure is shown in the

following pseudocode:

following pseudocode:

set CorrectStatusInput to n

set CorrectStatusInput to n

while CorrectStatusInput is equal to n


begin
print Enter filing status: should be between 1 and 4:
read status
if status is greater than 0
if status is less than 5
set CorrectStatusInput to y
end if
end if
end
end_while

while CorrectStatusInput is equal to n


begin
print Enter filing status: should be between 1 and 4:
read status
if status is greater than 0
if status is less than 5
set CorrectStatusInput to y
end if
end if
end
end_while

Outcome 3: Programming Tools and Concepts


3-10

Outcome 3: Programming Tools and Concepts


3-10

Pseudocode

Pseudocode

Conventions for

While discussing the three basic control structures, we have

Conventions for

While discussing the three basic control structures, we have

Pseudocode

started a seed vocabulary for our pseudocode. So far, it

Pseudocode

started a seed vocabulary for our pseudocode. So far, it

consists of the keywords if, else, while, begin, end, end_if and

consists of the keywords if, else, while, begin, end, end_if and

end_while.

end_while.

Now, we are ready to summarize our pseudocoding

Now, we are ready to summarize our pseudocoding

conventions.

conventions.

1. Each pseudocode statement consists of keywords that

1. Each pseudocode statement consists of keywords that

describe operations and some appropriate, English-like

describe operations and some appropriate, English-like

descriptions of operands.

descriptions of operands.

2. Each statement should be written on a separate line. In

2. Each statement should be written on a separate line. In

case a statement requires more than one line, the

case a statement requires more than one line, the

continuation lines should be indented.

continuation lines should be indented.

3. The statements that make up a sequence control

3. The statements that make up a sequence control

structure should begin with unambiguous words, such

structure should begin with unambiguous words, such

as computer, initialize, set etc.

as computer, initialize, set etc.

4. For selection control structure, use an if-else

4. For selection control structure, use an if-else

statement. In an if-else statement, the then-part and, if

statement. In an if-else statement, the then-part and, if

used, the else-part should be indented. Terminate each

used, the else-part should be indented. Terminate each

if statement by the keyword end_if.

if statement by the keyword end_if.

5. For the repetition control structure, use the while

5. For the repetition control structure, use the while

statement and indent the loop-body. Terminate each

statement and indent the loop-body. Terminate each

while statement by the keyword end_while.

while statement by the keyword end_while.

6. All words in a pseudocode statement must be chosen

6. All words in a pseudocode statement must be chosen

to be unambiguous, and as easy as possible for

to be unambiguous, and as easy as possible for

nonprogrammers to understand.

nonprogrammers to understand.

Outcome 3: Programming Tools and Concepts


3-11

Outcome 3: Programming Tools and Concepts


3-11

Pseudocode

Pseudocode

7. Enclose comments lines between /* and */. A

7. Enclose comments lines between /* and */. A

comment is an explanation that clarifies some aspect

comment is an explanation that clarifies some aspect

of an algorithm.

of an algorithm.

Comments constitute an important element of software

Comments constitute an important element of software

documentation. However, in pseudocode descriptions of

documentation. However, in pseudocode descriptions of

algorithms, you are expected to make all statements clear.

algorithms, you are expected to make all statements clear.

Therefore, you should try to write your pseudocode

Therefore, you should try to write your pseudocode

statements such as no additional comments are necessary.

statements such as no additional comments are necessary.

Lets discuss the problem to create a pseudocode more in this

Lets discuss the problem to create a pseudocode more in this

example:

example:

Problem we are given a quadratic equation of the form

Problem we are given a quadratic equation of the form

where a, b, and c are constant coefficients. We would like to

where a, b, and c are constant coefficients. We would like to

develop a C program that solves as many quadratic equations

develop a C program that solves as many quadratic equations

as the user would like. We know that a quadratic equation has

as the user would like. We know that a quadratic equation has

two roots and that they can be computed using the following

two roots and that they can be computed using the following

formulas:

formulas:

Requirement Specification: Develop a program that does the

Requirement Specification: Develop a program that does the

following:

following:

Outcome 3: Programming Tools and Concepts


3-12

Outcome 3: Programming Tools and Concepts


3-12

Pseudocode

Pseudocode

1. Prompt the user to enter values for the coefficients a, b,

1. Prompt the user to enter values for the coefficients a, b,

and c, using the terminal keyboard.


2. Computes the discriminant of the quadratic equation using
the formula

and c, using the terminal keyboard.


2. Computes the discriminant of the quadratic equation using
the formula

3. Determines if the roots of the equations are real by

3. Determines if the roots of the equations are real by

comparing the discriminant to zero. If the discriminant is

comparing the discriminant to zero. If the discriminant is

less than zero, we know that the roots are complex. In this

less than zero, we know that the roots are complex. In this

case, we do not want to compute the roots but print a

case, we do not want to compute the roots but print a

message on the screen that informs the user that the roots

message on the screen that informs the user that the roots

are complex.

are complex.

4. However, if the discriminant is greater than or equal to

4. However, if the discriminant is greater than or equal to

zero, we have 2 roots to be computed using the formulas

zero, we have 2 roots to be computed using the formulas

given above. We would like the program to compute the

given above. We would like the program to compute the

roots and print them out on the screen.

roots and print them out on the screen.

5. After the quadratic equation is solved, the user should be

5. After the quadratic equation is solved, the user should be

able to continue with others, if any. The program should

able to continue with others, if any. The program should

ask the user if he or she would like to continue, and

ask the user if he or she would like to continue, and

prompt him or her to respond by typing yes or no. If the

prompt him or her to respond by typing yes or no. If the

user wishes to solve another equation, the above steps

user wishes to solve another equation, the above steps

should be repeated. Otherwise the program should

should be repeated. Otherwise the program should

terminate.

terminate.

Analysis:

Analysis:

Inputs: Values of the coefficients a, b and c for each

Inputs: Values of the coefficients a, b and c for each

equation.

equation.

Outputs: values of the roots root1 and root2, or a message

Outputs: values of the roots root1 and root2, or a message

informing, the roots are complex.

informing, the roots are complex.

Outcome 3: Programming Tools and Concepts


3-13

Outcome 3: Programming Tools and Concepts


3-13

Pseudocode

Pseudocode

Formula: The formulas given above for the computation of

Formula: The formulas given above for the computation of

root1 and root2.

root1 and root2.

Design: we start with an initial pseudocode:

Design: we start with an initial pseudocode:

while there are more equations to solve


begin
prompt user to enter values for a, b and c
read values entered
solve the quadratic equations
print roots for root1 and root2
ask user if there are more equations to solve
end
end_while

while there are more equations to solve


begin
prompt user to enter values for a, b and c
read values entered
solve the quadratic equations
print roots for root1 and root2
ask user if there are more equations to solve
end
end_while

Since this algorithm is not sufficiently detailed, it cannot

Since this algorithm is not sufficiently detailed, it cannot

presently be translated into a C program. There are 2 steps we

presently be translated into a C program. There are 2 steps we

need to refine. From:

need to refine. From:

prompt user to enter values for a, b and c


read values entered

To:

Print Enter value for a:


Read a
Print Enter value for b:
Read b
Print Enter value for c:
Read c

Outcome 3: Programming Tools and Concepts


3-14

prompt user to enter values for a, b and c


read values entered

To:

Print Enter value for a:


Read a
Print Enter value for b:
Read b
Print Enter value for c:
Read c

Outcome 3: Programming Tools and Concepts


3-14

Pseudocode
And from:

Pseudocode
And from:

Solve the quadratic equation and print roots root1 and root2

To:

Solve the quadratic equation and print roots root1 and root2

To:
if a is equal to zero

if a is equal to zero

print This is not a quadratic equation.


else
compute and print the roots of the quadratic equation
end_if

print This is not a quadratic equation.


else
compute and print the roots of the quadratic equation
end_if

So far so good? But how do we compute and print the roots of

So far so good? But how do we compute and print the roots of

the quadratic equation? This is how it should look like:

the quadratic equation? This is how it should look like:

if a is equal to zero

if a is equal to zero

print This is not a quadratic equation.


else
begin
compute discriminant = b x b 4 x a x c
compute denum = 2 x a

print This is not a quadratic equation.


else
begin
compute discriminant = b x b 4 x a x c
compute denum = 2 x a

if discriminant is less than zero


print The roots are complex
else
begin
compute root1=(- b sqrt(discriminant))/denum
compute root1=(- b + sqrt(discriminant))/denum
print root1, root2
end
end_if
end
end_if

if discriminant is less than zero


print The roots are complex
else
begin
compute root1=(- b sqrt(discriminant))/denum
compute root1=(- b + sqrt(discriminant))/denum
print root1, root2
end
end_if
end
end_if

In this pseudocode,

sqrt is a function that computes and

In this pseudocode,

sqrt is a function that computes and

returns the square root of a given number. We will discuss

returns the square root of a given number. We will discuss

functions in later module.

functions in later module.

Outcome 3: Programming Tools and Concepts


3-15

Outcome 3: Programming Tools and Concepts


3-15

Pseudocode

Pseudocode

The final step in the algorithm design is the refinement of the

The final step in the algorithm design is the refinement of the

while loop.

while loop.

while there are more equation to solve


begin

ask user if there are more equations to solve


end
end_while

while there are more equation to solve


begin

ask user if there are more equations to solve


end
end_while

For this, we use loop control variable called more, which is

For this, we use loop control variable called more, which is

initialized to y outside the while loop. In the loop body, after

initialized to y outside the while loop. In the loop body, after

an equation is solved, we prompt the user to type y if he or she

an equation is solved, we prompt the user to type y if he or she

wants to continue. Depending on what the user enters for

wants to continue. Depending on what the user enters for

more, the algorithm will either repeat or terminate. Following

more, the algorithm will either repeat or terminate. Following

are the refined pseudocode for the while loop:

are the refined pseudocode for the while loop:

Set more to y

Set more to y

while more is equal to y


begin

print Do you want to continue? Type y/n:


read more
end
end_while

while more is equal to y


begin

print Do you want to continue? Type y/n:


read more
end
end_while

Your Task:

Your Task:

Based on the example and our discussion previously, combine

Based on the example and our discussion previously, combine

all the pseducode to make it a final pseudocode.

all the pseducode to make it a final pseudocode.

Outcome 3: Programming Tools and Concepts


3-16

Outcome 3: Programming Tools and Concepts


3-16

Flow Charting
Flow Chart

Flow Charting
A flowchart traces the flow of logic in a program and is very

Flow Chart

A flowchart traces the flow of logic in a program and is very

useful in finding logic errors in larger programs.

useful in finding logic errors in larger programs.

The logic always flows in the direction of the arrows, which

The logic always flows in the direction of the arrows, which

are very important to include in the flow chart. Notice that

are very important to include in the flow chart. Notice that

the arrows do not always proceed in a sequential manner.

the arrows do not always proceed in a sequential manner.

When an arrow points side-ways or upward, a decision and/or

When an arrow points side-ways or upward, a decision and/or

iteration are occurring. You can check the logic of an

iteration are occurring. You can check the logic of an

algorithm simply by following the arrows. If arrows collide,

algorithm simply by following the arrows. If arrows collide,

with each other an error has occurred. By colliding we mean

with each other an error has occurred. By colliding we mean

arrows pointing into each other with no other direction to

arrows pointing into each other with no other direction to

take.

take.

A flowchart is a graph consisting of geometrical


shapes that are connected by flow lines

Outcome 3: Programming Tools and Concepts


3-17

A flowchart is a graph consisting of geometrical


shapes that are connected by flow lines

Outcome 3: Programming Tools and Concepts


3-17

Flow Charting

Flow Charting

In order to use flowcharts to communicate algorithms, we

In order to use flowcharts to communicate algorithms, we

must develop some conventions for its symbols. They are

must develop some conventions for its symbols. They are

shown in the next table. The basic flowchart symbols are the

shown in the next table. The basic flowchart symbols are the

terminal, process, input-output, and selection symbols.

terminal, process, input-output, and selection symbols.

1. Terminal symbol is oval in shape. They indicate the

1. Terminal symbol is oval in shape. They indicate the

beginning and end points of an algorithm. The

beginning and end points of an algorithm. The

beginning point oval should have Begin type in it; the

beginning point oval should have Begin type in it; the

end point oval should contain End. There should be

end point oval should contain End. There should be

no more than 2 terminal symbols in a flowchart for an

no more than 2 terminal symbols in a flowchart for an

algorithm.

algorithm.

2. Process symbol is rectangular in shape. They represent

2. Process symbol is rectangular in shape. They represent

operations such as computations, assignments and

operations such as computations, assignments and

initializations.

initializations.

3. Input-output symbol is parallelogram. Each symbol

3. Input-output symbol is parallelogram. Each symbol

should contain the keyword read or write, and what to

should contain the keyword read or write, and what to

be read or written.

be read or written.

4. 2-way selection symbol is a diamond-shaped box. It

4. 2-way selection symbol is a diamond-shaped box. It

stands for the keyword if in pseudocode. The if

stands for the keyword if in pseudocode. The if

condition should be written inside the selection

condition should be written inside the selection

symbol.

symbol.

Outcome 3: Programming Tools and Concepts


3-18

Outcome 3: Programming Tools and Concepts


3-18

Flow Charting

Flow Charting

In addition to these basic symbols, there are other symbols for

In addition to these basic symbols, there are other symbols for

disk storage input-output, printer output, and off-page and on-

disk storage input-output, printer output, and off-page and on-

page connectors as shown in previous table. They are used in

page connectors as shown in previous table. They are used in

algorithms in which input-output device types have to be

algorithms in which input-output device types have to be

specified on in large or detail flowcharts.

specified on in large or detail flowcharts.

The sequence, selection, and repetition control structures

The sequence, selection, and repetition control structures

essential for algorithm design can be represented in

essential for algorithm design can be represented in

flowcharts, which will be shown later.

flowcharts, which will be shown later.

Outcome 3: Programming Tools and Concepts


3-19

Outcome 3: Programming Tools and Concepts


3-19

Flow Charting

Flow Charting

SEQUENTIAL STRUCTURE
Pseudocode
Statement 1
Statement2
..

Statement n

SEQUENTIAL STRUCTURE

Flowchart
Statement 1

Statement 2

...

Statement n

Pseudocode
Statement 1
Statement2
..

Statement n

SELECTION STRUCTURE
Pseudocode

Flowchart

false

if condition
then-part
end if

condi
tion

true

Flowchart

false
Else part

Outcome 3: Programming Tools and Concepts


3-20

condi
tion

Statement 2

Flowchart

false

if condition
then-part
end if

then part

condi
tion

true
then part

SELECTION STRUCTURE
Pseudocode

true

...

SELECTION STRUCTURE

SELECTION STRUCTURE

if condition
then-part
else
else-part
end if

Statement 1

Pseudocode

then part

Pseudocode

Flowchart

if condition
then-part
else
else-part
end if

Flowchart

false
Else part

Outcome 3: Programming Tools and Concepts


3-20

condi
tion

true
then part

Statement n

Flow Charting

Flow Charting

REPETITION STRUCTURE
Pseudocode

REPETITION STRUCTURE

Flowchart

While condition
Loop body
End_while

true

conditio
n

Pseudocode

Flowchart

While condition
Loop body
End_while

Loop body

true

conditio
n

false

Loop body

false

Although, like pseudocoding, flowcharting is useful for

Although, like pseudocoding, flowcharting is useful for

algorithm

algorithm

design

disadvantage

and

compared

representation,
to

it

pseudocoding.

has
For

certain
large

design

disadvantage

and

compared

representation,
to

it

pseudocoding.

has
For

certain
large

algorithms, flowcharts tend to become excessively large. As a

algorithms, flowcharts tend to become excessively large. As a

result, it becomes quite difficult to read and understand the

result, it becomes quite difficult to read and understand the

algorithm. Also drawing detailed flowcharts for large

algorithm. Also drawing detailed flowcharts for large

algorithms is tedious and time-consuming.

algorithms is tedious and time-consuming.

Outcome 3: Programming Tools and Concepts


3-21

Outcome 3: Programming Tools and Concepts


3-21

Flow Charting

Flow Charting

Example Quadratic Solutions

Example Quadratic Solutions

START

START

Prompt
user to
enter value
a,b and c

Prompt
user to
enter value
a,b and c

Read values
entered

Read values
entered

Print This
is not a
quadratic
equation

Yes

If a is equal to
zero

No

Computer the
roots of the
quadratic equation

Print This
is not a
quadratic
equation

Yes

If a is equal to
zero

Print the
final result

No

Computer the
roots of the
quadratic equation

Print the
final result

END

END

Outcome 3: Programming Tools and Concepts


3-22

Outcome 3: Programming Tools and Concepts


3-22

Flow Charting

Flow Charting

Tax Computation

Tax Computation

START

START

Set IncomeInput
to n

Set IncomeInput
to n

If IncomeInput equal
to n

true

Print enter
taxable income;
should be less
than 50000

If IncomeInput equal
to n

true

Read
income

false

Income
>=50000

Read
income

false

true

Outcome 3: Programming Tools and Concepts


3-23

Income
>=50000
true

Set incomeinput to
y
false

END

Print enter
taxable income;
should be less
than 50000

Set incomeinput to
y
false

END

Outcome 3: Programming Tools and Concepts


3-23

Summary
At a glance

Summary

In this chapter, we introduced the concept of problem

At a glance

In this chapter, we introduced the concept of problem

solving the process of transforming the description of a

solving the process of transforming the description of a

problem to its solution. To solve complex problems, we

problem to its solution. To solve complex problems, we

use computers as a tool and develop computer programs

use computers as a tool and develop computer programs

that give use solutions.

that give use solutions.

An algorithm is sequence of a finite number of steps

An algorithm is sequence of a finite number of steps

arranged in a specific logical order that, when executed,

arranged in a specific logical order that, when executed,

produces the solution for a problem. An algorithm design

produces the solution for a problem. An algorithm design

should be put on paper. For this purpose, and also to

should be put on paper. For this purpose, and also to

facilitate its development, we resort to pseudocoding. A

facilitate its development, we resort to pseudocoding. A

pseudocode is a semiformal, English-like language with a

pseudocode is a semiformal, English-like language with a

limited vocabulary that can be used to design and

limited vocabulary that can be used to design and

representation is equivalent to pseudocoding and can be

representation is equivalent to pseudocoding and can be

used as an alternative to it.

used as an alternative to it.

Any algorithm can be described in terms of three basic

Any algorithm can be described in terms of three basic

control structures. They are the sequence, selection, and

control structures. They are the sequence, selection, and

repetition structures.

repetition structures.

In this chapter, we have enhanced our skills in problem

In this chapter, we have enhanced our skills in problem

solving, based on problem statement. Next, we will focus

solving, based on problem statement. Next, we will focus

more on C statement types that can be used in

more on C statement types that can be used in

implementing the sequence, selection and repetition

implementing the sequence, selection and repetition

control structures in algorithms.

control structures in algorithms.

Outcome 3: Programming Tools and Concepts


3-24

Outcome 3: Programming Tools and Concepts


3-24

Outcome 4

Outcome 4

Variables, Operators and

Variables, Operators and

Fundamental of Input and

Fundamental of Input and

Output

Output

Introduction and Objectives

Introduction and Objectives

Chapter

In this chapter, you will learn about:

Chapter

In this chapter, you will learn about:

Objectives

Programming Concepts

Objectives

Programming Concepts

The Structure of C Program

The Structure of C Program

o Processor Directives

o Processor Directives

o Include Directive

o Include Directive

o Data types and declaration

o Data types and declaration

o Name Constant

o Name Constant

Statements

Statements

First Look At Function

First Look At Function

Introduction to MS Visual C/C++ 6.0

Introduction to MS Visual C/C++ 6.0

Operators

Operators

o Assignment operators

o Assignment operators

o Arithmetic operators

o Arithmetic operators

o Relational and Logical operators

o Relational and Logical operators

Outcome 4: Variables, operators and Fundamental of input and output


4-1

Outcome 4: Variables, operators and Fundamental of input and output


4-1

Programming Concepts

Programming Concepts

Definition of

Programming is a process of reducing a problem into small

Definition of

Programming is a process of reducing a problem into small

Programming

steps that the computer can understand.

Programming

steps that the computer can understand.

In summary,

In summary,

A program is a list of detailed instructions

The Programming

Determine the objective(s) of the program.

Process

Determine the methods you want to use in writing the

A program is a list of detailed instructions

The Programming

Determine the objective(s) of the program.

Process

Determine the methods you want to use in writing the

program.

program.

Create the program to solve the problem.

Create the program to solve the problem.

Run the program to see the results

Run the program to see the results

Determine the objective(s) of the program.

Determine the objective(s) of the program.

Determine the methods

Determine the methods

Outcome 4: Variables, operators and Fundamental of input and output


4-2

Outcome 4: Variables, operators and Fundamental of input and output


4-2

Programming Concepts

Programming Concepts

Create the program

Create the program

Translates the design of the flow of program into step-by-

Translates the design of the flow of program into step-by-

step detailed instructions that computer understands, which

step detailed instructions that computer understands, which

is sometimes called coding.

is sometimes called coding.

Run the program

Run the program

The programmer then tests the program thoroughly to obtain

The programmer then tests the program thoroughly to obtain

the desired

the desired

Program

Program

Development

Development

Cycle

Cycle

Step 1: Create the source code

Step 1: Create the source code

The first step in Program Development Cycle is to enter

The first step in Program Development Cycle is to enter

source code into an editor.

source code into an editor.

Source code is a series of statements or commands that are

Source code is a series of statements or commands that are

used to instruct the computer to perform desired tasks.

used to instruct the computer to perform desired tasks.

A program is also known as source code

A program is also known as source code

Example of C source code:

Example of C source code:

Outcome 4: Variables, operators and Fundamental of input and output


4-3

Outcome 4: Variables, operators and Fundamental of input and output


4-3

Programming Concepts

Programming Concepts

Step 2: Compile the source code

Step 2: Compile the source code

The second step in Program Development Cycle is to


compile source code to machine code.

The compiler takes source code file as input and

compile source code to machine code.

The compiler takes source code file as input and

produces a disk file containing the machine language

produces a disk file containing the machine language

instructions that correspond to source code statements.

instructions that correspond to source code statements.

Compiler is a program that translates source code to

machine language.

The second step in Program Development Cycle is to

The machine language instructions created by compiler

Compiler is a program that translates source code to


machine language.

The machine language instructions created by compiler

are called object code, and the disk file containing them

are called object code, and the disk file containing them

is called an object file.

is called an object file.

In C, the compiler creates object files with an extension


of .OBJ.

In C, the compiler creates object files with an extension


of .OBJ.

Step 3:Linking to Create an Executable File

Step 3:Linking to Create an Executable File

What is a Library File?

What is a Library File?

A library file contains C codes that has already been

A library file contains C codes that has already been

written and is supplied in a ready-to-use form with the

written and is supplied in a ready-to-use form with the

compiler package.

compiler package.

In linking process, the object file produced during source

In linking process, the object file produced during source

code compilation is combined with object code from the

code compilation is combined with object code from the

function library to create the final executable program.

function library to create the final executable program.

Library File contains object code that has already been

Library File contains object code that has already been

written and is supplied in a ready-to-use form with your

written and is supplied in a ready-to-use form with your

compiler package.

compiler package.

Outcome 4: Variables, operators and Fundamental of input and output


4-4

Outcome 4: Variables, operators and Fundamental of input and output


4-4

Programming Concepts

Programming Concepts

A Brief History of

C language was created by Dennis Ritchie at Bell

A Brief History of

C language was created by Dennis Ritchie at Bell

C language

Telephone Laboratories in 1972.

C language

Telephone Laboratories in 1972.

Advantages of C

The development of C language is to design UNIX

The development of C language is to design UNIX

operating system (which is used on mainframe computers).

operating system (which is used on mainframe computers).

Readability

Advantages of C

Readability

Programs are easy to read.

Programs are easy to read.

Close to human languages, especially English.

Close to human languages, especially English.

C is a language of few words, containing only a handful

C is a language of few words, containing only a handful

of terms, called keywords, which serve as the base on

of terms, called keywords, which serve as the base on

which the language's functionality is built.

which the language's functionality is built.

Maintainability

Maintainability

Programs are easy to maintain.

Programs are easy to maintain.

Programs written in C can be reused. You can save your

Programs written in C can be reused. You can save your

C programs into a library file and invoke them in your

C programs into a library file and invoke them in your

next programming project simply by including the

next programming project simply by including the

library file.

library file.

Portability

Portability

Programs are easy to port across different computer


platforms.

It means that a C program written for one computer

Programs are easy to port across different computer


platforms.

It means that a C program written for one computer

system (an IBM PC, for example) can be compiled and

system (an IBM PC, for example) can be compiled and

run on another system (a DEC VAX system, perhaps)

run on another system (a DEC VAX system, perhaps)

with little or no modification.

with little or no modification.

Outcome 4: Variables, operators and Fundamental of input and output


4-5

Outcome 4: Variables, operators and Fundamental of input and output


4-5

Programming Concepts

Programming Concepts

Lowest high-level programming language

Lowest high-level programming language

C is the lowest high-level programming language

C is the lowest high-level programming language

because it is able to control computer hardware and

because it is able to control computer hardware and

peripherals easily.

peripherals easily.

C language softwareWe are going to use MS Visual

C language softwareWe are going to use MS Visual

C/C++ v6.0 for this module.

C/C++ v6.0 for this module.

Structure of C

Structure of C

Outcome 4: Variables, operators and Fundamental of input and output


4-6

Outcome 4: Variables, operators and Fundamental of input and output


4-6

The Structure of C Program

The Structure of C Program

Now, we have studied the basic language elements, the

Now, we have studied the basic language elements, the

character set, we will examine higher-level language

character set, we will examine higher-level language

constructs from a structural point of view. In general, a C

constructs from a structural point of view. In general, a C

program consists of following components:

program consists of following components:

1.

Program comments

1.

Program comments

2.

Preprocessor directives

2.

Preprocessor directives

3.

Type declarations

3.

Type declarations

4.

Named constant

4.

Named constant

5.

Statements

5.

Statements

6.

Function declarations (prototypes)

6.

Function declarations (prototypes)

7.

Function definitions

7.

Function definitions

8.

Function calls

8.

Function calls

Program

Comments are explanations or annotations that are included

Program

Comments are explanations or annotations that are included

Comments

in a program for documentation and clarification purposes.

Comments

in a program for documentation and clarification purposes.

Program comments are used to describe the purpose of a

Program comments are used to describe the purpose of a

program, function or statement.

program, function or statement.

Rules for Program Comments

Rules for Program Comments

1. The characters /* start a comment. A comment that

1. The characters /* start a comment. A comment that

starts with /* should be terminated by the characters */

starts with /* should be terminated by the characters */

2. /* comments cannot be nested

2. /* comments cannot be nested

3. The characters // also start a comments. Such

3. The characters // also start a comments. Such

comment terminates at the end of the line.

Outcome 4: Variables, operators and Fundamental of input and output


4-7

comment terminates at the end of the line.

Outcome 4: Variables, operators and Fundamental of input and output


4-7

The Structure of a C Program

The Structure of a C Program

Some examples of comments are given below:

Some examples of comments are given below:

// Preprocessor directives:

// Preprocessor directives:

/* Purpose: Calculates city tax of gross income */

/* Purpose: Calculates city tax of gross income */

Following are some style considerations concerning the use

Following are some style considerations concerning the use

program comments

program comments

1. Comments are valuable for enhancing the readability of

1. Comments are valuable for enhancing the readability of

a program. They should be meaningful, clear, relevant

a program. They should be meaningful, clear, relevant

and up-to-date.

and up-to-date.

2. Comments should not be redundant. If something is

2. Comments should not be redundant. If something is

clearly stated in the program, it should not be repeated

clearly stated in the program, it should not be repeated

in a comment. The following comment is redundant:

in a comment. The following comment is redundant:

/* Compute city tax as City Tax times the gross income */


city_tax = CITY_TAX_RATE * gross_income;

/* Compute city tax as City Tax times the gross income */


city_tax = CITY_TAX_RATE * gross_income;

3. Comments should be distinct and visually separated

3. Comments should be distinct and visually separated

from the program code. It is good to practice to

from the program code. It is good to practice to

highlight comment lines by using blank lines before and

highlight comment lines by using blank lines before and

after them.

after them.

Preprocessor

A preprocessor directive (also called a compiler directive)

Preprocessor

A preprocessor directive (also called a compiler directive)

Directives

is an instruction to the preprocessor. The preprocessor is

Directives

is an instruction to the preprocessor. The preprocessor is

part of the C compiler. It can perform three functions:

part of the C compiler. It can perform three functions:

1.

Inclusion of named files in a source program

1.

Inclusion of named files in a source program

2.

Conditional compilation

2.

Conditional compilation

3.

Macro substitution

3.

Macro substitution

Only name file inclusion will be discuss in this subject, as

Only name file inclusion will be discuss in this subject, as

its important.

its important.

Outcome 4: Variables, operators and Fundamental of input and output


4-8

Outcome 4: Variables, operators and Fundamental of input and output


4-8

The Structure of a C Program


Include Directive

The #include directive instructs the C compiler to add the

The Structure of a C Program


Include Directive

The #include directive instructs the C compiler to add the

contents of an include file into the program during

contents of an include file into the program during

compilation. Include files should all have an .H extension

compilation. Include files should all have an .H extension

(for example, STDIO.H).

(for example, STDIO.H).

We have the standard header file stdio.h, which contains the

We have the standard header file stdio.h, which contains the

declaration of the basic C input-output routines. When the

declaration of the basic C input-output routines. When the

compiler encounters this directive, it combines the content

compiler encounters this directive, it combines the content

of the header file stdio.h and the source program code and

of the header file stdio.h and the source program code and

proceeds with compilation.

proceeds with compilation.

Example useful code included in stdio.h such as

Example useful code included in stdio.h such as

printf()

Writes output to standard output stream

printf()

Writes output to standard output stream

scanf()

Reads input from the standard input stream

scanf()

Reads input from the standard input stream

Essentially, the #include directive is a text manipulation

Essentially, the #include directive is a text manipulation

facility. It causes a header file to be copied into the code and

facility. It causes a header file to be copied into the code and

compiled together with the rest of the program. There are

compiled together with the rest of the program. There are

many useful standard C header files.

many useful standard C header files.

Mathematical Functions (math.h)

Mathematical Functions (math.h)

sqrt()

Return the square root of x where x is radian

sqrt()

Return the square root of x where x is radian

exp()

Return the exponential of x with the base e

exp()

Return the exponential of x with the base e

where e is 2.718282

where e is 2.718282

General Utilities (stdlib.h)


rand()

abort()

Return a random number in range

General Utilities (stdlib.h)


0 to

rand()

Return a random number in range

0 to

RAND_MAX, where RAND_MAX is a

RAND_MAX, where RAND_MAX is a

symbolic constant that must be at least 32767

symbolic constant that must be at least 32767

Result in abnormal program termination and


returns control on the environment

Outcome 4: Variables, operators and Fundamental of input and output


4-9

abort()

Result in abnormal program termination and


returns control on the environment

Outcome 4: Variables, operators and Fundamental of input and output


4-9

The Structure of a C Program


exit()
Data Types and

exit()

Return normal program termination

void main()

Declarations

The Structure of a C Program

Data Types and

void main()

Declarations

Return normal program termination

double gross_income
double city_tax

double gross_income
double city_tax

These are type declaration of variables, telling the compiler

These are type declaration of variables, telling the compiler

that the program variables are floating-point variables. The

that the program variables are floating-point variables. The

type that a variable has determines some very significant

type that a variable has determines some very significant

characteristics about it. These characteristics include:

characteristics about it. These characteristics include:

1.

How it is stored internally

1.

How it is stored internally

2.

What operations can be applied to it

2.

What operations can be applied to it

3.

How such operations are interpreted

3.

How such operations are interpreted

We define data types as follows:

We define data types as follows:

A data type is a set of data values and a set of operations on

A data type is a set of data values and a set of operations on

those values.

those values.

In C languages, built in data types are classified as follows:

In C languages, built in data types are classified as follows:

1.

Fundamental data types

1.

Fundamental data types

2.

Derived data types

2.

Derived data types

A fundamental data type corresponds to the most common,

A fundamental data type corresponds to the most common,

fundamental storage units of a computer and the most

fundamental storage units of a computer and the most

common, fundamental ways of using such data.

common, fundamental ways of using such data.

There are 3 classes of fundamental data types in C:

There are 3 classes of fundamental data types in C:

1. int

1. int

Used to declare numeric program variables of integer

Used to declare numeric program variables of integer

type. It can only store positive and negative integers in

type. It can only store positive and negative integers in

the range of -32,768 through 32,767

the range of -32,768 through 32,767

Outcome 4: Variables, operators and Fundamental of input and output


4-10

Outcome 4: Variables, operators and Fundamental of input and output


4-10

The Structure of a C Program

The Structure of a C Program

We can use signed, unsigned or plain integer values as

We can use signed, unsigned or plain integer values as

follows:

follows:
signed int index = 41982;

signed int index = 41982;

signed int temperature = -32;

signed int temperature = -32;

unsigned int count = 0;

unsigned int count = 0;

int height = 100;

int height = 100;

int balance = -67;

int balance = -67;

Signed integers can hold positive or negative values, and

Signed integers can hold positive or negative values, and

unsigned integers can hold only positive values.

unsigned integers can hold only positive values.

However, plain integer can always hold positive or

However, plain integer can always hold positive or

negative values, they're always signed.

negative values, they're always signed.

Integer values come in three sizes, plain int, short int

Integer values come in three sizes, plain int, short int

and long int.

and long int.

int normal = 1000;

int normal = 1000;

short int smallValue = 100;

short int smallValue = 100;

long int bigValue = 10000;

long int bigValue = 10000;

2. char

2. char

Used to declare character variables. A character variable

Used to declare character variables. A character variable

stores any printable or non-printable character in the

stores any printable or non-printable character in the

computers. Such characters are represented in one byte

computers. Such characters are represented in one byte

(8 bits) of the computers memory.

(8 bits) of the computers memory.

3. float

3. float

Floating point types can contain decimal numbers, for

Floating point types can contain decimal numbers, for

example 1.23, -.087. There are three sizes, float (single-

example 1.23, -.087. There are three sizes, float (single-

precision), double (double-precision) and long double

precision), double (double-precision) and long double

(extended-precision). Some examples:

(extended-precision). Some examples:

float celsius = 37.623;

float celsius = 37.623;

double fahrenheit = 98.415;

double fahrenheit = 98.415;

long double accountBalance = 1897.23;

long double accountBalance = 1897.23;

Outcome 4: Variables, operators and Fundamental of input and output


4-11

Outcome 4: Variables, operators and Fundamental of input and output


4-11

The Structure of a C Program


Name Constant

Another component that we may encounter in a C program

The Structure of a C Program


Name Constant

Another component that we may encounter in a C program

is a name constant. A name constant is an identifier whose

is a name constant. A name constant is an identifier whose

values is fixed and does not change during the execution of

values is fixed and does not change during the execution of

a program which it appears.

a program which it appears.

In C, the declaration of a named constant begins with the

In C, the declaration of a named constant begins with the

keywords const, continues with a type specifier for the

keywords const, continues with a type specifier for the

constant. Once an identifier is defined as a named constant,

constant. Once an identifier is defined as a named constant,

its value cannot be changed. For example, an attempt to

its value cannot be changed. For example, an attempt to

reinitialize CITY_TAX_RATE using a statement such as:

reinitialize CITY_TAX_RATE using a statement such as:

const CITY_TAX_RATE = 0.0175

const CITY_TAX_RATE = 0.0175

For the above example, an attempt to reinitialize

For the above example, an attempt to reinitialize

CITY_TAX_RATE using a statement such as:

CITY_TAX_RATE using a statement such as:

CITY_TAX_RATE = 0.0185

CITY_TAX_RATE = 0.0185

will result an error.

will result an error.

After define a named constant in a program, we can use the

After define a named constant in a program, we can use the

corresponding identifier in any statement in the rest of the

corresponding identifier in any statement in the rest of the

code. We can write equivalently

code. We can write equivalently

city_tax = CITY_TAX_RATE * gross_income

city_tax = CITY_TAX_RATE * gross_income

Outcome 4: Variables, operators and Fundamental of input and output


4-12

Outcome 4: Variables, operators and Fundamental of input and output


4-12

Statements

Statements
A statement is a specification of an action to be taken by the

A statement is a specification of an action to be taken by the

computer as program executes.

computer as program executes.

Every statement in C, if correct, does what it is expected to

Every statement in C, if correct, does what it is expected to

do and then passes the program control to the next statement

do and then passes the program control to the next statement

in the program.

in the program.

Compound

A compound statement (also called a block) is a list of

Compound

A compound statement (also called a block) is a list of

Statements

statements enclosed in braces { }.

Statements

statements enclosed in braces { }.

{
Statement;
Statement;
{
Statement;
Statement;
}

Statement;
Statement;
{
Statement;
Statement;
}
}

You should note that, although all C statements must end

You should note that, although all C statements must end

with semicolons, a compound statement does not need the

with semicolons, a compound statement does not need the

semicolon after the right brace, }.

semicolon after the right brace, }.

Outcome 4: Variables, operators and Fundamental of input and output


4-13

Outcome 4: Variables, operators and Fundamental of input and output


4-13

A First Look at Function


Function Heading

The main( ) function consists of the name main

A First Look at Function


Function Heading

followed by a pair of empty parentheses, ( ) and a pair

followed by a pair of empty parentheses, ( ) and a pair

of braces, {}.

of braces, {}.

Within the braces are statements that make up the main

body of the program.

The main( ) function consists of the name main

Program execution starts at the first statement in main( )


and terminates at the last statement in main( ).

Within the braces are statements that make up the main


body of the program.

Program execution starts at the first statement in main( )


and terminates at the last statement in main( ).

The simplest function is the function main. The definition of

The simplest function is the function main. The definition of

the function main consists of

the function main consists of

1. A type specifier

1. A type specifier

2. The keyword main

2. The keyword main

3. A null argument list ()

3. A null argument list ()

4. A compound statement

4. A compound statement

And look like this:

And look like this:

Type specifier main()


{
Statement;
Statement;
{
Statement;
Statement;
}
}

Type specifier main()


{
Statement;
Statement;
{
Statement;
Statement;
}
}

The function main is of type void: it does many things, but

The function main is of type void: it does many things, but

it does not return a value. Each C program must have one

it does not return a value. Each C program must have one

main function. The function main in a program marks the

main function. The function main in a program marks the

entry point of the program.

entry point of the program.

Outcome 4: Variables, operators and Fundamental of input and output


4-14

Outcome 4: Variables, operators and Fundamental of input and output


4-14

A First Look at Function


End

Place a command, getch ( ) before the last braces of

A First Look at Function


End

the program.

The purpose of getch ( ) is to ensure that the program

Place a command, getch ( ) before the last braces of


the program.

The purpose of getch ( ) is to ensure that the program

will pause at the output mode (DOS base) until we press

will pause at the output mode (DOS base) until we press

any key to return to the source code.

any key to return to the source code.

Outcome 4: Variables, operators and Fundamental of input and output


4-15

Outcome 4: Variables, operators and Fundamental of input and output


4-15

Introduction to MS Visual C/C++ 6.0


MS Visual

Source Code Editor

C/C++ 6.0

Main Menu

Windows

Introduction to MS Visual C/C++ 6.0


MS Visual

Source Code Editor

C/C++ 6.0

Main Menu

Windows

o File

o File

o Edit

o Edit

o Search

o Search

o Run

o Run

o Compile

o Compile

o Debug

o Debug

o Project

o Project

o Option

o Option

o Window

o Window

o Help

o Help

Message window

Message window

Source Code

Source code editor is similar as the text window in Microsoft

Source Code

Source code editor is similar as the text window in Microsoft

Editor

Word. The programmer types all the programming languages

Editor

Word. The programmer types all the programming languages

in this editor.
Message Window

Message window is used to display all the errors during the

in this editor.
Message Window

compilation of the source code.


Variables

A variable is a named data storage location in your

Message window is used to display all the errors during the


compilation of the source code.

Variables

computer's memory.

A variable is a named data storage location in your


computer's memory.

Variable

A variable declaration has the following form:

Variable

A variable declaration has the following form:

Declarations

variable type varname ;

Declarations

variable type varname ;

int count, number, start;

int count, number, start;

float percent, total;

float percent, total;

Outcome 4: Variables, operators and Fundamental of input and output


4-16

Outcome 4: Variables, operators and Fundamental of input and output


4-16

Introduction to MS Visual C/C++ 6.0


Variable Names

The name can contain letters, digits, and the underscore

Introduction to MS Visual C/C++ 6.0


Variable Names

character (_).

The name can contain letters, digits, and the underscore


character (_).

The first character of the name must be a letter. The

The first character of the name must be a letter. The

underscore is also a legal first character, but its use is not

underscore is also a legal first character, but its use is not

recommended.

recommended.

Case matters (that is, upper- and lowercase letters). Thus,

Case matters (that is, upper- and lowercase letters). Thus,

the names count and Count refer to two different

the names count and Count refer to two different

variables.

variables.

C keywords(refer to Appendix A) can't be used as

C keywords(refer to Appendix A) can't be used as

variable names. A keyword is a word that is part of the C

variable names. A keyword is a word that is part of the C

language.

language.

Example
Variable Name

Example
Legality

Variable Name

Legality

Percent

Legal

Percent

Legal

y2x5__fg7h

Legal

y2x5__fg7h

Legal

annual_profit

Legal

annual_profit

Legal

_1990_tax

Legal but not advised

_1990_tax

Legal but not advised

savings#account

Illegal: The illegal character #

savings#account

Illegal: The illegal character #

double

Illegal: Is a C keyword

double

Illegal: Is a C keyword

9winter

Illegal: First character is a digit

9winter

Illegal: First character is a digit

Numeric

Numeric

Variable Types

Variable Types

Outcome 4: Variables, operators and Fundamental of input and output


4-17

Outcome 4: Variables, operators and Fundamental of input and output


4-17

Introduction to MS Visual C/C++ 6.0

Introduction to MS Visual C/C++ 6.0

Fundamentals of

Display information on-screen with printf( ) library function.

Fundamentals of

Display information on-screen with printf( ) library function.

Input and

Read data from the keyboard with scanf( ) library function

Input and

Read data from the keyboard with scanf( ) library function

Output

scanf( )

Output

The most flexible way for a program to read numeric

scanf( )

The most flexible way for a program to read numeric

data from the keyboard is by using the scanf( ) library

data from the keyboard is by using the scanf( ) library

function.

function.

The scanf( ) function reads data from the keyboard

The scanf( ) function reads data from the keyboard

according to a specified format and assigns the input

according to a specified format and assigns the input

data to one or more program variables.

data to one or more program variables.

The format of scanf command is

The format of scanf command is

The whole command means the integer number received from

The whole command means the integer number received from

the keyboard is located in a variable called number1.

the keyboard is located in a variable called number1.

Refer to Appendix 4-1

Refer to Appendix 4-1

Outcome 4: Variables, operators and Fundamental of input and output


4-18

Outcome 4: Variables, operators and Fundamental of input and output


4-18

Introduction to MS Visual C/C++ 6.0

Introduction to MS Visual C/C++ 6.0

Conversion

Conversion

Specifier

Specifier

REMEMBER...

REMEMBER...

Ensure that the conversion specifier used matches the variable

Ensure that the conversion specifier used matches the variable

declaration.

declaration.

int num1;

int num1;

printf(Please enter number:);


scanf(%c, &num1);

printf(Please enter number:);


scanf(%c, &num1);

SOMETIMES, the compiler WILL NOT prompt an

error message even though there is a mismatch.

SOMETIMES, the compiler WILL NOT prompt an


error message even though there is a mismatch.

Do not place an escape sequence within the double quote for

Do not place an escape sequence within the double quote for

scanf command.

scanf command.

int num1;

int num1;

printf(Please enter number:);


scanf(%d\n, &num1);

printf(Please enter number:);


scanf(%d\n, &num1);

The compiler WILL NOT prompt an error message if


you do so.

Outcome 4: Variables, operators and Fundamental of input and output


4-19

The compiler WILL NOT prompt an error message if


you do so.

Outcome 4: Variables, operators and Fundamental of input and output


4-19

Introduction to MS Visual C/C++ 6.0


printf( )

The printf( ) function reads data from the variable according to

Introduction to MS Visual C/C++ 6.0


printf( )

The printf( ) function reads data from the variable according to

a specified format and display on the screen.

a specified format and display on the screen.

Types of printf() Format Strings

Types of printf() Format Strings

1. Literal text

1. Literal text

Literal text is displayed exactly as entered in the format string

Literal text is displayed exactly as entered in the format string

Refer to Appendix 4-2

Refer to Appendix 4-2

2. Escape sequence

2. Escape sequence

An escape sequence provides special formatting

control.

An escape sequence consists of a backslash (\) followed


by a single character.

3. Conversion specifier
Applied when the display involves the variables.

Outcome 4: Variables, operators and Fundamental of input and output


4-20

An escape sequence provides special formatting


control.

An escape sequence consists of a backslash (\) followed


by a single character.

3. Conversion specifier
Applied when the display involves the variables.

Outcome 4: Variables, operators and Fundamental of input and output


4-20

Introduction to MS Visual C/C++ 6.0

Introduction to MS Visual C/C++ 6.0

REMEMBER ...

REMEMBER ...

Ensure that the conversion specifier used matches the


variable declaration.

variable declaration.

int num1=10;

int num1=10;

printf(Value for num1 is %c, num1);

printf(Value for num1 is %c, num1);

o SOMETIMES, the compiler WILL NOT prompt

o SOMETIMES, the compiler WILL NOT prompt

an error message even though there is a

an error message even though there is a

mismatch.

mismatch.

Place the comma after the double quote.

Place the comma after the double quote.

printf(Value for num1 is %d num1);

printf(Value for num1 is %d num1);

o The compiler will prompt an error message if

o The compiler will prompt an error message if

you misplaced the comma.

Ensure that the conversion specifier used matches the

Do not place the ampersand sign for printf command

you misplaced the comma.

Do not place the ampersand sign for printf command

printf(Value for num1 is %d, &num1);

printf(Value for num1 is %d, &num1);

o The compiler WILL NOT prompt an error

o The compiler WILL NOT prompt an error

message if you place an ampersand sign.

Outcome 4: Variables, operators and Fundamental of input and output


4-21

message if you place an ampersand sign.

Outcome 4: Variables, operators and Fundamental of input and output


4-21

Operators

Operators
Operators are tokens that result in some kind of

Operators are tokens that result in some kind of

computation or action when applied to variables or other

computation or action when applied to variables or other

elements in an expression.

elements in an expression.

Now, lets look at operational method. We have 4 type of

Now, lets look at operational method. We have 4 type of

operators which is:

operators which is:

1. The assignment operator

1. The assignment operator

2. Arithmetic operators

2. Arithmetic operators

3. Relational operators

3. Relational operators

4. Logical operators

4. Logical operators

Let's look for more details.

Let's look for more details.

Assignment

The assignment operator is the equal sign, =.

Assignment

The assignment operator is the equal sign, =.

operator

In C, the equal sign indicates copying of data within

operator

In C, the equal sign indicates copying of data within

variables.

Outcome 4: Variables, operators and Fundamental of input and output


4-22

variables.

Outcome 4: Variables, operators and Fundamental of input and output


4-22

Operators

Operators

Arithmetic

We can form more complicated arithmetic expressions by

Arithmetic

We can form more complicated arithmetic expressions by

Operators

using arithmetic operators. There are 2 types of arithmetic

Operators

using arithmetic operators. There are 2 types of arithmetic

operators in C: unary arithmetic operators and binary

operators in C: unary arithmetic operators and binary

arithmetic operators.

arithmetic operators.

Unary mathematical operators are operators that require

Unary mathematical operators are operators that require

one operand.

one operand.

Auto-increment, ++

Auto-increment, ++

For example: ++x , x++

Auto-decrement, - -

For example: - -x , x- -

For example: ++x , x++

Auto-decrement, - -

For example: - -x , x- -

Binary mathematical operator are operators that require

Binary mathematical operator are operators that require

two operands:

two operands:

Outcome 4: Variables, operators and Fundamental of input and output


4-23

Outcome 4: Variables, operators and Fundamental of input and output


4-23

Operators

Operators

Relational

An expression that computes two expressions using a

Relational

An expression that computes two expressions using a

Operators

relational operators. There are 6 relational expressions in

Operators

relational operators. There are 6 relational expressions in

C:

Logical Operators

In general, the logical expression is one that computes to

C:

Logical Operators

In general, the logical expression is one that computes to

either true or false.

either true or false.

Refer to Appendix 4-4 to 4-9 for more examples..

Refer to Appendix 4-4 to 4-9 for more examples..

Outcome 4: Variables, operators and Fundamental of input and output


4-24

Outcome 4: Variables, operators and Fundamental of input and output


4-24

Summary

Summary

This chapter at a

There must have one function called main().

glance

Place an empty parentheses (( )) after the main function

This chapter at a

There must have one function called main().

glance

Place an empty parentheses (( )) after the main function

name

name

Place a pair of braces ({}) after main ( ) to indicate the

start and end of the program.

Place a pair of braces ({}) after main ( ) to indicate the


start and end of the program.

Every program statement must end with semicolon

except main ( ) & include directive.

Every program statement must end with semicolon


except main ( ) & include directive.

C is a case sensitive programming.

C is a case sensitive programming.

Number of open braces { must be equal to number of

Number of open braces { must be equal to number of

close braces } within the whole program.

clrscr ( ) is used to clear the screen.

Place

the

command

clrscr()

after

close braces } within the whole program.

the

variable

clrscr ( ) is used to clear the screen.

Place

declaration.

the

command

clrscr()

after

the

variable

declaration.

Place the comment by using command /*..*/

Place the comment by using command /*..*/

The C compiler isn't sensitive to spaces, tabs, and blank

The C compiler isn't sensitive to spaces, tabs, and blank

lines in the source code.

Outcome 4: Variables, operators and Fundamental of input and output


4-25

lines in the source code.

Outcome 4: Variables, operators and Fundamental of input and output


4-25

Outcome 5

Outcome 5

Basic Program Control

Basic Program Control

Structures

Structures

Controlling Program Execution


Introduction

Controlling Program Execution

The C language includes a variety of program control

Introduction

The C language includes a variety of program control

statements that let you control the order of program

statements that let you control the order of program

execution. Frequently in a program, we may want to execute

execution. Frequently in a program, we may want to execute

a block of code repeatedly, a finite number of times, until a

a block of code repeatedly, a finite number of times, until a

certain task is accomplished. For this purpose we use

certain task is accomplished. For this purpose we use

repetition statements.

repetition statements.

For statement

For statement

Nested for statement

Nested for statement

While statement

While statement

Nested while statement

Nested while statement

Do..while statement

Do..while statement

Nested Do..while statement

Nested Do..while statement

Purpose of

The purpose of using the looping command is to shorten the

Purpose of

The purpose of using the looping command is to shorten the

Looping

program,

Looping

program,

FOR Statement

which

involves

repeated

task.

Every

which

involves

repeated

task.

Every

programming language has constructs that can be used to

programming language has constructs that can be used to

define controlled repetition (or loops) on a program block.

define controlled repetition (or loops) on a program block.

A program block that is executed repeatedly by a repetition

A program block that is executed repeatedly by a repetition

statement is called its loop body.

statement is called its loop body.

A FOR statement has the following structure:

Outcome 5: Basic Program Control

FOR Statement

A FOR statement has the following structure:

Outcome 5: Basic Program Control


5-1

5-1

Controlling Program Execution

Controlling Program Execution

For example,

For example,

for (time = 2 am ; time <=10 pm ; time=time + 2 hours)

for (time = 2 am ; time <=10 pm ; time=time + 2 hours)

{
task 1;

task 1;

task 2;

task 2;

task 3;

task 3;

task 4;

task 4;

In flowchart, this code represent by:

In flowchart, this code represent by:

Example with C expression:

Example with C expression:

for (count1=1 ; count1<=20 ; ++count1)

for (count1=1 ; count1<=20 ; ++count1)

Outcome 5: Basic Program Control

Outcome 5: Basic Program Control


5-2

5-2

Controlling Program Execution

Controlling Program Execution

task 1;

task 1;

task 2;

task 2;

}
task 3;

task 3;

Refer Appendix 5-1 to look at the example of FOR

Refer Appendix 5-1 to look at the example of FOR

statement.

statement.

The flow of FOR statement for Appendix 5-1 is

The flow of FOR statement for Appendix 5-1 is

Initial, condition, and increment are all C expressions, and

Initial, condition, and increment are all C expressions, and

statement is a single or compound C statement. When a for

statement is a single or compound C statement. When a for

statement is encountered during program execution, the

statement is encountered during program execution, the

following events occur:

following events occur:

The expression initial is evaluated. initial is usually

The expression initial is evaluated. initial is usually

an assignment statement that sets a variable to a

an assignment statement that sets a variable to a

particular value.

particular value.

Outcome 5: Basic Program Control

Outcome 5: Basic Program Control


5-3

5-3

Controlling Program Execution

Controlling Program Execution

The expression condition is evaluated. Condition is


typically a relational expression.

The expression condition is evaluated. Condition is


typically a relational expression.

If condition evaluates to false (that is, as zero), the

If condition evaluates to false (that is, as zero), the

FOR statement terminates, and execution passes to

FOR statement terminates, and execution passes to

the first statement following statement.

the first statement following statement.

If condition evaluates to true (that is, as nonzero),

If condition evaluates to true (that is, as nonzero),

the C statement(s) in statement are executed. The

the C statement(s) in statement are executed. The

expression increment is evaluated, and execution

expression increment is evaluated, and execution

returns to step 2.

returns to step 2.

In FOR statement, the variable for initial statement,

In FOR statement, the variable for initial statement,

condition and increment can be a different variable.

condition and increment can be a different variable.

For example,

For example,

for (count1=1 ; count3<=20 ; count2 = count2+2 )

for (count1=1 ; count3<=20 ; count2 = count2+2 )

{
task 1;

task 1;

task 2;

task 2;

}
task 3;

task 3;

Refer Appendix 5-2 to look at the example...

Refer Appendix 5-2 to look at the example...

Nested FOR

A FOR statement can be executed within another for

Nested FOR

A FOR statement can be executed within another for

Statement

statement. This is called nesting. By nesting FOR

Statement

statement. This is called nesting. By nesting FOR

statements, you can do some complex programming. The

statements, you can do some complex programming. The

nested FOR statement will be applied in the array section.

nested FOR statement will be applied in the array section.

Outcome 5: Basic Program Control

Outcome 5: Basic Program Control


5-4

5-4

Controlling Program Execution


for (count1=1 ; count1<=20 ; ++count1)

Controlling Program Execution


for (count1=1 ; count1<=20 ; ++count1)

task 1;

task 1;

for (count2=1;count2<=10 ; ++count2)

for (count2=1;count2<=10 ; ++count2)

{
task 2;
task 3;

task 2;

FOR loop
within the
outer loop

task 3;
}

task 4;

FOR loop
within the
outer loop

task 4;

Refer to Appendix 5-3 for the example of Nested FOR

Refer to Appendix 5-3 for the example of Nested FOR

Statement...

Statement...

Outcome 5: Basic Program Control

Outcome 5: Basic Program Control


5-5

5-5

Controlling Program Execution

Controlling Program Execution

Multiple FOR loop:

Multiple FOR loop:

for (count1 =1; count1<=20 ; ++count1)

for (count1 =1; count1<=20 ; ++count1)

{
task 1;

task 1;

for (count2=1; count2<=10; ++count2)

for (count2=1; count2<=10; ++count2)

{
task 2;

task 2;

for (count3=5; count3>0; - - count3)

for (count3=5; count3>0; - - count3)

{
task 3;

task 3;

}
REMEMBER...

1. Do not place a semicolon after FOR statement


for (count1 =1; count1<=20 ; ++count1);

REMEMBER...

1. Do not place a semicolon after FOR statement


for (count1 =1; count1<=20 ; ++count1);

The compiler WILL NOT prompt an error

The compiler WILL NOT prompt an error

message if the semicolon is placed after FOR

message if the semicolon is placed after FOR

statement.

statement.

The misplaced of semicolon will

cause the compiler to skip FOR statement.

The misplaced of semicolon will

cause the compiler to skip FOR statement.

2. Place curly braces after FOR statement if there is more

2. Place curly braces after FOR statement if there is more

than ONE expression/statements under this FOR loop.

than ONE expression/statements under this FOR loop.

for (count3=5; count3>0; - - count3)

for (count3=5; count3>0; - - count3)

task 3;

task 3;

task 4;

task 4;

The compiler WILL NOT prompt an error


message. If this case occurs, only the statement

Outcome 5: Basic Program Control

The compiler WILL NOT prompt an error


message. If this case occurs, only the statement

Outcome 5: Basic Program Control


5-6

5-6

Controlling Program Execution

Controlling Program Execution

after FOR statement is consider belongs to this

after FOR statement is consider belongs to this

FOR loop. The rest are considered outside FOR

FOR loop. The rest are considered outside FOR

loop.

loop.

3. Ensure that the condition in FOR statement is valid.

3. Ensure that the condition in FOR statement is valid.

for (count3=10; count3>0; count3++)

for (count3=10; count3>0; count3++)

{
task 3;

task 3;

task 4;

task 4;

The compiler WILL NOT prompt an error

The compiler WILL NOT prompt an error

message if the condition is invalid. The output

message if the condition is invalid. The output

of the program may continue looping

of the program may continue looping

(like

(like

screen saver). Press Ctrl + Break to stop the

screen saver). Press Ctrl + Break to stop the

looping and return to the source code editor to

looping and return to the source code editor to

find the error(s).

find the error(s).

4. Ensure that the number of close curly braces and open


curly braces is same.
for (count1 =1; count1<=20 ; ++count1)
{

4. Ensure that the number of close curly braces and open


curly braces is same.
for (count1 =1; count1<=20 ; ++count1)
{

task 1;

task 1;

task 2;

task 2;

for (count3=5; count3>0; - - count3)

for (count3=5; count3>0; - - count3)

{
task 3;

task 3;

Outcome 5: Basic Program Control

Outcome 5: Basic Program Control


5-7

5-7

Controlling Program Execution

Controlling Program Execution

The compiler prompts a message Compound

The compiler prompts a message Compound

statement missing } in function main and the

statement missing } in function main and the

last curly brace is highlighted. Do not place the

last curly brace is highlighted. Do not place the

missing } in highlighted position. Troubleshoot

missing } in highlighted position. Troubleshoot

your program step by step to look for the missing

your program step by step to look for the missing

}.

}.

WHILE

The WHILE statement, also called the while loop, executes

WHILE

The WHILE statement, also called the while loop, executes

Statement

a block of statements as long as a specified condition is true.

Statement

a block of statements as long as a specified condition is true.

The while statement has the following form:

The while statement has the following form:

while (condition)
{
task 1;
task 2;
}

while (condition)
{

Condition is the
requirement / prerequisite to
execute the tasks within the
open braces and close
braces

task 1;
task 2;
}

Condition is the
requirement / prerequisite to
execute the tasks within the
open braces and close
braces

The WHILE statement DOES NOT contain an initialisation

The WHILE statement DOES NOT contain an initialisation

section. Thus, we must take care of initializing any variables

section. Thus, we must take care of initializing any variables

before starting WHILE statement. The increment section of

before starting WHILE statement. The increment section of

WHILE statement is done within the statement of the

WHILE statement is done within the statement of the

looping (within the curly braces).

looping (within the curly braces).

For example,

For example,

time = 2 am ;
while (time <=10 pm )
{
task 1;
task 2;
time = time + 2 hours;
}

Outcome 5: Basic Program Control

The initialisation is not part of the


format for while statement.
This statement is considered
as a C statement. Thus, this
statement is not a FORMAT
of while statement

time = 2 am ;
while (time <=10 pm )
{
task 1;
task 2;
time = time + 2 hours;
}

Outcome 5: Basic Program Control


5-8

5-8

The initialisation is not part of the


format for while statement.
This statement is considered
as a C statement. Thus, this
statement is not a FORMAT
of while statement

Controlling Program Execution

Controlling Program Execution

WHILE Statement Flowchart:

WHILE Statement Flowchart:

When program execution reaches a WHILE statement, the

When program execution reaches a WHILE statement, the

following events occur:

following events occur:

The expression condition is evaluated.

The expression condition is evaluated.

If condition evaluates to false , the while statement

If condition evaluates to false , the while statement

terminates, and execution passes to the first

terminates, and execution passes to the first

statement following statement.

statement following statement.

If condition evaluates to true, the C statement(s) in

statement are executed.

Execution returns to step 1.

Outcome 5: Basic Program Control

If condition evaluates to true, the C statement(s) in


statement are executed.

Execution returns to step 1.

Outcome 5: Basic Program Control


5-9

5-9

Controlling Program Execution

Controlling Program Execution

The example of C expression,

The example of C expression,

count1 = 1;
while (count1<=10)
{
task 1;
task 2;
++count1;
}

count1 = 1;
while (count1<=10)
{
task 1;
task 2;
++count1;
}

Refer Appendix 5-4 for the example of WHILE loop...

Refer Appendix 5-4 for the example of WHILE loop...

Difference

In general, anything that can be done with a FOR statement

Difference

In general, anything that can be done with a FOR statement

between FOR and

can also be done with a WHILE statement. Since, the

between FOR and

can also be done with a WHILE statement. Since, the

WHILE statement

increment section is a separate statement, we may forget to

WHILE statement

increment section is a separate statement, we may forget to

include the statement in WHILE statement.

include the statement in WHILE statement.

If this case happens, the program wouldnt know when to

If this case happens, the program wouldnt know when to

stop. Thus, FOR loop is preferred compare with WHILE

stop. Thus, FOR loop is preferred compare with WHILE

loop.

loop.

Nested While

The nested WHILE statement is very similar with the nested

Nested While

The nested WHILE statement is very similar with the nested

Statement

FOR statement. The differences are the initialisation and

Statement

FOR statement. The differences are the initialisation and

increment section for WHILE statement is separated

increment section for WHILE statement is separated

whereby the initialisation and increment section are

whereby the initialisation and increment section are

combined in a single statement for FOR loop.

combined in a single statement for FOR loop.

count1=1;
while (count1<=20)
{
task 1;
count2=1;
while (count2<=5)
{
task 2;
++count2;
}
task 4;
++count1;
}

count1=1;
while (count1<=20)
{
task 1;
count2=1;
while (count2<=5)
{
task 2;
++count2;
}
task 4;
++count1;
}

Outcome 5: Basic Program Control

Outcome 5: Basic Program Control


5-10

5-10

REMEMBER...

Controlling Program Execution

Controlling Program Execution

Refer to Appendix 5-5 for the example of Nested

Refer to Appendix 5-5 for the example of Nested

WHILE statement...

WHILE statement...

1. Do not place a semicolon after WHILE statement

REMEMBER...

1. Do not place a semicolon after WHILE statement

while (count1<=20);

while (count1<=20);

The compiler WILL NOT prompt an error

The compiler WILL NOT prompt an error

message if the semicolon is placed after WHILE

message if the semicolon is placed after WHILE

statement.

statement.

The misplaced of semicolon will

cause the compiler to skip WHILE statement.

The misplaced of semicolon will

cause the compiler to skip WHILE statement.

2. Place curly braces after WHILE statement if there is

2. Place curly braces after WHILE statement if there is

more than ONE expressions / statements under this

more than ONE expressions / statements under this

WHILE loop.

WHILE loop.
while (count1<=20)
task 1;
count2=1;

Outcome 5: Basic Program Control

while (count1<=20)
task 1;
count2=1;

Outcome 5: Basic Program Control


5-11

5-11

Controlling Program Execution

Controlling Program Execution

The compiler WILL NOT prompt an error

The compiler WILL NOT prompt an error

message. If this case occurs, only the statement

message. If this case occurs, only the statement

after WHILE statement is consider belongs to

after WHILE statement is consider belongs to

this WHILE loop. The rest of the expressions

this WHILE loop. The rest of the expressions

are considered outside WHILE loop.

are considered outside WHILE loop.

3. Ensure that the condition in WHILE statement is valid.

3. Ensure that the condition in WHILE statement is valid.

while (count1>0)
task 1;
count2=1;

while (count1>0)
task 1;
count2=1;

The compiler WILL NOT prompt an error

The compiler WILL NOT prompt an error

message if the condition is invalid. The output

message if the condition is invalid. The output

of the program may continue looping

of the program may continue looping

(like

(like

screen saver). Press Ctrl + Break to stop the

screen saver). Press Ctrl + Break to stop the

looping and return to the source code editor to

looping and return to the source code editor to

find the error(s).

find the error(s).

4. Ensure that the number of close curly braces and open

4. Ensure that the number of close curly braces and open

curly braces is same.

curly braces is same.

count1=1;
while (count1<=20)
{
task 1;
count2=1;
while (count2<=5)
{
task 2;
++count2;
}
task 4;
++count1;

count1=1;
while (count1<=20)
{
task 1;
count2=1;
while (count2<=5)
{
task 2;
++count2;
}
task 4;
++count1;

Outcome 5: Basic Program Control

Outcome 5: Basic Program Control


5-12

5-12

Controlling Program Execution

Controlling Program Execution

The compiler prompts a message Compound

The compiler prompts a message Compound

statement missing } in function main and the

statement missing } in function main and the

last curly brace is highlighted. Do not place the

last curly brace is highlighted. Do not place the

missing } in highlighted position. Troubleshoot

missing } in highlighted position. Troubleshoot

your program step by step to look for the missing

your program step by step to look for the missing

} .

} .

DOWHILE

The DO...WHILE loop tests the condition at the end of the

DOWHILE

The DO...WHILE loop tests the condition at the end of the

Statement

loop rather than at the beginning, as is done by FOR loop

Statement

loop rather than at the beginning, as is done by FOR loop

and WHILE loop.

and WHILE loop.

The structure of DO...WHILE loop is as follows:

The structure of DO...WHILE loop is as follows:

do
Condition is the requirement / prerequisite
{
to execute the tasks within the open
braces and close braces
task 1;
task 2;
} while (condition);

do
Condition is the requirement / prerequisite
{
to execute the tasks within the open
braces and close braces
task 1;
task 2;
} while (condition);

The statements associated with a DO...WHILE loop are

The statements associated with a DO...WHILE loop are

always executed at least once. This is because the test

always executed at least once. This is because the test

condition is evaluated at the end of the loop.

condition is evaluated at the end of the loop.

In contrast, FOR loops and WHILE loops evaluate the test

In contrast, FOR loops and WHILE loops evaluate the test

condition at the start of the loop, so the associated

condition at the start of the loop, so the associated

statements are not executed at all if the test condition is

statements are not executed at all if the test condition is

initially false. The DO...WHILE loop is used less frequently

initially false. The DO...WHILE loop is used less frequently

than WHILE and FOR loops.

than WHILE and FOR loops.

For example,

For example,

The initialisation is not part of the


time = 2 am ;
format for do...while statement.
do
{
task 1;
This statement is considered
task 2;
as a C statement. Thus, this
time = time + 2 hours;
statement is not a FORMAT
} while (time <=10 pm );
of do...while statement
Outcome 5: Basic Program Control

The initialisation is not part of the


time = 2 am ;
format for do...while statement.
do
{
task 1;
This statement is considered
task 2;
as a C statement. Thus, this
time = time + 2 hours;
statement is not a FORMAT
} while (time <=10 pm );
of do...while statement
Outcome 5: Basic Program Control

5-13

5-13

Controlling Program Execution

Controlling Program Execution

When program execution reaches a DO...WHILE statement,

When program execution reaches a DO...WHILE statement,

the following events occur:

the following events occur:

The statements in statement are executed.

The statements in statement are executed.

Condition is evaluated. If it's true, execution returns

Condition is evaluated. If it's true, execution returns

to step 1. If it's false, the loop terminates.

REMEMBER...

to step 1. If it's false, the loop terminates.

The example of C expression,

The example of C expression,

count1 = 1;
do
{
task 1;
task 2;
++count1;
} while (count1<=10);

count1 = 1;
do
{
task 1;
task 2;
++count1;
} while (count1<=10);

Refer Appendix 5-6 for example of DOWHILE loop...

Refer Appendix 5-6 for example of DOWHILE loop...

1. Do not place a semicolon after DO statement

REMEMBER...

1. Do not place a semicolon after DO statement

count1 = 1;
do;

Outcome 5: Basic Program Control

count1 = 1;
do;

Outcome 5: Basic Program Control


5-14

5-14

Controlling Program Execution

Controlling Program Execution

The compiler WILL NOT prompt an error

The compiler WILL NOT prompt an error

message if the semicolon is placed after

message if the semicolon is placed after

DOWHILE statement.

DOWHILE statement.

The misplaced of

semicolon will cause the compiler to skip

semicolon will cause the compiler to skip

DOWHILE statement.

DOWHILE statement.

2. Ensure the condition in DOWHILE statement is valid.

2. Ensure the condition in DOWHILE statement is valid.

count1 = 30;
do
{
task 1;
task 2;
++count1;
} while (count1>10);

3. Place

The misplaced of

count1 = 30;
do
{
task 1;
task 2;
++count1;
} while (count1>10);

The compiler WILL NOT prompt an error

The compiler WILL NOT prompt an error

message if the condition is invalid. The output

message if the condition is invalid. The output

of the program may continue looping

of the program may continue looping

(like

(like

screen saver). Press Ctrl + Break to stop the

screen saver). Press Ctrl + Break to stop the

looping and return to the source code editor to

looping and return to the source code editor to

find the error(s).

find the error(s).

semicolon

after

WHILE

statement

for

DOWHILE loop.

3. Place

semicolon

Outcome 5: Basic Program Control

statement

for

} while (count1>10);

The compiler prompt an error message

The compiler prompt an error message

Do-while statement misssing ; in function

Do-while statement misssing ; in function

main. and the last curly brace is

main. and the last curly brace is

highlighted. Do not place the missing ;

highlighted. Do not place the missing ;

in highlighted position. Troubleshoot

in highlighted position. Troubleshoot

your program step by step to look for the

your program step by step to look for the

missing ; .

missing ; .

Outcome 5: Basic Program Control


5-15

WHILE

DOWHILE loop.

} while (count1>10);

after

5-15

Outcome 6

Outcome 6

Selection Control

Selection Control

Structures

Structures

Introduction and Objectives

Introduction and Objectives

Module

In this chapter you will learn about:

Module

In this chapter you will learn about:

Objectives

Objectives

Simple selection control structures

Simple selection control structures

o Selection using If statement

o Selection using If statement

o Using the Multiple If statement

o Using the Multiple If statement

o Nested if statement

o Nested if statement

o If.else statement

o If.else statement

o Nested If.Else statement

o Nested If.Else statement

o Switch and Break Statement

o Switch and Break Statement

In previous chapter, we learned that the selection control

In previous chapter, we learned that the selection control

structures are one of the fundamental elements in algorithm

structures are one of the fundamental elements in algorithm

design. Its purpose is to execute one of the several possible

design. Its purpose is to execute one of the several possible

alternatives using an appropriate selection criterion. Every

alternatives using an appropriate selection criterion. Every

programming language, including C, has some language

programming language, including C, has some language

constructs that correspond to the selection control structure.

constructs that correspond to the selection control structure.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-1

6-1

Selection Control Structures

IF Statement

Selection Control Structures

The selection control structures are control statements that

The selection control structures are control statements that

select alternative statements for execution based on the

select alternative statements for execution based on the

result of the test.

result of the test.

The C language includes a variety of selection control

The C language includes a variety of selection control

structures that let us control the program execution.

structures that let us control the program execution.

If statement

If statement

Ifelse statement

Ifelse statement

Ifelse if statement

Ifelse if statement

Switch and Break statement

Switch and Break statement

An IF statement has the following structure:


if (condition)
{
task 1 ;
task 2 ;
task 3 ;
task 4 ;
}
task 5;

Condition is the
requirement /
prerequisite to
execute the tasks

The selection control structure represent by flowchart:

Outcome 6: Selection Structure

IF Statement

An IF statement has the following structure:


if (condition)
{
task 1 ;
task 2 ;
task 3 ;
task 4 ;
}
task 5;

The selection control structure represent by flowchart:

Outcome 6: Selection Structure


6-2

Condition is the
requirement /
prerequisite to
execute the tasks

6-2

Selection Control Structures

REMEMBER...

Selection Control Structures

if ((number >3)&& ( number < 20))


{
task 1 ;
task 2 ;
task 3 ;
task 4 ;
}
task 5;

if ((number >3)&& ( number < 20))


{
task 1 ;
task 2 ;
task 3 ;
task 4 ;
}
task 5;

Refer Appendix 6-1 to look at example of IF statement

Refer Appendix 6-1 to look at example of IF statement

Do not place a semicolon after IF statement

REMEMBER...

if ((number >3)&& (number < 20));

Do not place a semicolon after IF statement


if ((number >3)&& (number < 20));

o The compiler WILL NOT prompt an error message

o The compiler WILL NOT prompt an error message

if the semicolon is placed after IF statement. The

if the semicolon is placed after IF statement. The

misplaced of semicolon will cause the compiler to

misplaced of semicolon will cause the compiler to

skip IF statement. It means all the statement under IF

skip IF statement. It means all the statement under IF

statements are executed without checking the

statements are executed without checking the

condition.

condition.

Place curly braces after IF statement if there is more

than ONE expressions / statements under IF statement.

Place curly braces after IF statement if there is more


than ONE expressions / statements under IF statement.

if ((number >3)&& (number < 20))


task 1 ;
task 2 ;

if ((number >3)&& (number < 20))


task 1 ;
task 2 ;

o The compiler WILL NOT prompts an error

o The compiler WILL NOT prompts an error

message. If this case occurs, only a single

message. If this case occurs, only a single

statement after IF statement is consider belongs

statement after IF statement is consider belongs

to this IF statement. The rest of the expressions

to this IF statement. The rest of the expressions

are considered outside IF statement.

are considered outside IF statement.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-3

6-3

Selection Control Structures

Selection Control Structures

Multiple IF

For example,

Multiple IF

For example,

Statement

if (condition1)
{
task 1 ;
task 2;
}
if ( condition2)
{
task 3 ;
task 4 ;
}

Statement

if (condition1)
{
task 1 ;
task 2;
}
if ( condition2)
{
task 3 ;
task 4 ;
}

Nested IF

Refer Appendix 6-2 to look at the example of Multiple IF

Refer Appendix 6-2 to look at the example of Multiple IF

statement

statement

For example,

Nested IF

Statement

For example,

Statement
if (condition1)
{
task 1 ;
if ( condition2)
{
task 2 ;
task 3 ;
}

if (condition1)
{
task 1 ;
if ( condition2)
{
task 2 ;
task 3 ;
}

task 4;
}

task 4;
}

Refer Appendix 6-3 to look at the example of Nested IF

Refer Appendix 6-3 to look at the example of Nested IF

statement

statement

IF-ELSE

Essentially, the IF statement is used to implement two-way

IF-ELSE

Essentially, the IF statement is used to implement two-way

Statement

selection. The IF-ELSE statement lets us choose between

Statement

selection. The IF-ELSE statement lets us choose between

two alternative statements.

two alternative statements.

If the condition is true, one set of statement(s) to be

If the condition is true, one set of statement(s) to be

executed. If the condition is false, another set of

executed. If the condition is false, another set of

statement(s) to be executed.

statement(s) to be executed.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-4

6-4

Selection Control Structures


The general form of IF-ELSE statement is

Selection Control Structures


The general form of IF-ELSE statement is

if (condition1)
{
task 1 ;
task 2;
}
else
{
task 3;
task 4;
}
task 5;

if (condition1)
{
task 1 ;
task 2;
}
else
{
task 3;
task 4;
}
task 5;

The flowchart shows the logic of IF statement graphically.

The flowchart shows the logic of IF statement graphically.

In executing an if statement, the computer goes through the

In executing an if statement, the computer goes through the

following sequence of operations:

following sequence of operations:

1. Evaluate the parenthesized expression.

1. Evaluate the parenthesized expression.

2. If the computed value of the expression is true,

2. If the computed value of the expression is true,

execute Task1 & 2, and bypass Task3 & 4, dropping

execute Task1 & 2, and bypass Task3 & 4, dropping

down to the Task5 and other statement that follows

down to the Task5 and other statement that follows

the entire if statement.

the entire if statement.

3. If the expression evaluate to false, it will bypass

3. If the expression evaluate to false, it will bypass

Task 1& 2, and execute Task 3 & 4.

Task 1& 2, and execute Task 3 & 4.

Refer Appendix 6-4 to look at the example of IF-ELSE

Refer Appendix 6-4 to look at the example of IF-ELSE

statement.

statement.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-5

6-5

Selection Control Structures

Selection Control Structures

Relational

Conditional expressions are formed using relational and

Relational

Conditional expressions are formed using relational and

Operators and

logical operators. In this chapter we will study only

Operators and

logical operators. In this chapter we will study only

Simple Predicates

relational operators. An expression that compares two

Simple Predicates

relational operators. An expression that compares two

expressions using a relational operator is called a simple

expressions using a relational operator is called a simple

predicate. A simple predicate compute to either 1 (for true)

predicate. A simple predicate compute to either 1 (for true)

or 0 (for false). There are six relational operators in C:

or 0 (for false). There are six relational operators in C:

1. Equal-to, ==

1. Equal-to, ==

2. Not-equal-to, !=

2. Not-equal-to, !=

3. Less-than, <

3. Less-than, <

4. Less-than-or-equal-to, <=

4. Less-than-or-equal-to, <=

5. Greater-than, >

5. Greater-than, >

6. Greater-than-or-equal-to, >=

6. Greater-than-or-equal-to, >=

Logical

In order to cope with complex selection problems, C allows

Logical

In order to cope with complex selection problems, C allows

expressions and

us to use complex logical expressions (or predicates) in

expressions and

us to use complex logical expressions (or predicates) in

operators

selection structures. In general, a logical expression is one

operators

selection structures. In general, a logical expression is one

that computes to either true or false. A simple predicate is a

that computes to either true or false. A simple predicate is a

logical expression because it produces either a true or false

logical expression because it produces either a true or false

result; so is a complex predicate.

result; so is a complex predicate.

A complex predicate is an expression that is formed using

A complex predicate is an expression that is formed using

simple predicates and logical operators.

simple predicates and logical operators.

There are 3 logical operators that can be used in forming

There are 3 logical operators that can be used in forming

complex predicates:

complex predicates:

1. Logical and (conjunction)

1. Logical and (conjunction)

2. Logical or (disjunction)

2. Logical or (disjunction)

3. Logical not (negation)

3. Logical not (negation)

Logical and is a binary operator that requires two operands

Logical and is a binary operator that requires two operands

that are logical expression. It yields true if and only if both

that are logical expression. It yields true if and only if both

of its operands evaluate to true.

of its operands evaluate to true.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-6

6-6

Selection Control Structures

Selection Control Structures

Otherwise, it computes to false. Following is the truth table

Otherwise, it computes to false. Following is the truth table

for logical and:

for logical and:

Operand_1 Operand_2

Operand_1 and Operand _2

Operand_1 Operand_2

Operand_1 and Operand _2

true

true

true

true

true

true

true

false

false

true

false

false

false

true

false

false

true

false

false

false

false

false

false

false

Logical or is also a binary operator, requiring two operands

Logical or is also a binary operator, requiring two operands

that are logical expressions. It returns false if and only if

that are logical expressions. It returns false if and only if

both of its operands are false; otherwise, it returns true. Here

both of its operands are false; otherwise, it returns true. Here

is the truth table for logical or:

is the truth table for logical or:

Operand_1 Operand_2

Operand_1 or Operand _2

Operand_1 Operand_2

Operand_1 or Operand _2

true

true

true

true

true

true

true

false

true

true

false

true

false

true

true

false

true

true

false

false

false

false

false

false

In C, the symbols used for the three logical operators and

In C, the symbols used for the three logical operators and

their semantics are somewhat different from usual notation

their semantics are somewhat different from usual notation

or interpretation.

or interpretation.

1. Logical and is represented by &&.

1. Logical and is represented by &&.

2. Logical or is represented by ||

2. Logical or is represented by ||

Nested IF-ELSE

The IF statement can be another IF-ELSE statement. A

Nested IF-ELSE

The IF statement can be another IF-ELSE statement. A

Statement

nested IF-ELSE statement may create some confusion

Statement

nested IF-ELSE statement may create some confusion

during the interpreting of ELSE portion.

Outcome 6: Selection Structure

during the interpreting of ELSE portion.

Outcome 6: Selection Structure


6-7

6-7

Selection Control Structures

REMEMBER...

Selection Control Structures

For example,

For example,

If (condition1)
{
task 1;
if (condition2)
{
task 2;
task 3;
}
else
{
task 4;
task 5;
}

If (condition1)
{
task 1;
if (condition2)
{
task 2;
task 3;
}
else
{
task 4;
task 5;
}

The ambiguity comes from the fact that it is not obvious as

The ambiguity comes from the fact that it is not obvious as

to which IF then ELSE refers to.

to which IF then ELSE refers to.

In C, ELSE statement is always associated with the closet IF

In C, ELSE statement is always associated with the closet IF

statement that does not have an ELSE statement. Thus, in

statement that does not have an ELSE statement. Thus, in

this example, ELSE is linked to the second IF statement

this example, ELSE is linked to the second IF statement

instead of the first IF.

instead of the first IF.

Do not place a semicolon after ELSE statement

The compiler WILL NOT prompt an error message if

REMEMBER...

Do not place a semicolon after ELSE statement

The compiler WILL NOT prompt an error message if

the semicolon is placed after ELSE statement for

the semicolon is placed after ELSE statement for

IF_ELSE commands. The misplaced of semicolon will

IF_ELSE commands. The misplaced of semicolon will

cause the compiler to execute all the tasks grouped

cause the compiler to execute all the tasks grouped

under the else statement even though the condition is

under the else statement even though the condition is

false.

false.

Place curly braces after IF or ELSE statement if there is

Place curly braces after IF or ELSE statement if there is

more than ONE expressions / statements under IF or

more than ONE expressions / statements under IF or

ELSE statement.

ELSE statement.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-8

6-8

Selection Control Structures

Selection Control Structures

The compiler WILL NOT prompt an error message. If

The compiler WILL NOT prompt an error message. If

this case occurs, only a single statement after IF or

this case occurs, only a single statement after IF or

ELSE statement is consider belongs to this IF or ELSE

ELSE statement is consider belongs to this IF or ELSE

statement. The rest of the expressions are considered

statement. The rest of the expressions are considered

outside IF statement.

outside IF statement.

ELSE-IF

The statement following the ELSE in an IF-ELSE statement

ELSE-IF

The statement following the ELSE in an IF-ELSE statement

Statement

can be another IF statement. In fact, a series of IFstatements

Statement

can be another IF statement. In fact, a series of IFstatements

can be chained together.

can be chained together.

If (condition1)
{
task 1;
}

If (condition1)
{
task 1;
}

else if (condition2)
{
task 2;
task 3;
}

else if (condition2)
{
task 2;
task 3;
}

else if (condition 3)
{
task 4;
task 5;
}

else if (condition 3)
{
task 4;
task 5;
}

else
{
task 6;
}

else
{
task 6;
}

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-9

6-9

Selection Control Structures

Selection Control Structures

The code represent by the following flowchart.

The code represent by the following flowchart.

Refer Appendix 6-5 and 6-6 to look at the example of

Refer Appendix 6-5 and 6-6 to look at the example of

ELSE-IF statement.

ELSE-IF statement.

SWITCH and

The SWITCH statement is a multiple branch decision

SWITCH and

The SWITCH statement is a multiple branch decision

BREAK

statement in which one of several statements (or groups of

BREAK

statement in which one of several statements (or groups of

Statement

statements) is executed depending on the value of a variable

Statement

statements) is executed depending on the value of a variable

or an expression.

or an expression.

The general form of SWITCH statement is:

The general form of SWITCH statement is:

switch ( variable)
{
case constant 1:
task1;
break;
case constant 2:
task3;
break;
default:
task5 ;
break;
}

switch ( variable)
{
case constant 1:
task1;
break;
case constant 2:
task3;
break;
default:
task5 ;
break;
}

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-10

6-10

Selection Control Structures

Selection Control Structures

For example,

For example,

switch ( choice )
{
case 1:
printf (You have selected choice 1);
break;
case 2:
printf (You have selected choice 2);
break;
default:
printf (You have selected other choices);
break;
}

switch ( choice )
{
case 1:
printf (You have selected choice 1);
break;
case 2:
printf (You have selected choice 2);
break;
default:
printf (You have selected other choices);
break;
}

Refer to Appendix 6-7 and 6-8 to look at the example of

Refer to Appendix 6-7 and 6-8 to look at the example of

SWITCHBREAK statement.

SWITCHBREAK statement.

As stated, SWITCH statement consists of the following:

As stated, SWITCH statement consists of the following:

1. The keyword switch

1. The keyword switch

2. An expression, called the controlling expression,

2. An expression, called the controlling expression,

enclosed in parentheses.

enclosed in parentheses.

3. Enclosed in braces:

3. Enclosed in braces:

a. Any number of case clauses consisting of the

a. Any number of case clauses consisting of the

keyword case followed by a constant, a

keyword case followed by a constant, a

colon, and any number of statements.

colon, and any number of statements.

b. An optional default clause consisting of the

b. An optional default clause consisting of the

keyword default followed by a colon and

keyword default followed by a colon and

any number of statements.

any number of statements.

The semantics of SWITCH statement is somewhat different

The semantics of SWITCH statement is somewhat different

from that of CASE control structure. First, the controlling

from that of CASE control structure. First, the controlling

expression is evaluated. The controlling expression must be

expression is evaluated. The controlling expression must be

of type int or char ; it cannot be double.

of type int or char ; it cannot be double.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-11

6-11

Selection Control Structures

Selection Control Structures

If SWITCH statement contains a case clause with a constant

If SWITCH statement contains a case clause with a constant

value that matches the value of the controlling expressions,

value that matches the value of the controlling expressions,

the statements in that case clause are executed until the end

the statements in that case clause are executed until the end

of SWITCH statement it reached.

of SWITCH statement it reached.

The end of SWITCH statement is the right brace, } , that is

The end of SWITCH statement is the right brace, } , that is

associated with it. If the value of the controlling expression

associated with it. If the value of the controlling expression

does not match any of the constant values in the case

does not match any of the constant values in the case

clauses, the content of the default clause is executed. If

clauses, the content of the default clause is executed. If

there is no default clause, the program control exits

there is no default clause, the program control exits

SWITCH statement.

SWITCH statement.

Limitation of

There are some limitations for switch statement over IF-

Limitation of

There are some limitations for switch statement over IF-

SWITCH and

ELSE statement. The expression in SWITCH statement

SWITCH and

ELSE statement. The expression in SWITCH statement

BREAK

must be of type int or char. Thus, we cannot use SWITCH

BREAK

must be of type int or char. Thus, we cannot use SWITCH

statement

statement if our choice is based on a floating point variable.

statement

statement if our choice is based on a floating point variable.

REMEMBER...

The SWITCH statement can test only for equality, and the

The SWITCH statement can test only for equality, and the

value following case can be only an integer constant and not

value following case can be only an integer constant and not

a range of values.

a range of values.

Match the variable with the case constant.

The compiler WILL NOT prompt an error message if

REMEMBER...

Match the variable with the case constant.

The compiler WILL NOT prompt an error message if

the case constant does not match with the variable

the case constant does not match with the variable

declaration.

declaration.

Place a curly brace after SWITCH statement.

Place a curly brace after SWITCH statement.

The compiler will prompt the error messages misplaced

The compiler will prompt the error messages misplaced

break in function main and case outside of switch in

break in function main and case outside of switch in

function main if the curly brace is ignored.

function main if the curly brace is ignored.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-12

6-12

Selection Control Structures


Do not place a semicolon after SWITCH statement.

Do not place a semicolon after SWITCH statement.

The compiler will prompt the error messages misplaced

The compiler will prompt the error messages misplaced

break in function main and case outside of switch in

break in function main and case outside of switch in

function main if the semicolon is ignored.

function main if the semicolon is ignored.

Place a double colon after each CASE statement.

Place a double colon after each CASE statement.

The compiler will prompt the error messages case

The compiler will prompt the error messages case

statement missing : in the function main if the double

statement missing : in the function main if the double

colon is ignored.

colon is ignored.

Place a statement BREAK at the end of each case.

Place a statement BREAK at the end of each case.

The compiler WILL NOT prompt an error message if


BREAK statement is ignored.

Example 1

Selection Control Structures

The compiler will

The compiler WILL NOT prompt an error message if


BREAK statement is ignored.

continue executing the task until BREAK statement is

continue executing the task until BREAK statement is

reached even though BREAK statement belongs to other

reached even though BREAK statement belongs to other

CASE.

CASE.

Write a program that can determine the root(s) of a

Example 1

Write a program that can determine the root(s) of a

quadratic equation.

quadratic equation.

The user allows to key in the value of a, b and c for the


quadratic equation of ax2 + bx +c.

The compiler will

From the data keyed in by the user, the program

quadratic equation of ax2 + bx +c.

determines the root(s) of the equation.

Outcome 6: Selection Structure

The user allows to key in the value of a, b and c for the

From the data keyed in by the user, the program


determines the root(s) of the equation.

Outcome 6: Selection Structure


6-13

6-13

Summary

Summary

Style

In software design, our objective is to create clear and

Style

In software design, our objective is to create clear and

consideration

readable code. Complex multiway selection structure

consideration

readable code. Complex multiway selection structure

when using

requires special care. Otherwise, the reader of the program

when using

requires special care. Otherwise, the reader of the program

multiway selection

may find it difficult to understand its logic.

multiway selection

may find it difficult to understand its logic.

structure

So in designing using a selection structure, you must

structure

So in designing using a selection structure, you must

remember the following:

remember the following:

1. Avoid deeply nested IF statement. Instead, prefer

1. Avoid deeply nested IF statement. Instead, prefer

either a series of consecutive IF or a few IF statements

either a series of consecutive IF or a few IF statements

with complex predicates.

with complex predicates.

2. Keep the use of logical negation to minimum in forming

2. Keep the use of logical negation to minimum in forming

complex predicates.

complex predicates.

3. Keep logical expression simple by using nested

3. Keep logical expression simple by using nested

selection control structures, if necessary.

selection control structures, if necessary.

4. Remember that nested IF statement is more general

4. Remember that nested IF statement is more general

than a SWITCH statement. However, you should

than a SWITCH statement. However, you should

prefer SWITCH statement whenever the alternatives in a

prefer SWITCH statement whenever the alternatives in a

selection control structures are based on a reasonably

selection control structures are based on a reasonably

small number of values of a variable or expression. A

small number of values of a variable or expression. A

good rule of thumb is to use SWITCH statement for

good rule of thumb is to use SWITCH statement for

three to ten alternative selection control structures.

three to ten alternative selection control structures.

5. Use

proper

indentation

in

forming

SWITCH

5. Use

proper

indentation

in

forming

SWITCH

statements. Indent the keyword CASE for each CASE

statements. Indent the keyword CASE for each CASE

clause with respect to the left brace of SWITCH

clause with respect to the left brace of SWITCH

statement by an equal amount.

statement by an equal amount.

6. In SWITCH statements, separate CASE clause using

6. In SWITCH statements, separate CASE clause using

a blank line. This helps readers understand the actions

a blank line. This helps readers understand the actions

for different CASES.

for different CASES.

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-14

6-14

Summary

Summary

7. Whenever possible, use a default clause in your

7. Whenever possible, use a default clause in your

SWITCH statements. This will force you to consider

SWITCH statements. This will force you to consider

all alternatives, including those that are not defined by

all alternatives, including those that are not defined by

your CASE clause.

your CASE clause.

8. Arrange CASE clauses in SWITCH statements such


as

duplication

of

similar

actions

to

8. Arrange CASE clauses in SWITCH statements such

several

as

duplication

of

similar

actions

to

several

alternatives is avoided. For example, SWITCH

alternatives is avoided. For example, SWITCH

statement below has duplicate action:

statement below has duplicate action:

switch(major code)
{
case 1:
printf(Science student);
break;

switch(major code)
{
case 1:
printf(Science student);
break;

case 2:

case 2:
printf(Art student);
break;

printf(Art student);
break;

case 3:

case 3:
printf(Science student);
break;

printf(Science student);
break;

case 4:

case 4:
printf(Art student);
break;

printf(Art student);
break;

case 5:

case 5:
printf(Science student);
break;

printf(Science student);
break;

}
/* end switch */

}
/* end switch */

On the other hand, in the following SWITCH statement,

On the other hand, in the following SWITCH statement,

duplications are eliminated by arranging CASES with

duplications are eliminated by arranging CASES with

similar actions in groups:

similar actions in groups:

Outcome 6: Selection Structure

Outcome 6: Selection Structure


6-15

6-15

Summary

Summary

switch (major code)


{
case 1:
case 3:
case 5:
printf(Science student);
break;

switch (major code)


{
case 1:
case 3:
case 5:
printf(Science student);
break;

case 2:
case 4:

case 2:
case 4:
printf(Art student);
break;

printf(Art student);
break;

}
/* end switch */

Outcome 6: Selection Structure

}
/* end switch */

Outcome 6: Selection Structure


6-16

6-16

Outcome 7

Outcome 7

Array, Pointer and

Array, Pointer and

Character String

Character String

Introduction and Objectives


Overview

In this chapter, you will learn about:

Definition of an array

Introduction and Objectives


Overview

In this chapter, you will learn about:

Definition of an array

1-Dimensional array

1-Dimensional array

2-Dimensional array

2-Dimensional array

Pointers

Pointers

Declaration of Pointers

Declaration of Pointers

Input and Output Format of Pointers

Input and Output Format of Pointers

Pointers Arithmetic

Pointers Arithmetic

Character String

Character String

Character constant & character string

Character constant & character string

Library Functions for String Manipulation

Library Functions for String Manipulation

Outcome 7: Array, Pointers and Character String


7-1

Outcome 7: Array, Pointers and Character String


7-1

Definition

Definition

What is an

An array is a collection of data storage locations, each

What is an

An array is a collection of data storage locations, each

Array?

having the same data type and the same

Array?

having the same data type and the same

Advantages of

Variables are like individual folders, whereas an array is

Variables are like individual folders, whereas an array is

like a single folder with many compartments.

like a single folder with many compartments.

Array

To provide us with a systematic, compact and flexible

Advantages of

way to handle groups of related data.

Array

way to handle groups of related data.

To allow us to store information in an organized manner


so that it can be easily accessed.

To provide us with a systematic, compact and flexible

To allow us to store information in an organized manner


so that it can be easily accessed.

General

We can create a six elements array with its individual

General

We can create a six elements array with its individual

Introduction of

elements of x[0], x[1], x[2], x[3], x[4] and x[5].

Introduction of

elements of x[0], x[1], x[2], x[3], x[4] and x[5].

Array

Array
x[0]

x[1]

x[2]

x[3]

x[4]

x[5]

x[0]

x[1]

x[2]

x[3]

x[4]

x[5]

80

90

45

30

14

19

80

90

45

30

14

19

Outcome 7: Array, Pointers and Character String


7-2

Outcome 7: Array, Pointers and Character String


7-2

1-Dimensional Array

1-Dimensional Array

The array index, which is the number enclosed in square

The array index, which is the number enclosed in square

brackets after the array name, defines the position of the

brackets after the array name, defines the position of the

individual element in the array.

individual element in the array.

1-Dimensional

The array declaration specifies the type for the array and the

1-Dimensional

The array declaration specifies the type for the array and the

array

number of elements in the array. All arrays in C must be

array

number of elements in the array. All arrays in C must be

explicitly declared so that the compiler can allocate the

explicitly declared so that the compiler can allocate the

necessary memory for the array. The general form of the

necessary memory for the array. The general form of the

declaration for a one-dimensional array:

declaration for a one-dimensional array:

type_specifier array_name[size];

type_specifier array_name[size];

Example of 1-dimensional array declarations:

Example of 1-dimensional array declarations:

REMEMBER...

REMEMBER...

Use an integer constant to declare the size of an array.

The compiler will prompt an error message of

Use an integer constant to declare the size of an array.

The compiler will prompt an error message of

constant expression required in the function main

constant expression required in the function main

and the cursor is placed near the declaration of the

and the cursor is placed near the declaration of the

array if is not.

array if is not.

Outcome 7: Array, Pointers and Character String


7-3

Outcome 7: Array, Pointers and Character String


7-3

1-Dimensional Array

1-Dimensional Array

1-Dimensional

The array initialization method is used to assign data into

1-Dimensional

The array initialization method is used to assign data into

Array

the elements of an array.

Array

the elements of an array.

Initialization

initialization for a one-dimensional array is.

Initialization

initialization for a one-dimensional array is.

REMEMBER...

The general form of array

The general form of array

type_specifier array_name[size] = { list of values};

type_specifier array_name[size] = { list of values};

int buffer [5]= { 50 , 30 , 24 , 8 , 16 };

int buffer [5]= { 50 , 30 , 24 , 8 , 16 };

Refer Appendix 7-1 and Appendix 7-2 to look at the

Refer Appendix 7-1 and Appendix 7-2 to look at the

example of array initialization.

example of array initialization.

Do not forget to place the semicolon at the end of array


initialization.

Do not forget to place the semicolon at the end of array


initialization.

The compiler will prompt an error message of

The compiler will prompt an error message of

Declaration syntax error in function main and the

Declaration syntax error in function main and the

cursor is placed near the area of array initialization.

cursor is placed near the area of array initialization.

Place the array initialization in the declaration part.

REMEMBER...

The compiler will prompt an error message of

Place the array initialization in the declaration part.

The compiler will prompt an error message of

syntax error if the array initialization is made

syntax error if the array initialization is made

within the body of the program.

within the body of the program.

The following is one of the example of manipulate array:

The following is one of the example of manipulate array:

a = buffer [ i ] - buffer [ j ];

a = buffer [ i ] - buffer [ j ];

It is allowed to place a variable as a array index provided

It is allowed to place a variable as a array index provided

the content of the variable is an integer number. In this

the content of the variable is an integer number. In this

case, it means the content of the variable j is being

case, it means the content of the variable j is being

substitute inside the square bracket. Thus, the actual array

substitute inside the square bracket. Thus, the actual array

index is an integer even though we see a variable j inside

index is an integer even though we see a variable j inside

the square bracket.

the square bracket.

Outcome 7: Array, Pointers and Character String


7-4

Outcome 7: Array, Pointers and Character String


7-4

1-Dimensional Array

1-Dimensional Array

Refer Appendix 7-3 to look at the example...

Refer Appendix 7-3 to look at the example...

The most efficient way of manipulating array elements is to

The most efficient way of manipulating array elements is to

use looping command. The loop control variable is used as

use looping command. The loop control variable is used as

the array index.

the array index.

The following program is used to receive 10 data from the

The following program is used to receive 10 data from the

user and place them into an array.

user and place them into an array.

for (count1 = 1; count <= 4; ++count1)


{
scanf (%d, &data [count1] ) ;
}

for (count1 = 1; count <= 4; ++count1)


{
scanf (%d, &data [count1] ) ;
}

It indicates that the integer number that received is being

It indicates that the integer number that received is being

stored in an array called Data. The FOR loop is used to

stored in an array called Data. The FOR loop is used to

change the array index inside the square bracket. Thus, each

change the array index inside the square bracket. Thus, each

new data is being stored in a different level but same

new data is being stored in a different level but same

building.

building.

Outcome 7: Array, Pointers and Character String


7-5

Outcome 7: Array, Pointers and Character String


7-5

1-Dimensional Array

1-Dimensional Array

Refer Appendix 7-4 to look at the manipulation of array

Refer Appendix 7-4 to look at the manipulation of array

using looping command.

using looping command.

Outcome 7: Array, Pointers and Character String


7-6

Outcome 7: Array, Pointers and Character String


7-6

2-Dimensional Array
Overview

2-Dimensional Array

An array whose elements have two array index is called

Overview

An array whose elements have two array index is called

two-dimensional array. A two-dimensional array can be

two-dimensional array. A two-dimensional array can be

seen to represent a table made up of rows and columns. A

seen to represent a table made up of rows and columns. A

two-dimensional array may be thought of as being

two-dimensional array may be thought of as being

composed of horizontal rows and vertical columns.

composed of horizontal rows and vertical columns.

In two-dimensional array, the first array index refers to the

In two-dimensional array, the first array index refers to the

row number, and the second array index refers to the

row number, and the second array index refers to the

column number.

column number.

The array declaration specifies the type of the array and the

The array declaration specifies the type of the array and the

number of elements (for rows and columns) in the array.

number of elements (for rows and columns) in the array.

All arrays in C must be explicitly declared so that the

All arrays in C must be explicitly declared so that the

compiler can allocate the necessary memory for the array.

compiler can allocate the necessary memory for the array.

The general form of declarating for a two-dimensional array

The general form of declarating for a two-dimensional array

type_specifier array_name[row size][column size];

type_specifier array_name[row size][column size];

Outcome 7: Array, Pointers and Character String


7-7

Outcome 7: Array, Pointers and Character String


7-7

2-Dimensional Array
Example of 2-dimensional array declarations:

2-Dimensional Array
Example of 2-dimensional array declarations:

The array initialization method is used to assign data into

The array initialization method is used to assign data into

the elements of an array.

the elements of an array.

The general form of array

initialization for a two-dimensional array is:

The general form of array

initialization for a two-dimensional array is:

type_specifier array_name[size ] = { list of values};

type_specifier array_name[size ] = { list of values};

50

30

24

16

50

30

24

16

Refer Appendix 7-5 and Appendix 7-6 to look at the

Refer Appendix 7-5 and Appendix 7-6 to look at the

example of array initialization

example of array initialization

Outcome 7: Array, Pointers and Character String


7-8

Outcome 7: Array, Pointers and Character String


7-8

2-Dimensional Array
REMEMBER...

Use an integer constant to declare size of two-dimensional

2-Dimensional Array
REMEMBER...

array.

Use an integer constant to declare size of two-dimensional


array.

The compiler will prompt an error message of

The compiler will prompt an error message of

constant expression required in the function main

constant expression required in the function main

and the cursor is placed near the declaration of the

and the cursor is placed near the declaration of the

array.

array.

Do not forget to place the semicolon at the end of array

Do not forget to place the semicolon at the end of array

initialization.

initialization.

The compiler will prompt an error message of


Declaration syntax error in function main and the

Declaration syntax error in function main and the

cursor is placed near the area of array initialization.

cursor is placed near the area of array initialization.

Place the array initialization in the declaration part.

The compiler will prompt an error message of

Place the array initialization in the declaration part.

The compiler will prompt an error message of

The compiler will prompt an error message of

syntax error if the array initialization is made

syntax error if the array initialization is made

within the body of the program.

within the body of the program.

2-dimensional

The following is one of the example of manipulate 2-

2-dimensional

The following is one of the example of manipulate 2-

array Processing

Dimensional array:

array Processing

Dimensional array:

a = buffer[ k ][m] - buffer[i ][ j ];

a = buffer[ k ][m] - buffer[i ][ j ];

This case is similar with 1-dimensional array. It is allowed

This case is similar with 1-dimensional array. It is allowed

to place a variable as an array index provided the content of

to place a variable as an array index provided the content of

the variables are integer numbers. In this case, it means the

the variables are integer numbers. In this case, it means the

content of the variables i and j is being substitute inside

content of the variables i and j is being substitute inside

the square bracket. Thus, the actual array index is an integer

the square bracket. Thus, the actual array index is an integer

even though we see a variable i and j inside the square

even though we see a variable i and j inside the square

bracket.

bracket.

Refer Appendix 7-7 to look at the example.

Refer Appendix 7-7 to look at the example.

Outcome 7: Array, Pointers and Character String


7-9

Outcome 7: Array, Pointers and Character String


7-9

2-Dimensional Array

2-Dimensional Array

The most efficient way of manipulating array elements is to

The most efficient way of manipulating array elements is to

use looping command. The loop control variable is used as

use looping command. The loop control variable is used as

the array index. Two-Dimensional array needs 2 FOR

the array index. Two-Dimensional array needs 2 FOR

looping control variables to manipulate the operation of

looping control variables to manipulate the operation of

rows and columns.

rows and columns.

The following program is used to receive 20 data from the

The following program is used to receive 20 data from the

user and place them into 4 x 5 array.

user and place them into 4 x 5 array.

for (count1=1; count<= 4; ++count1)


{
for (count2=1;count2<=5;++count2)
{
scanf (%d, &data [count2][count1] ) ;
}
}

for (count1=1; count<= 4; ++count1)


{
for (count2=1;count2<=5;++count2)
{
scanf (%d, &data [count2][count1] ) ;
}
}

It indicates that the integer number that received is being

It indicates that the integer number that received is being

stored in a 2-dimensional array called data. The FOR loop is

stored in a 2-dimensional array called data. The FOR loop is

used to change the array index inside the square bracket.

used to change the array index inside the square bracket.

The first FOR loop refers to the row of the array and second

The first FOR loop refers to the row of the array and second

FOR loop refers to the column of the array.

FOR loop refers to the column of the array.

Refer Appendix 7-8 to look at the manipulation of array

Refer Appendix 7-8 to look at the manipulation of array

using looping command.

using looping command.

Outcome 7: Array, Pointers and Character String


7-10

Outcome 7: Array, Pointers and Character String


7-10

Examples
Example 1

Examples
Write a program that determines the sum of multiple arrays.

Example 1

Write a program that determines the sum of multiple arrays.

The program allows the user to enter the data for


multiple arrays.

multiple arrays.

The number of elements for each array is

determining by the user. It can be different for each

array.

array.

After the data entry, the program will prompt the

Write a program that sort the data of a single array in

Example 2

Write a program that sort the data of a single array in


descending order.

The program allows the user to enter the data for


multiple arrays.

The number of elements for each array is

determining by the user. It can be different for each

array.

array.

After the data entry, the program will sort the data

array

After the data entry, the program will sort the data
keyed in by the user in descending order.

Example 3

Write a program that determine maximum number of single


array

The program allows the user to enter the data for

multiple arrays.

The number of elements for each array is

determining by the user. It can be different for each

Write a program that determine maximum number of single

The program allows the user to enter the data for


multiple arrays.

keyed in by the user in descending order.


Example 3

After the data entry, the program will prompt the


sum of each array.

descending order.

The number of elements for each array is

determining by the user. It can be different for each

sum of each array.


Example 2

The program allows the user to enter the data for

The number of elements for each array is

The program allows the user to enter the data for


multiple arrays.

The number of elements for each array is

determining by user. It can be different for each

determining by user. It can be different for each

array.

array.

After data entry, the program will prompt maximum


number of a single array.

Outcome 7: Array, Pointers and Character String


7-11

After data entry, the program will prompt maximum


number of a single array.

Outcome 7: Array, Pointers and Character String


7-11

Pointers
Introduction

Pointers
A pointer is a variable whose value is the address or

Introduction

memory location of another data object.


Purpose of using

Pointer

A pointer is a variable whose value is the address or


memory location of another data object.

Able to pass addresses of variables to functions so that

Purpose of using

functions can change the value of these variables.

Pointer

functions can change the value of these variables.

Capable to work with memory that has been allocated


dynamically.

Able to pass addresses of variables to functions so that

Capable to work with memory that has been allocated


dynamically.

Process and manipulate strings using C library string


functions.

Process and manipulate strings using C library string


functions.

Pass the address of a function to another function.

Pass the address of a function to another function.

Improve efficiency of certain functions.

Improve efficiency of certain functions.

Direct access to the computers hardware.

Direct access to the computers hardware.

Function of pointer

Function of pointer

Outcome 7: Array, Pointers and Character String


7-12

Outcome 7: Array, Pointers and Character String


7-12

Pointers

Pointers

Pointer

To declare a pointer variable, we must associate it with a

Pointer

To declare a pointer variable, we must associate it with a

declaration

data type such as int, char or double and use the indirection

declaration

data type such as int, char or double and use the indirection

operator *, as it prefix.

operator *, as it prefix.

Here is an example:

Here is an example:

int *pointer_to_margaret;

int *pointer_to_margaret;

This declares the variable pointer_to_margaret as a pointer

This declares the variable pointer_to_margaret as a pointer

variable to a memory location that can store a value of type

variable to a memory location that can store a value of type

int.

int.

Initializing

After a pointer variable has been declared, by using an

Initializing

After a pointer variable has been declared, by using an

Pointer variables

assignment statement it is possible to initialize it to:

Pointer variables

assignment statement it is possible to initialize it to:

1. the symbolic constant NULL

1. the symbolic constant NULL

2. an address; OR

2. an address; OR

3. value of another pointer variable

3. value of another pointer variable

For example:

For example:

pointer_to_margaret = NULL;

pointer_to_margaret = NULL;

pointer_to_margaret = 0;

pointer_to_margaret = 0;

pointer_to_margaret = &margaret;

pointer_to_margaret = &margaret;

Outcome 7: Array, Pointers and Character String


7-13

Outcome 7: Array, Pointers and Character String


7-13

Pointers
Input & Output

Input

format

Pointers
Input & Output

scanf (%d, & pu);

Input

format

Output

scanf (%d, & pu);


Output

printf (%d, pu);

Unary operator

Summary

printf (%d, pu);

Unary operator

*ac in declaration part identifies variable, ac as a

Summary

pointer. (eg. int *ac)

*ac in execution part directs the pointer, ac moves to a


specified address (the specified address is the data

Outcome 7: Array, Pointers and Character String


7-14

*ac in declaration part identifies variable, ac as a


pointer. (eg. int *ac)

*ac in execution part directs the pointer, ac moves to a


specified address (the specified address is the data

Outcome 7: Array, Pointers and Character String


7-14

Pointers

Pointers

inside the ac s memory) to read the data.

inside the ac s memory) to read the data.

&v is a command to access the address location of


variable, v

variable, v

Refer to Appendix 7-9 to 7-11 ..

Explanation of program (App7-2)

Pointer and Array

Whenever we create an array, C creates a pointer

&v is a command to access the address location of

Refer to Appendix 7-9 to 7-11 ..

Explanation of program (App7-2)

Pointer and Array

Whenever we create an array, C creates a pointer

constant which has the same name as the name of the

constant which has the same name as the name of the

array.

array.

This pointer constant always point to the first element of


the array.

Outcome 7: Array, Pointers and Character String


7-15

This pointer constant always point to the first element of


the array.

Outcome 7: Array, Pointers and Character String


7-15

Pointers

Pointers

Refer to Appendix 7-12


Pointer Arithmetic

Refer to Appendix 7-12


Pointer Arithmetic

Refer to Appendix 7-13


Pointer as

Pointer can return more than one value from a function.

Refer to Appendix 7-13


Pointer as

Pointer can return more than one value from a function.

Function

Function

Outcome 7: Array, Pointers and Character String


7-16

Outcome 7: Array, Pointers and Character String


7-16

Pointers

Pointers

Function without pointer

Function without pointer

Pass pointer to function

Pass pointer to function

Outcome 7: Array, Pointers and Character String


7-17

Outcome 7: Array, Pointers and Character String


7-17

Pointers
Function with pointer

Pointers
Function with pointer

Refer to Appendix 7-14

Outcome 7: Array, Pointers and Character String


7-18

Refer to Appendix 7-14

Outcome 7: Array, Pointers and Character String


7-18

Character Strings

Character Strings

Character

Here some basic ways to analyze and manipulate string data

Character

Here some basic ways to analyze and manipulate string data

constant &

and then presents some C library functions that are useful

constant &

and then presents some C library functions that are useful

character string

for string manipulation.

character string

for string manipulation.

Character data is stored as intrinsic data type char.

Character data is stored as intrinsic data type char.

String data is stored with a null character terminated

String data is stored with a null character terminated

character array.

character array.

Strings

Strings

Stings in C are a series of characters stored as an unit with

Stings in C are a series of characters stored as an unit with

null character, '\0', terminated character arrays. This means

null character, '\0', terminated character arrays. This means

that the length of a string is the number of characters it

that the length of a string is the number of characters it

contains plus one to store the null character. Common string

contains plus one to store the null character. Common string

operations include finding lengths, copying, searching,

operations include finding lengths, copying, searching,

replacing and counting the occurrences of specific

replacing and counting the occurrences of specific

characters and words. Here is a simple way to determine the

characters and words. Here is a simple way to determine the

length of a string.

length of a string.

#include <stdio.h>

#include <stdio.h>

int main()
{
char sentence[] = "Hello World";
int count = 0;
int i;

int main()
{
char sentence[] = "Hello World";
int count = 0;
int i;

for (i = 0; sentence[i] != '\0'; i++)


{
count++;
}

for (i = 0; sentence[i] != '\0'; i++)


{
count++;
}

printf("The string %s has %d characters ", sentence,count);


printf("and is stored in %d bytes\n", count+1);

printf("The string %s has %d characters ", sentence,count);


printf("and is stored in %d bytes\n", count+1);

Outcome 7: Array, Pointers and Character String


7-19

Outcome 7: Array, Pointers and Character String


7-19

Character Strings

Character Strings

Each character within the array sentence is compared with

Each character within the array sentence is compared with

the null character terminator until the end of the string is

the null character terminator until the end of the string is

encountered. This technique can be generalized to search for

encountered. This technique can be generalized to search for

any character.

any character.

Library Functions

To use these functions in coding, header file "string.h" must

Library Functions

To use these functions in coding, header file "string.h" must

for String

be included. It is programmer's responsibility to check that

for String

be included. It is programmer's responsibility to check that

Manipulation

the destination array is large enough to hold either what is

Manipulation

the destination array is large enough to hold either what is

copied or appended to it. C performs no error checking in

copied or appended to it. C performs no error checking in

this respect. The data type size_t is equivalent to unsigned

this respect. The data type size_t is equivalent to unsigned

integer.

integer.

strcpy

strcpy

strcpy copies a string, including null character terminator

strcpy copies a string, including null character terminator

from source string to destination string. This function

from source string to destination string. This function

returns a pointer to destination string, or a NULL pointer on

returns a pointer to destination string, or a NULL pointer on

error. Its prototype is:

error. Its prototype is:

main()
{

main()
{
char sent1[100], sent2 [100];
strcpy (sent1, sent2 )
:

char sent1[100], sent2 [100];


strcpy (sent1, sent2 )
:

Refer to Appendix 7-9, 7-10 and 7-11 for examples

Refer to Appendix 7-9, 7-10 and 7-11 for examples

strncpy

strncpy

Outcome 7: Array, Pointers and Character String


7-20

Outcome 7: Array, Pointers and Character String


7-20

Character Strings

strcmp

Outcome 7: Array, Pointers and Character String


7-21

Character Strings

strcmp

Outcome 7: Array, Pointers and Character String


7-21

Character Strings

Character Strings

strncmp

strncmp

strstr

strstr

Refer to Appendix 7-15 to 7-24 for more examples

Refer to Appendix 7-15 to 7-24 for more examples

Outcome 7: Array, Pointers and Character String


7-22

Outcome 7: Array, Pointers and Character String


7-22

Summary
This chapter at a

Summary

glance

In this chapter, we studied one-dimensional arrays and

This chapter at a

two-dimensional arrays.

glance

Arrays are a built-in C-data type. Hence, we dont have

two-dimensional arrays.

Arrays are a built-in C-data type. Hence, we dont have

to declare them as data types; all we have to do is

to declare them as data types; all we have to do is

declare variables as arrays. We studied the C rules to

declare variables as arrays. We studied the C rules to

declare arrays, to initialize them and to access array

declare arrays, to initialize them and to access array

elements.

elements.

In C, there is a close relationship between arrays and

In C, there is a close relationship between arrays and

pointers. We learned about pointer, which can be used as

pointers. We learned about pointer, which can be used as

an alternative technique to process arrays.

an alternative technique to process arrays.

Two common operations on lists stored in arrays are

sorting and searching.

In this chapter, we studied one-dimensional arrays and

Next, we focused on strings, which is another structured

Two common operations on lists stored in arrays are


sorting and searching.

Next, we focused on strings, which is another structured

data type. C does not support strings as a data type.

data type. C does not support strings as a data type.

However, we can use character arrays to represent

However, we can use character arrays to represent

strings. We discussed string declaration, compile-time

strings. We discussed string declaration, compile-time

initialization, and input and output.

initialization, and input and output.

C relies on the standard string manipulation functions of

C relies on the standard string manipulation functions of

its string handling library to process strings. We

its string handling library to process strings. We

familiarize ourselves with many string manipulation

familiarize ourselves with many string manipulation

functions.

functions.

Outcome 7: Array, Pointers and Character String


7-23

Outcome 7: Array, Pointers and Character String


7-23

Outcome 8

Outcome 8

Structure and Function

Structure and Function

Introduction and Objectives


Objective

Introduction and Objectives

In this chapter you will learn about:

Objective

In this chapter you will learn about:

Structure data type and structure

Structure data type and structure

C Functions

C Functions

o Function Definitions

o Function Definitions

o Function Declarations

o Function Declarations

o Function calls

o Function calls

C Functions with parameters

C Functions with parameters

o Formal and actual parameters


o Defining

and

declaring

o Formal and actual parameters


functions

with

o Defining

parameters

and

declaring

functions

with

parameters

o Calling function s with parameters

o Calling function s with parameters

o Sending input to functions; parameter passing by

o Sending input to functions; parameter passing by

value

Outcome 8: Structure and Function

value

Outcome 8: Structure and Function


8-1

8-1

Introduction to Structure

Introduction to Structure

A STRUCTURE is a collection of one or more variables

A STRUCTURE is a collection of one or more variables

grouped under a single name for easy manipulation. The

grouped under a single name for easy manipulation. The

variables in a structure, unlike those in an array, can be of

variables in a structure, unlike those in an array, can be of

different variable types

different variable types

Revision

int student[100] ;

Revision

int student[100] ;

(1-Dimensional

The above declaration indicates that 100 memory locations

(1-Dimensional

The above declaration indicates that 100 memory locations

Array)

called Manager are reserved for the program to store the

Array)

called Manager are reserved for the program to store the

integer number. (Assume that the integer number indicates

integer number. (Assume that the integer number indicates

the batch no of respective student).

the batch no of respective student).

Study the code in Appendix 8-1 for revision in array


Differences

between Array &


STRUCTURE

Study the code in Appendix 8-1 for revision in array

Array does not allow having different data types in a

Differences

single array.

between Array &

STRUCTURE allows having different data types in a


single structure.

Thus, it can be considered as

combination of multiple arrays with different data types.

Outcome 8: Structure and Function

STRUCTURE

Array does not allow having different data types in a


single array.

STRUCTURE allows having different data types in a


single structure.

combination of multiple arrays with different data types.

Outcome 8: Structure and Function


8-2

Thus, it can be considered as

8-2

Introduction to Structure
Revision (Array)

In order to store the name of 100 students into an array,

Introduction to Structure
Revision (Array)

In order to store the name of 100 students into an array,

we need to create a 2-dimensional array to allocate the

we need to create a 2-dimensional array to allocate the

name of 100 students.

name of 100 students.

Name of manager is considered as a string. Thus, the


declaration is

Name of manager is considered as a string. Thus, the


declaration is

In order to store CGPA of 100 students into an array, we

In order to store CGPA of 100 students into an array, we

need to create a 1-dimensional array to allocate the CGPA

need to create a 1-dimensional array to allocate the CGPA

of 100 students.

of 100 students.

The CGPA is a float number. Thus, the declaration is

The CGPA is a float number. Thus, the declaration is

float student_CGPA [101];

float student_CGPA [101];

In order to store the batch no. of 100 students into an array,

In order to store the batch no. of 100 students into an array,

we need to create a 1-dimensional array to allocate the batch

we need to create a 1-dimensional array to allocate the batch

no. of 100 students.

no. of 100 students.

The batch no. is an integer number. Thus, the declaration is

The batch no. is an integer number. Thus, the declaration is

int student_batchno [101];

int student_batchno [101];

The programmer is required to declare 3 different

The programmer is required to declare 3 different

arrays to store the name of the students, their

arrays to store the name of the students, their

respective batch no. and CGPA.

respective batch no. and CGPA.

These 3 information are isolated from each other

These 3 information are isolated from each other

because they are stored in 3 different arrays in the

because they are stored in 3 different arrays in the

memory location of PC.

memory location of PC.

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-3

8-3

Introduction to Structure
STRUCTURE

The use of STRUCTURE will group these 3 information (3


arrays) to become a structure.

Declaration of STRUCTURE

Introduction to Structure
STRUCTURE

The use of STRUCTURE will group these 3 information (3


arrays) to become a structure.

Declaration of STRUCTURE

After declaring a STRUCTURE type, we may declare

After declaring a STRUCTURE type, we may declare

variables that are of that type. A STRUCTURE variable

variables that are of that type. A STRUCTURE variable

declaration requires:

declaration requires:

1. the keyword struct

1. the keyword struct

2. the structure type name; and

2. the structure type name; and

3. a list of variable names separate by semicolon

3. a list of variable names separate by semicolon

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-4

8-4

Introduction to Structure

Introduction to Structure

Input

scanf(%s, student[1].name);

Input

scanf(%s, student[1].name);

manipulation of

scanf(%s,student[2].name);

manipulation of

scanf(%s,student[2].name);

STRUCTURE

STRUCTURE
scanf(%d, &student[1].batchno);

scanf(%d, &student[1].batchno);

scanf(%d, &student[2].batchno);

scanf(%d, &student[2].batchno);

scanf(%f,&student[1].CGPA);

scanf(%f,&student[1].CGPA);

scanf(%f,&student[2].CGPA);

scanf(%f,&student[2].CGPA);

Output

printf(%s, student[1].name);

Output

printf(%s, student[1].name);

manipulation of

printf(%s,student[2].name);

manipulation of

printf(%s,student[2].name);

STRUCTURE

printf(%d, student[1].batchno);

STRUCTURE

printf(%d, student[1].batchno);

printf(%d, student[2].batchno);

printf(%d, student[2].batchno);

printf(%f,student[1].CGPA);

printf(%f,student[1].CGPA);

printf(%f,student[2].CGPA);

printf(%f,student[2].CGPA);

Refer to Appendix 8-2 and 8-3

Refer to Appendix 8-2 and 8-3

Declaring Nested

Members of a STRUCTURE declaration can be of any type,

Declaring Nested

Members of a STRUCTURE declaration can be of any type,

STRUCTURE

including

STRUCTURE

including

another

STRUCTURE

variable.

Such

another

STRUCTURE

variable.

Such

STRUCTURE type is called nested. An example is given

STRUCTURE type is called nested. An example is given

below.

below.

Suppose we have the STRUCTURE declaration:

Suppose we have the STRUCTURE declaration:

struct faculty_name
{
char last_name_initial;
char last_name_initial;
};
/* end struct faculty_name */

struct faculty_name
{
char last_name_initial;
char last_name_initial;
};
/* end struct faculty_name */

We can then use this structure type and rewrite the structure

We can then use this structure type and rewrite the structure

declaration.

declaration.

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-5

8-5

Introduction to Structure

Introduction to Structure

struct faculty
{
int faculty_idno;
struct faculty_name name_initials;
int age;
char sex;
float salary;
};
/* end struct faculty */

struct faculty
{
int faculty_idno;
struct faculty_name name_initials;
int age;
char sex;
float salary;
};
/* end struct faculty */

In this declaration, member name_initials is STRUCTURE

In this declaration, member name_initials is STRUCTURE

variable of type struct faculty_name. Therefore, the

variable of type struct faculty_name. Therefore, the

STRUCTURE type faculty has now become a nested

STRUCTURE type faculty has now become a nested

STRUCTURE type.

STRUCTURE type.

In declaring a nested STRUCTURE type, we should be

In declaring a nested STRUCTURE type, we should be

careful to place the declaration of the inner STRUCTURE

careful to place the declaration of the inner STRUCTURE

type before the nested STRUCTURE type. If the inner type

type before the nested STRUCTURE type. If the inner type

will be used only in a nested STRUCTURE type, the two

will be used only in a nested STRUCTURE type, the two

declarations can be combined. Here is an example:

declarations can be combined. Here is an example:

The STRUCTURE type faculty can be written as:

The STRUCTURE type faculty can be written as:

struct faculty
{
int faculty_idno;
struct
{
char last_name_initial;
char first_name_initial;
} name_initials;
/*end struct */

struct faculty
{
int faculty_idno;
struct
{
char last_name_initial;
char first_name_initial;
} name_initials;
/*end struct */

int age;
char sex;
float salary;
};
/* end struct faculty */

Outcome 8: Structure and Function

int age;
char sex;
float salary;
};
/* end struct faculty */

Outcome 8: Structure and Function


8-6

8-6

Introduction to Structure

Introduction to Structure

Advantage of

One major advantage of a STRUCTURE is to copy

Advantage of

One major advantage of a STRUCTURE is to copy

STRUCTURE

information between structures of the same type with a

STRUCTURE

information between structures of the same type with a

REMEMBER...

simple equation statement

simple equation statement

Refer to Appendix 8-4

Refer to Appendix 8-4

Place semicolon after the variables name in the declaration

REMEMBER...

of STRUCTURE

Place semicolon after the variables name in the declaration


of STRUCTURE

The compiler prompts a message Declaration


syntax error.

The compiler prompts a message Declaration


syntax error.

STRUCTURE

The format of STRUCTURE within STRUCTURE is:

STRUCTURE

The format of STRUCTURE within STRUCTURE is:

within

struct particular {
char name[100];
int studentID;
float CGPA;
};

within

struct particular {
char name[100];
int studentID;
float CGPA;
};

STRUCTURE

STRUCTURE

struct HND {
int batchno;
int no_of_student_EE;
int no_of_student_MM;
struct particular EE_student[5];
struct particular MM_student[5];
}batch[10];

struct HND {
int batchno;
int no_of_student_EE;
int no_of_student_MM;
struct particular EE_student[5];
struct particular MM_student[5];
}batch[10];

Manipulation of

The input and output manipulation of STRUCTURE within

Manipulation of

The input and output manipulation of STRUCTURE within

STRUCTURE

STRUCTURE needs two dot operators.

STRUCTURE

STRUCTURE needs two dot operators.

within

scanf("%d",&batch[1].EE_student[1].studentID);

STRUCTURE

within

scanf("%d",&batch[1].EE_student[1].studentID);

STRUCTURE
scanf("%s",batch[1].EE_student[1].name);

scanf("%s",batch[1].EE_student[1].name);

scanf("%f",&batch[1].EE_student[1].CGPA);

scanf("%f",&batch[1].EE_student[1].CGPA);

Refer Appendix 8-5 to 8-8

Outcome 8: Structure and Function

Refer Appendix 8-5 to 8-8

Outcome 8: Structure and Function


8-7

8-7

Introduction to Structure
REMEMBER

Place the sub-STRUCTURE in front of the main structure.

The compiler prompts a message Undefined

Introduction to Structure
REMEMBER

Place the sub-STRUCTURE in front of the main structure.

structure .

Outcome 8: Structure and Function

The compiler prompts a message Undefined


structure .

Outcome 8: Structure and Function


8-8

8-8

Function
Modular Design

Function
A variable strategy to break down the complex program into

Modular Design

A variable strategy to break down the complex program into

several smaller modules.

several smaller modules.

These modules are then combined to form a complete

These modules are then combined to form a complete

program.

program.

Advantages of

Easier to develop.

Advantages of

Easier to develop.

modular design

Easier to debug the program.

modular design

Easier to debug the program.

Programs can be developed by several programmers.

Programs can be developed by several programmers.

Modules can be used in several places in the same

Modules can be used in several places in the same

program and in other programs.

Requirements for

A module should be relatively small.

modules

A module should have one entry point and one exit

program and in other programs.

Requirements for

A module should be relatively small.

modules

A module should have one entry point and one exit

point.

point.

A module should perform a single, well-defined task.

A module should perform a single, well-defined task.

Function

A function is a subprogram that is an implementation of a

Function

A function is a subprogram that is an implementation of a

definitions

logical module in a modular program. Its definition consists

definitions

logical module in a modular program. Its definition consists

of

of
1. a function type

1. a function type

2. a function name

2. a function name

3. an optional list of formal parameters enclosed in

3. an optional list of formal parameters enclosed in

parentheses
4. a compound statements; function body

Outcome 8: Structure and Function

parentheses
4. a compound statements; function body

Outcome 8: Structure and Function


8-9

8-9

Function

Function

Syntax of header

Syntax of header

Example of header

Example of header

Function Body

Function Body

Return to the
calling function
without taking
any data

Return to the
calling function
without taking
any data

Invoking a

Invoking a

function

function

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-10

8-10

Function
Control flow
between calling
and called
function

void max( int sum )


{
int large;

return; }

Function
Control flow
between calling
and called
function

void max( int sum )


{
int large;

return; }

main( )
{
int x, y z, total, largest;

max (total)
..
}

main( )
{
int x, y z, total, largest;

max (total)
..
}

Indicate that the content hold by variable total is copied to

Indicate that the content hold by variable total is copied to

the memory location called sum

the memory location called sum

Relationship of parameters and arguments

Relationship of parameters and arguments

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-11

8-11

Function

Function

int max(int a [ ], int b[ ][100], int c)


{
int max;

return (largest);
}

int max(int a [ ], int b[ ][100], int c)


{
int max;

return (largest);
}

main( )
{
int x [100], y[100][100],z ;

result=max ( x , y , z);
..
}

main( )
{
int x [100], y[100][100],z ;

result=max ( x , y , z);
..
}

Refer to 8-8 to 8-11 for examples. Remember, function

Refer to 8-8 to 8-11 for examples. Remember, function

can only return a single value, not an array

can only return a single value, not an array

Refer to Appendix 8-12 to 8-14 for more examples.

Refer to Appendix 8-12 to 8-14 for more examples.

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-12

8-12

Function

Function

Functions that

If the function we are designing is expected to produce and

Functions that

If the function we are designing is expected to produce and

return values

return only one value, we can use the function name for this

return values

return only one value, we can use the function name for this

purpose. In this case, the function name must have a return

purpose. In this case, the function name must have a return

type other than void.

type other than void.

The return type is any data type, such as int, double, or char,

The return type is any data type, such as int, double, or char,

that C supports.

that C supports.

The return statement

The return statement

A function designed to return a value under its name must

A function designed to return a value under its name must

contain at least one return statement in its body. The syntax

contain at least one return statement in its body. The syntax

of the return statement is simple; it has the keyword return,

of the return statement is simple; it has the keyword return,

followed by a return expression. The return expression must

followed by a return expression. The return expression must

produce a value consistent with the type of the function in

produce a value consistent with the type of the function in

which the return statement appears.

which the return statement appears.

It is this value that is returned under the function name to

It is this value that is returned under the function name to

the calling program. Also, the return statement terminates

the calling program. Also, the return statement terminates

the execution of the function and takes the program control

the execution of the function and takes the program control

back to the calling program.

back to the calling program.

If the return type of a function definition is missing, the

If the return type of a function definition is missing, the

default is int. However, if a function is not intended to

default is int. However, if a function is not intended to

return a value under its name, its return type must be void.

return a value under its name, its return type must be void.

Function with

When a function calls another function to perform a task, it

Function with

When a function calls another function to perform a task, it

parameters

may also pass data to it as a latters input. After completing

parameters

may also pass data to it as a latters input. After completing

its task, the called function may pass data back to the calling

its task, the called function may pass data back to the calling

function as its output. There are 3 ways through which

function as its output. There are 3 ways through which

functions can communicate data:

functions can communicate data:

1. through global variables

1. through global variables

2. by returning a value under a function name

2. by returning a value under a function name

3. by using parameters

3. by using parameters

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-13

8-13

Function

Function

Use a global

By declaring a variable before the function main, will make

Use a global

By declaring a variable before the function main, will make

variables between

the variable global and can be use by all functions.

variables between

the variable global and can be use by all functions.

functions

/* Global variables: */
int i; double j; int k;

functions

/* Global variables: */
int i; double j; int k;

void main()
{

void main()
{

Use of parameters

A non-void function can return a value under its name to a

Use of parameters

A non-void function can return a value under its name to a

between functions

function that calls it, and such a value would be a function

between functions

function that calls it, and such a value would be a function

output. If a function requires input data to be passed to it by

output. If a function requires input data to be passed to it by

the calling function, and if we are not to use global variables

the calling function, and if we are not to use global variables

for this purpose, then we must resort to function parameters.

for this purpose, then we must resort to function parameters.

Rules for parameter passing by value:

Rules for parameter passing by value:

1. In parameter passing by value, the actual and formal

1. In parameter passing by value, the actual and formal

parameters must be of similar types.

parameters must be of similar types.

2. The formal parameters must be declared in the function


definition as regular variables, not as pointer variables.
3. The actual parameters in functions calls can be
constants, variables or expressions.

2. The formal parameters must be declared in the function


definition as regular variables, not as pointer variables.
3. The actual parameters in functions calls can be
constants, variables or expressions.

4. At the time the program control passes to the called

4. At the time the program control passes to the called

function, a copy of each actual parameter is made in the

function, a copy of each actual parameter is made in the

memory

memory

location

for

the

corresponding

formal

location

for

the

corresponding

formal

parameter. Any changes made by the called function on

parameter. Any changes made by the called function on

this copy will not be reflected in the corresponding

this copy will not be reflected in the corresponding

actual parameter. Therefore, parameter passing by value

actual parameter. Therefore, parameter passing by value

can be used only for supplying input to a called

can be used only for supplying input to a called

function.

function.

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-14

8-14

Calling Functions

Function

Function

5. Since the called function cannot access the memory

5. Since the called function cannot access the memory

location of the actual parameters in the data area of the

location of the actual parameters in the data area of the

calling function, the actual parameters are protected

calling function, the actual parameters are protected

against

against

inadvertent

alterations.

Hence,

whenever

inadvertent

alterations.

Hence,

whenever

possible, parameters passing by value should be

possible, parameters passing by value should be

preferred to parameter passing by pointers.

preferred to parameter passing by pointers.

Functions in C language that have arguments can be called

Calling Functions

Functions in C language that have arguments can be called

by using either one of these method:

by using either one of these method:

By Value

By Value

By Reference

By Reference

By Value

By Value

Values of variables in Called Function do not get affected

Values of variables in Called Function do not get affected

when arguments are passed by Value

when arguments are passed by Value

Eg

Eg

void addition(int Num1, int Num2)


{
Num1=10;
Num2=20;
printf(In Void Addition, Num 1
and Num2 are %d and %d,
Num1,Num2);
}

void addition(int Num1, int Num2)


{
Num1=10;
Num2=20;
printf(In Void Addition, Num 1
and Num2 are %d and %d,
Num1,Num2);
}

void main()
{
int a,b;
a=1;
b=2;
addition(a,b);
printf(In void main(), a and b are %d and %d,a,b);
}

void main()
{
int a,b;
a=1;
b=2;
addition(a,b);
printf(In void main(), a and b are %d and %d,a,b);
}

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-15

8-15

Function

Function

Output: In void Addition, Num1 and Num2 are 10 and 20

Output: In void Addition, Num1 and Num2 are 10 and 20

In void main() a and b are 1 and 2

In void main() a and b are 1 and 2

When arguments are passed by Value, the called function

When arguments are passed by Value, the called function

creates a new variable of the same data type (parameters). It

creates a new variable of the same data type (parameters). It

then copies the argument values into it. By Value is useful

then copies the argument values into it. By Value is useful

when you do not need to modify the values of the original

when you do not need to modify the values of the original

variables in the calling function

variables in the calling function

By Reference

By Reference

A reference is just like an alternate name for the argument

A reference is just like an alternate name for the argument

that is passed. You need to use an ampersand (&) following

that is passed. You need to use an ampersand (&) following

the data type of the argument.

the data type of the argument.

Eg:

Eg:

void addition(int &Num1, int &Num2)


{
Num1=10;
Num2=20;
printf(In Void Addition, Num 1
and Num2 are %d and %d,
Num1,Num2);
}

void addition(int &Num1, int &Num2)


{
Num1=10;
Num2=20;
printf(In Void Addition, Num 1
and Num2 are %d and %d,
Num1,Num2);
}

void main()
{
int a,b;
a=1;
b=2;
addition(a,b);
printf(In void main(), a and b are %d and %d,a,b);
}

void main()
{
int a,b;
a=1;
b=2;
addition(a,b);
printf(In void main(), a and b are %d and %d,a,b);
}

Output: In void Addition, Num1 and Num2 are 10 and 20


In void main() a and b are 10 and 20

Output: In void Addition, Num1 and Num2 are 10 and 20


In void main() a and b are 10 and 20

By Reference is useful if the user wants to keep track the

By Reference is useful if the user wants to keep track the

changes that are made to the values in the variables.

changes that are made to the values in the variables.

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-16

8-16

Summary
This chapter at a

Summary

glance

In this chapter, we undertook a discussion of structure.

This chapter at a

A STRUCTURE is a user-defined data type that can be

glance

A STRUCTURE is a user-defined data type that can be

used to represent a collection of related data items of

used to represent a collection of related data items of

different types.

different types.

We

studied

STRUCTURE

type

and

variable

studied

STRUCTURE

type

and

variable

declarations, how STRUCTURE members can be

accessed, how they can be initialized, and what

accessed, how they can be initialized, and what

operations can be used on STRUCTURE.

operations can be used on STRUCTURE.

A modular program has a structure that consists of its

Each function must be defined, appropriately declared,

Although we can use global variables to pass data to

A modular program has a structure that consists of its


modules and the called by relationship among them.

and called by other functions.

We

declarations, how STRUCTURE members can be

modules and the called by relationship among them.

In this chapter, we undertook a discussion of structure.

Each function must be defined, appropriately declared,


and called by other functions.

Although we can use global variables to pass data to

functions, this method has its drawback and is not

functions, this method has its drawback and is not

recommended.

recommended.

The usual way functions to communicate data are

The usual way functions to communicate data are

through function parameters. In a function definition,

through function parameters. In a function definition,

we may have formal parameters that must be variables.

we may have formal parameters that must be variables.

In calling a function with parameters, we must use

In calling a function with parameters, we must use

actual parameters, which may be constants, variables or

actual parameters, which may be constants, variables or

expressions.

expressions.

Outcome 8: Structure and Function

Outcome 8: Structure and Function


8-17

8-17

Appendix

Appendix

C Keywords/ Reserved words

C Keywords/ Reserved words

auto

extern

static

auto

extern

static

break

float

struct

break

float

struct

case

for

switch

case

for

switch

char

goto

union

char

goto

union

const

if

unsigned

const

if

unsigned

continue

int

void

continue

int

void

default

long

volatile

default

long

volatile

do

registertypedef

while

do

registertypedef

while

double

return

signed

double

return

signed

else

short

sizeof

else

short

sizeof

enum

enum

Remarks

Remarks

All programs included in this appendix are tested using Microsoft Visual C/C++ 6.0
The project type used is Win32 Console Application
o File > New > Projects > Win32 Console Application
o Type in the project name and indicate the location
o Select A simple application
If these programs were to run on other C compilers; they may not be able to run as
expected because of different libraries are required/included to support the compilation
o If want the programs to be portable between different compilers, some
modification may desire

All programs included in this appendix are tested using Microsoft Visual C/C++ 6.0
The project type used is Win32 Console Application
o File > New > Projects > Win32 Console Application
o Type in the project name and indicate the location
o Select A simple application
If these programs were to run on other C compilers; they may not be able to run as
expected because of different libraries are required/included to support the compilation
o If want the programs to be portable between different compilers, some
modification may desire

Appendix Outcome 4-1

Appendix Outcome 4-1

Objective : To understand the structure of C program.

Objective : To understand the structure of C program.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
int a, b, c;

/* Variable declaration */
int a, b, c;

/* Promt user to enter value of a */


printf("Enter a number between 1 and 100: ");
/* Read in the value of a */
scanf("%d", &a);

/* Promt user to enter value of a */


printf("Enter a number between 1 and 100: ");
/* Read in the value of a */
scanf("%d", &a);

/* Promt user to enter value of b */


printf("Enter another number between 1 and 100: ");
/* Read in the value of b */
scanf("%d", &b);

/* Promt user to enter value of b */


printf("Enter another number between 1 and 100: ");
/* Read in the value of b */
scanf("%d", &b);

/* Multiply the value of a and b then assign to c */


c = a * b;

/* Multiply the value of a and b then assign to c */


c = a * b;

/* Print the value of a, b and c on screen */


printf("%d times %d = %d\n", a, b, c);

/* Print the value of a, b and c on screen */


printf("%d times %d = %d\n", a, b, c);

Appendix Outcome 4-2

Appendix Outcome 4-2

Objective : To understand the usage of printf command as literal text .

Objective : To understand the usage of printf command as literal text .

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Print out the string on screen */
printf("This program is to observe the function of printf command\n");
printf("The printf function is under the usage of literal text\n");

/* Print out the string on screen */


printf("This program is to observe the function of printf command\n");
printf("The printf function is under the usage of literal text\n");
}

Appendix Outcome 4-3

Appendix Outcome 4-3

Objective : To understand the usage of printf, scanf and conversion specifier


command.

Objective : To understand the usage of printf, scanf and conversion specifier


command.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
char c;
int a;
float b;

/* Variable declaration */
char c;
int a;
float b;

/* Prompt the user to enter character */


printf("Enter any character
: ");
/* Read in the character using character conversion specifier */
scanf ("%c", &c);

/* Prompt the user to enter character */


printf("Enter any character
: ");
/* Read in the character using character conversion specifier */
scanf ("%c", &c);

/* Prompt the user to enter float number */


printf("Enter any float number : ");
/* Read in the float number using conversion specifier */
scanf ("%f", &b);

/* Prompt the user to enter float number */


printf("Enter any float number : ");
/* Read in the float number using conversion specifier */
scanf ("%f", &b);

/* Promt the user to enter integer number */


printf("Enter any integer number : ");
/* Read in the integer number using conversion specifier */
scanf ("%d", &a);

/* Promt the user to enter integer number */


printf("Enter any integer number : ");
/* Read in the integer number using conversion specifier */
scanf ("%d", &a);

/* Print out the title */


printf("\n\n\nBelow is the list of data types entered\n");
printf("=========================================\n");

/* Print out the title */


printf("\n\n\nBelow is the list of data types entered\n");
printf("=========================================\n");

/* Print out the character entered */


printf("The CHARACTER you entered is %c\n", c);

/* Print out the character entered */


printf("The CHARACTER you entered is %c\n", c);

/* Print out the float number entered */

/* Print out the float number entered */

printf("The FLOAT NUMBER you entered is %.2f\n", b);

printf("The FLOAT NUMBER you entered is %.2f\n", b);

/* Print out the integer number entered */


printf("The INTEGER NUMBER you entered is %d\n", a);

/* Print out the integer number entered */


printf("The INTEGER NUMBER you entered is %d\n", a);

Explanation of the program:

Explanation of the program:

The function of this program is to receive a character, float number and integer number from the
keyboard (key in by the user) and place them into their respective memorys location called c, b
and a. The last three printf statements are to display the content inside the variable a, b and c.
This is to ensure that the data received is being stored into the respective location. If the data
received are successfully stored into their respective location, the data display out using the
printf command should be similar as the data key in by the user.

The function of this program is to receive a character, float number and integer number from the
keyboard (key in by the user) and place them into their respective memorys location called c, b
and a. The last three printf statements are to display the content inside the variable a, b and c.
This is to ensure that the data received is being stored into the respective location. If the data
received are successfully stored into their respective location, the data display out using the
printf command should be similar as the data key in by the user.

Appendix Outcome 4-4

Appendix Outcome 4-4

Objective : To understand different numeric data types

Objective : To understand different numeric data types

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
int
number1;
long
number2;
unsigned int number3;
unsigned short number4;
unsigned long number5;

/* Variable declaration */
int
number1;
long
number2;
unsigned int number3;
unsigned short number4;
unsigned long number5;

/* Prompt, read and print the integer value of number1 */


printf("Please enter any number : ");
scanf ("%d", &number1);
printf("The number you entered is %d\n", number1);

/* Prompt, read and print the integer value of number1 */


printf("Please enter any number : ");
scanf ("%d", &number1);
printf("The number you entered is %d\n", number1);

printf("\n");

printf("\n");

/* Prompt, read and print the signed value of number2 */


printf("Please enter any signed long decimal integer : ");
scanf ("%ld", &number2);
printf("The long number you entered is %ld\n", number2);

/* Prompt, read and print the signed value of number2 */


printf("Please enter any signed long decimal integer : ");
scanf ("%ld", &number2);
printf("The long number you entered is %ld\n", number2);

printf("\n");

printf("\n");

/* Prompt, read and print the unsigned integer value of number3 */


printf("Please enter any unsigned decimal integer : ");
scanf ("%u", &number3);
printf("The unsigned decimal integer you entered is %u\n", number3);

/* Prompt, read and print the unsigned integer value of number3 */


printf("Please enter any unsigned decimal integer : ");
scanf ("%u", &number3);
printf("The unsigned decimal integer you entered is %u\n", number3);

printf("\n");

printf("\n");

/* Prompt, read and print the unsigned short integer value of number4 */
printf("Please enter any unsigned short decimal integer : ");
scanf ("%u", &number4);
printf("The unsigned short decimal integer you entered is %u\n", number4);

/* Prompt, read and print the unsigned short integer value of number4 */
printf("Please enter any unsigned short decimal integer : ");
scanf ("%u", &number4);
printf("The unsigned short decimal integer you entered is %u\n", number4);

printf("\n");

printf("\n");

/* Prompt, read and print the unsigned long integer value of number5 */
printf("Please enter any unsigned long decimal integer : ");
scanf ("%lu", &number5);
printf("The unsigned long decimal integer you entered is %lu\n", number5);

/* Prompt, read and print the unsigned long integer value of number5 */
printf("Please enter any unsigned long decimal integer : ");
scanf ("%lu", &number5);
printf("The unsigned long decimal integer you entered is %lu\n", number5);

printf("\n");

printf("\n");

Appendix Outcome 4-5

Appendix Outcome 4-5

Objective : To understand the usage of %s and %c conversion specifiers

Objective : To understand the usage of %s and %c conversion specifiers

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
char a;
char b[20];

/* Variable declaration */
char a;
char b[20];

/* Print out the string */


printf("Character means ONLY one letter\n");
printf("String is a combination of MORE than one characters\n");

/* Print out the string */


printf("Character means ONLY one letter\n");
printf("String is a combination of MORE than one characters\n");

printf("\n");

printf("\n");

/* Prompt, read and print out the character of a */


printf("Please enter any character : ");
scanf ("%c", &a);
printf("The character you entered is %c\n", a);

/* Prompt, read and print out the character of a */


printf("Please enter any character : ");
scanf ("%c", &a);
printf("The character you entered is %c\n", a);

printf("\n");

printf("\n");

/* Prompt, read and print out the string of b */


printf("Please enter any string : ");
scanf ("%s", &b);
printf("The string you entered is %s\n", b);

/* Prompt, read and print out the string of b */


printf("Please enter any string : ");
scanf ("%s", &b);
printf("The string you entered is %s\n", b);

printf("\n");

printf("\n");

Appendix Outcome 4-6

Appendix Outcome 4-6

Objective : To understand the differences of signed character and unsigned


character.

Objective : To understand the differences of signed character and unsigned


character.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
signed char b;
unsigned char a;

/* Variable declaration */
signed char b;
unsigned char a;

/* Prompt, read and print the character of variable 'a' */


printf("Please enter any unsigned character : ");

/* Prompt, read and print the character of variable 'a' */


printf("Please enter any unsigned character : ");

/* Enter Alt + 254 */


scanf ("%c", &a);
printf("The character you entered has an ASCII value of %d\n", a);

/* Enter Alt + 254 */


scanf ("%c", &a);
printf("The character you entered has an ASCII value of %d\n", a);

/* Clean the previous input value from following variable */


fflush(stdin);

/* Clean the previous input value from following variable */


fflush(stdin);

/* Prompt, read and print the character of variable 'b' */


printf("\n\nPlease enter any signed character : ");

/* Prompt, read and print the character of variable 'b' */


printf("\n\nPlease enter any signed character : ");

/* Enter Alt + 254 */


scanf ("%c", &b);
printf("The character you entered has an ASCII value of %d\n", b);

/* Enter Alt + 254 */


scanf ("%c", &b);
printf("The character you entered has an ASCII value of %d\n", b);

Modification to observe the differences :

Modification to observe the differences :

Step 1 : Enter  (press ALT+254), the output will display 254 if a is declared as unsigned char.

Step 1 : Enter  (press ALT+254), the output will display 254 if a is declared as unsigned char.

Step 3 : Enter  (press ALT+254), the output will display -2 if once a is declared as signed
char.

Step 3 : Enter  (press ALT+254), the output will display -2 if once a is declared as signed
char.

Appendix Outcome 4-7

Appendix Outcome 4-7

Objective : To observe the usage of assignment operator

Objective : To observe the usage of assignment operator

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
int number1, number2;

/* Variable declaration */
int number1, number2;

/* Prompt and read the value of number1 */


printf("Please enter an integer for number1 : ");
scanf ("%d", &number1);

/* Prompt and read the value of number1 */


printf("Please enter an integer for number1 : ");
scanf ("%d", &number1);

/* Assign the value of number2 to number1 */


number1 = number2;

/* Assign the value of number2 to number1 */


number1 = number2;

/* Print out the value of number1 (undesired cause never assigned!) */


printf("The content of number2 is %d\n", number2);

/* Print out the value of number1 (undesired cause never assigned!) */


printf("The content of number2 is %d\n", number2);

/* Prompt and read the value of number1 */


printf("\n\nPlease enter again an integer for number1 : ");
scanf ("%d", &number1);

/* Prompt and read the value of number1 */


printf("\n\nPlease enter again an integer for number1 : ");
scanf ("%d", &number1);

/* Assign the value of number1 to number2 */


number2 = number1;

/* Assign the value of number1 to number2 */


number2 = number1;

/* Print out the value of number2 */


printf("The content of number2 is %d\n\n\n", number2);

/* Print out the value of number2 */


printf("The content of number2 is %d\n\n\n", number2);

10

10

Appendix Outcome 4-8

Appendix Outcome 4-8

Objective : To understand compound assignment operators, +=, - =,*= and /=

Objective : To understand compound assignment operators, +=, - =,*= and /=

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
int number = 10;

/* Variable declaration */
int number = 10;

/* Plus 5 to number */
number += 5;
/* Print out the value of number */
printf("Value of number added by 5 is %d\n\n", number);

/* Plus 5 to number */
number += 5;
/* Print out the value of number */
printf("Value of number added by 5 is %d\n\n", number);

/* Subtract 3 to number */
number -= 3;
/* Print out the value of number */
printf("Value of number subtracted by 3 is %d\n\n", number);

/* Subtract 3 to number */
number -= 3;
/* Print out the value of number */
printf("Value of number subtracted by 3 is %d\n\n", number);

/* Multiply by 3 to number */
number *= 3;
/* Print out the value of number */
printf("Value of number multiplied by 3 is %d\n\n", number);

/* Multiply by 3 to number */
number *= 3;
/* Print out the value of number */
printf("Value of number multiplied by 3 is %d\n\n", number);

/* Divide by 3 to number */
number /= 3;
/* Print out the value of number */
printf("Value of number divided by 3 is %d\n\n", number);

/* Divide by 3 to number */
number /= 3;
/* Print out the value of number */
printf("Value of number divided by 3 is %d\n\n", number);

11

11

Appendix Outcome 4-9

Appendix Outcome 4-9

Objective : To understand the differences of ++i and i++

Objective : To understand the differences of ++i and i++

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main function */

/* Main function */

main()
{

main()
{
/* Variable declaration */
int y, i = 3;

/* Variable declaration */
int y, i = 3;

/* Print out the title */


printf("When increasing the value with i++\n");
printf("==================================\n");
printf("\n");
printf("i = 3\n");
printf("y = i++\n");
printf("\n");

/* Print out the title */


printf("When increasing the value with i++\n");
printf("==================================\n");
printf("\n");
printf("i = 3\n");
printf("y = i++\n");
printf("\n");

/* Assign the value of i to y and then auto increase the value of i */

/* Assign the value of i to y and then auto increase the value of i */

y = i++;

y = i++;

/* Print out the values of i and y */


printf("The answer for i is %d\n", i);
printf("The answer for y is %d\n", y);
printf("The answer for i is %d\n", i);

/* Print out the values of i and y */


printf("The answer for i is %d\n", i);
printf("The answer for y is %d\n", y);
printf("The answer for i is %d\n", i);

i = 3;
printf("\n\n");

i = 3;
printf("\n\n");

/* Print out the title */


printf("When increasing the value with ++i\n");
printf("==================================\n");
printf("\n");
printf("i = 3\n");
printf("y = ++i\n");
printf("\n");

/* Print out the title */


printf("When increasing the value with ++i\n");
printf("==================================\n");
printf("\n");
printf("i = 3\n");
printf("y = ++i\n");
printf("\n");

12

12

/* Auto increase the value of i and then assign the value to y */

/* Auto increase the value of i and then assign the value to y */

y = ++i;

y = ++i;

/* Print out the values of i and y */


printf("The answer for i is %d\n", i);
printf("The answer for y is %d\n", y);
printf("The answer for i is %d\n", i);

/* Print out the values of i and y */


printf("The answer for i is %d\n", i);
printf("The answer for y is %d\n", y);
printf("The answer for i is %d\n", i);

Explanation of the program:

Explanation of the program:

From the above example, the command of i++ and ++i does not make any differences if the
assignment operator is not involved. If the assignment operator involves, such as y = i++ and y =
++i; there is a difference between the use of ++i or i++. The differences are listed above.

From the above example, the command of i++ and ++i does not make any differences if the
assignment operator is not involved. If the assignment operator involves, such as y = i++ and y =
++i; there is a difference between the use of ++i or i++. The differences are listed above.

13

13

Appendix Outcome 5-1

Appendix Outcome 5-1

Objective : To understand the usage of FOR control structure

Objective : To understand the usage of FOR control structure

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Main Function */

/* Main Function */

main()
{

main()
{
/* Variable declaration */
int count1, b;

/* Variable declaration */
int count1, b;

/* Print out the title of the looping contents */


printf("The values for 9 loops are as below\n");
printf("===================================\n");

/* Print out the title of the looping contents */


printf("The values for 9 loops are as below\n");
printf("===================================\n");

/* Go to a new line */
printf("\n");

/* Go to a new line */
printf("\n");

/* Declaration of "FOR" control structure with */


/* initialization, logical control and counter respectively */
for (count1 = 1; count1 < 10; ++count1)
{

/* Declaration of "FOR" control structure with */


/* initialization, logical control and counter respectively */
for (count1 = 1; count1 < 10; ++count1)
{

/* Add up the values for count1 with 2 then assign to b */


b = count1 + 2;

/* Add up the values for count1 with 2 then assign to b */


b = count1 + 2;

/* Print out the value of b in each loop */


printf("Loop %d : The value of count1 is %d\n", count1, b);

/* Print out the value of b in each loop */


printf("Loop %d : The value of count1 is %d\n", count1, b);

/* Space for 3 lines */


printf("\n\n\n");

/* Space for 3 lines */


printf("\n\n\n");

}
14

14

Appendix Outcome 5-2

Appendix Outcome 5-2

Objective : To understand FOR control structure with different variables

Objective : To understand FOR control structure with different variables

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Main Function */

/* Main Function */

main()
{

main()
{
/* Variable declaration */
int count1, count3 = 2, count4 = 1;

/* Variable declaration */
int count1, count3 = 2, count4 = 1;

/* Control structure for the "FOR" loop */


/* with different initial statement, condition and increment */
for (count1 = 1; count3 <= 22; count3 = count3 + 2)
{

/* Control structure for the "FOR" loop */


/* with different initial statement, condition and increment */
for (count1 = 1; count3 <= 22; count3 = count3 + 2)
{

/* Print out the value of count3 in each loop */


printf("Loop %d: The value for count3 is %d\n",count4,count3);

/* Print out the value of count3 in each loop */


printf("Loop %d: The value for count3 is %d\n",count4,count3);

/* Increace the value of count4 */


++count4;

/* Increace the value of count4 */


++count4;

printf("\n\n\n");

printf("\n\n\n");

15

15

Appendix Outcome 5-3

Appendix Outcome 5-3

Objective : To understand Nested FOR control structure

Objective : To understand Nested FOR control structure

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Main Function */

/* Main Function */

main()
{

main()
{
/* Variable declaration */
int count1, count2, b;

/* Variable declaration */
int count1, count2, b;

/* Print out the title for the looping contents */


printf("This is a test for Nested FOR Control Loop\n");
printf("==========================================\n");

/* Print out the title for the looping contents */


printf("This is a test for Nested FOR Control Loop\n");
printf("==========================================\n");

/* Go to a new line */
printf("\n");

/* Go to a new line */
printf("\n");

/* Control structure for the "FOR" loop */


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

/* Control structure for the "FOR" loop */


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

/* Print out the number of each loop */


printf("\nLoop %d : ", count1);

/* Print out the number of each loop */


printf("\nLoop %d : ", count1);

/* Control structure for the Nested "FOR" loop */


for (count2 = 1; count2 <= 5; ++count2)
{

/* Control structure for the Nested "FOR" loop */


for (count2 = 1; count2 <= 5; ++count2)
{

/* Multiply the values of count2 with 2 then assign to b */


b = 2 * count2;

/* Multiply the values of count2 with 2 then assign to b */


b = 2 * count2;

/* Print out the value of b in each loop */


printf("%d ", b);

/* Print out the value of b in each loop */


printf("%d ", b);

}
16

16

}
/* Space for 3 lines */
printf("\n\n\n");

/* Space for 3 lines */


printf("\n\n\n");

17

17

Appendix Outcome 5-4

Appendix Outcome 5-4

Objective : To understand WHILE control structure

Objective : To understand WHILE control structure

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Main Function */

/* Main Function */

main()
{

main()
{
/* Variable declaration */
int count1, b ;

/* Variable declaration */
int count1, b ;

/* Initialize count1 to value 1 */


count1 = 1;

/* Initialize count1 to value 1 */


count1 = 1;

/* Print out the title of the looping contents */


printf("The values for 9 loops are as below\n");
printf("===================================\n");

/* Print out the title of the looping contents */


printf("The values for 9 loops are as below\n");
printf("===================================\n");

/* Go to a new line */
printf("\n");

/* Go to a new line */
printf("\n");

/* Control structure for the "WHILE" loop */


while (count1 < 10)
{

/* Control structure for the "WHILE" loop */


while (count1 < 10)
{

/* Add up the value of count1 with 2 then assign to b */


b = count1 + 2;
/* Print out the value of b in each loop */
printf("Loop %d : The value of count1 is %d\n", count1, b);
/* Increase the value of count1 */
++count1;

/* Add up the value of count1 with 2 then assign to b */


b = count1 + 2;
/* Print out the value of b in each loop */
printf("Loop %d : The value of count1 is %d\n", count1, b);
/* Increase the value of count1 */
++count1;

/* Space for 3 lines */


printf("\n\n\n");

/* Space for 3 lines */


printf("\n\n\n");

}
18

18

Appendix Outcome 5-5

Appendix Outcome 5-5

Objective : To understand Nested WHILE control structure

Objective : To understand Nested WHILE control structure

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Main Function */

/* Main Function */

main()
{

main()
{
/* Variable declaration */
int count1, count2, b;

/* Variable declaration */
int count1, count2, b;

/* Print out the title for the looping contents */


printf("This is a test for Nested WHILE control loop\n");
printf("============================================\n");

/* Print out the title for the looping contents */


printf("This is a test for Nested WHILE control loop\n");
printf("============================================\n");

/* Go to a new line */
printf("\n");

/* Go to a new line */
printf("\n");

/* Initialize count1 to value 1 */


count1 = 1;

/* Initialize count1 to value 1 */


count1 = 1;

/* Control structure for the "WHILE" loop */


while (count1 <= 10)
{

/* Control structure for the "WHILE" loop */


while (count1 <= 10)
{

/* Print out the number of each loop */


printf("\nLoop %d : ", count1);

/* Print out the number of each loop */


printf("\nLoop %d : ", count1);

/* Initialize count2 to value 1 */


count2 = 1;

/* Initialize count2 to value 1 */


count2 = 1;

/* Control structure for the Nested "WHILE" loop */


while (count2 <= 5)
{

/* Control structure for the Nested "WHILE" loop */


while (count2 <= 5)
{

/* Multiply value of count2 with 2 then assign to b */


19

/* Multiply value of count2 with 2 then assign to b */


19

b = 2 * count2;

b = 2 * count2;

/* Print out the value of b in each loop */


printf(" %d", b);
/* Increase the value of count2 */
++count2;

/* Print out the value of b in each loop */


printf(" %d", b);
/* Increase the value of count2 */
++count2;

/* Increase the value of count1 */


++count1;

/* Increase the value of count1 */


++count1;

/* Space for 3 lines */


printf("\n\n\n");

/* Space for 3 lines */


printf("\n\n\n");

20

20

Appendix Outcome 5-6

Appendix Outcome 5-6

Objective : To understand DOWHILE control structure

Objective : To understand DOWHILE control structure

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Include directives */
#include "stdafx.h"
#include <stdio.h>

/* Main Function */

/* Main Function */

main()
{

main()
{
/* Variable declaration */
int count1, b;

/* Variable declaration */
int count1, b;

/* Print out the title of the looping contents */


printf("The values for 9 loops are as below\n");
printf("===================================\n");

/* Print out the title of the looping contents */


printf("The values for 9 loops are as below\n");
printf("===================================\n");

/* Go to a new line */
printf("\n");

/* Go to a new line */
printf("\n");

/* Initialize count1 to value 1 */


count1 = 1;

/* Initialize count1 to value 1 */


count1 = 1;

/* Control structure for the "DO... WHILE" loop */

/* Control structure for the "DO... WHILE" loop */

do
{

do
{
/* Add up the value of count1 with 2 then assign to b */
b = count1 + 2;
/* Print out the values of b in each loop */
printf("Loop %d : The value of count1 is %d\n", count1, b);
/* Increase the value of count1 */
++count1;

/* Add up the value of count1 with 2 then assign to b */


b = count1 + 2;
/* Print out the values of b in each loop */
printf("Loop %d : The value of count1 is %d\n", count1, b);
/* Increase the value of count1 */
++count1;

} while (count1 < 10);

} while (count1 < 10);

/* Space for 3 lines */


printf("\n\n\n");

/* Space for 3 lines */


printf("\n\n\n");

}
21

21

Appendix Outcome 6-1

Appendix Outcome 6-1

Objective : To understand the if command.

Objective : To understand the if command.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main function

// Main function

main()
{

main()
{
// Variable declaration
float ass_1, ass_2, ass_3, average;

// Variable declaration
float ass_1, ass_2, ass_3, average;

// Read in the marks for assessments


printf("Please enter marks for 3 assessments\n\n");
printf("Mark for Assessment 1 : ");
scanf ("%f", &ass_1);
printf("Mark for Assessment 2 : ");
scanf ("%f", &ass_2);
printf("Mark for Assessment 3 : ");
scanf ("%f", &ass_3);

// Read in the marks for assessments


printf("Please enter marks for 3 assessments\n\n");
printf("Mark for Assessment 1 : ");
scanf ("%f", &ass_1);
printf("Mark for Assessment 2 : ");
scanf ("%f", &ass_2);
printf("Mark for Assessment 3 : ");
scanf ("%f", &ass_3);

// Calculate the average


average = (ass_1 + ass_2 + ass_3) / 3;

// Calculate the average


average = (ass_1 + ass_2 + ass_3) / 3;

// Check if average is in the range of 61 to 100


if ((average > 60) && (average <= 100))
printf("\n\nYou have obtained the validation of competancy!\n\n\n");

// Check if average is in the range of 61 to 100


if ((average > 60) && (average <= 100))
printf("\n\nYou have obtained the validation of competancy!\n\n\n");

22

22

Appendix Outcome 6-2

Appendix Outcome 6-2

Objective : To understand the multiple if statement.

Objective : To understand the multiple if statement.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main function

// Main function

main()
{

main()
{
// Variable declaration
float ass_1, ass_2, ass_3, average;

// Variable declaration
float ass_1, ass_2, ass_3, average;

// Read in marks for 3 assessments


printf("Please enter marks for 3 assessments\n\n");
printf("Mark for Assessment 1 : ");
scanf ("%f", &ass_1);
printf("Mark for Assessment 2 : ");
scanf ("%f", &ass_2);
printf("Mark for Assessment 3 : ");
scanf ("%f", &ass_3);

// Read in marks for 3 assessments


printf("Please enter marks for 3 assessments\n\n");
printf("Mark for Assessment 1 : ");
scanf ("%f", &ass_1);
printf("Mark for Assessment 2 : ");
scanf ("%f", &ass_2);
printf("Mark for Assessment 3 : ");
scanf ("%f", &ass_3);

// Calculate the average


average = (ass_1 + ass_2 + ass_3) / 3;
// Print out the value of average
printf("\n\nThe aveage is %.2f\n\n", average);

// Calculate the average


average = (ass_1 + ass_2 + ass_3) / 3;
// Print out the value of average
printf("\n\nThe aveage is %.2f\n\n", average);

// Check whether average is in range 85 to 100


if (average >= 85 && average <= 100)
printf("You obtained a Distinction!\n\n\n");

// Check whether average is in range 85 to 100


if (average >= 85 && average <= 100)
printf("You obtained a Distinction!\n\n\n");

// Check whether average is in range 70 to 84


if (average >= 70 && average < 85)
printf("You obtained a Merit!\n\n\n");

// Check whether average is in range 70 to 84


if (average >= 70 && average < 85)
printf("You obtained a Merit!\n\n\n");

// Check whether average is in range 50 to 69


if (average >= 50 && average < 70)

// Check whether average is in range 50 to 69


if (average >= 50 && average < 70)

23

23

printf("You obtained a Pass!\n\n\n");

printf("You obtained a Pass!\n\n\n");

// Check whether average is in range less than 50


if (average < 50)
printf("You obtained a Not Yet Pass!\n\n\n");
}

// Check whether average is in range less than 50


if (average < 50)
printf("You obtained a Not Yet Pass!\n\n\n");
}

24

24

Appendix Outcome 6-3

Appendix Outcome 6-3

Objective : To understand the Nested if statement.

Objective : To understand the Nested if statement.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main function

// Main function

main()
{

main()
{
// Variable declarations
float ass_1, ass_2, ass_3, average;
char competent;

// Variable declarations
float ass_1, ass_2, ass_3, average;
char competent;

// Read in marks for 3 assessments


printf("Please enter marks for 3 assessments\n\n");
printf("Mark for Assessment 1 : ");
scanf ("%f", &ass_1);
printf("Mark for Assessment 2 : ");
scanf ("%f", &ass_2);
printf("Mark for Assessment 3 : ");
scanf ("%f", &ass_3);

// Read in marks for 3 assessments


printf("Please enter marks for 3 assessments\n\n");
printf("Mark for Assessment 1 : ");
scanf ("%f", &ass_1);
printf("Mark for Assessment 2 : ");
scanf ("%f", &ass_2);
printf("Mark for Assessment 3 : ");
scanf ("%f", &ass_3);

// Calculate the average


average = (ass_1 + ass_2 + ass_3) / 3;
// Print out the value of average
printf("\n\nThe average is %.2f\n\n", average);

// Calculate the average


average = (ass_1 + ass_2 + ass_3) / 3;
// Print out the value of average
printf("\n\nThe average is %.2f\n\n", average);

// Read in the status of competancy


printf("Did you obtain the validation of competency in Practical work? : ");
fflush(stdin);
scanf ("%c", &competent);

// Read in the status of competancy


printf("Did you obtain the validation of competency in Practical work? : ");
fflush(stdin);
scanf ("%c", &competent);

// Check whether competent is equal to "y" or "Y"


if ((competent == 'y') || (competent == 'Y'))
{

// Check whether competent is equal to "y" or "Y"


if ((competent == 'y') || (competent == 'Y'))
{

25

25

// Check whether average is in range 85 to 100


if (average >= 85 && average <= 100)
printf("\nYou obtained a Distinction!\n\n\n");

// Check whether average is in range 85 to 100


if (average >= 85 && average <= 100)
printf("\nYou obtained a Distinction!\n\n\n");

// Check whether average is in range 70 to 84


if (average >= 70 && average < 85)
printf("\nYou obtained a Merit!\n\n\n");

// Check whether average is in range 70 to 84


if (average >= 70 && average < 85)
printf("\nYou obtained a Merit!\n\n\n");

// Check whether average is in range 50 to 69


if (average >= 50 && average < 70)
printf("\nYou obtained a Pass!\n\n\n");

// Check whether average is in range 50 to 69


if (average >= 50 && average < 70)
printf("\nYou obtained a Pass!\n\n\n");

// Check whether average is in range less than 50


if (average < 50)
printf("\nYou obtained a Not Yet Pass!\n\n\n");

// Check whether average is in range less than 50


if (average < 50)
printf("\nYou obtained a Not Yet Pass!\n\n\n");

// Check whether competent is equal to "n" or "N"


if ((competent == 'n') || (competent == 'N'))
printf("\nSorry! You get a NYP because you don't competent in Practical
work.\n\n\n");

// Check whether competent is equal to "n" or "N"


if ((competent == 'n') || (competent == 'N'))
printf("\nSorry! You get a NYP because you don't competent in Practical
work.\n\n\n");

26

26

Appendix Outcome 6-4

Appendix Outcome 6-4

Objective : To understand IFELSE control structure

Objective : To understand IFELSE control structure

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
float ass1, ass2, ass3, average;
char competent;

// Variable declaration
float ass1, ass2, ass3, average;
char competent;

// Read in marks for each assessment


printf("Please enter the mark for 3 assessment\n");
printf("Key in mark for Assessment 1 : ");
scanf ("%f", &ass1);
printf("Key in mark for Assessment 2 : ");
scanf ("%f", &ass2);
printf("Key in mark for Assessment 3 : ");
scanf ("%f", &ass3);

// Read in marks for each assessment


printf("Please enter the mark for 3 assessment\n");
printf("Key in mark for Assessment 1 : ");
scanf ("%f", &ass1);
printf("Key in mark for Assessment 2 : ");
scanf ("%f", &ass2);
printf("Key in mark for Assessment 3 : ");
scanf ("%f", &ass3);

// Calculate the average mark


average = (ass1 + ass2 + ass3) / 3;

// Calculate the average mark


average = (ass1 + ass2 + ass3) / 3;

// Print out the average mark


printf("\nThe average is %.2f\n\n\n", average);

// Print out the average mark


printf("\nThe average is %.2f\n\n\n", average);

// Execute when the average is in the range of 51 to 100


if (average > 50 && average <= 100)
{
printf("Well done!!!\n");
printf("You are competent in this module");
}
// Execute when the average is in the range of 50 to 0
else
{

// Execute when the average is in the range of 51 to 100


if (average > 50 && average <= 100)
{
printf("Well done!!!\n");
printf("You are competent in this module");
}
// Execute when the average is in the range of 50 to 0
else
{

27

27

printf("Do not feel bad.... \n");

printf("Do not feel bad.... \n");

printf("Work harder and you may do it better in the future");

printf("Work harder and you may do it better in the future");

printf("\n\n\n");

printf("\n\n\n");

28

28

Appendix Outcome 6-5

Appendix Outcome 6-5

Objective : To understand ELSEIF control structure

Objective : To understand ELSEIF control structure

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
float mark;

// Variable declaration
float mark;

// Read in a mark
printf("Please enter your mark : ");
scanf ("%f", &mark);

// Read in a mark
printf("Please enter your mark : ");
scanf ("%f", &mark);

// Execute when the mark is in range 85 and above


if (mark >= 85)
printf("\nYou get a distinction!\n\n\n");
else
// Execute when the mark is in range 60 to 84
if (mark >= 60)
printf("\nYou get a Merit!\n\n\n");
else
// Execute when the mark is in range 50 to 59
if (mark >= 50)
printf("\nYou get a Pass!\n\n\n");
else
// Execute when the mark is in range 49 and below
printf("\nYou get a Fail!\n\n\n");

// Execute when the mark is in range 85 and above


if (mark >= 85)
printf("\nYou get a distinction!\n\n\n");
else
// Execute when the mark is in range 60 to 84
if (mark >= 60)
printf("\nYou get a Merit!\n\n\n");
else
// Execute when the mark is in range 50 to 59
if (mark >= 50)
printf("\nYou get a Pass!\n\n\n");
else
// Execute when the mark is in range 49 and below
printf("\nYou get a Fail!\n\n\n");

29

29

Appendix Outcome 6-6

Appendix Outcome 6-6

Objective : Amend the program in Appendix Outcome 6-5 by using multiple IF


control structure to observe their difference(s).

Objective : Amend the program in Appendix Outcome 6-5 by using multiple IF


control structure to observe their difference(s).

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
float mark;

// Variable declaration
float mark;

// Read in a mark
printf("Please enter your mark : ");
scanf ("%f", &mark);

// Read in a mark
printf("Please enter your mark : ");
scanf ("%f", &mark);

// Execute when the mark is in range 85 and above


if (mark >= 85)
printf("\nYou get a Distinction!\n\n\n");

// Execute when the mark is in range 85 and above


if (mark >= 85)
printf("\nYou get a Distinction!\n\n\n");

// Execute when the mark is in range 60 to 84


if (mark >= 60 && mark < 85)
printf("\nYou get a Merit!\n\n\n");

// Execute when the mark is in range 60 to 84


if (mark >= 60 && mark < 85)
printf("\nYou get a Merit!\n\n\n");

// Execute when the mark is in range 50 to 59


if (mark >= 50 && mark < 60)
printf("\nYou get a Pass!\n\n\n");

// Execute when the mark is in range 50 to 59


if (mark >= 50 && mark < 60)
printf("\nYou get a Pass!\n\n\n");

// Execute when the mark is in range 49 and below


if (mark < 50)
printf("\nYou get a Fail!\n\n\n");

// Execute when the mark is in range 49 and below


if (mark < 50)
printf("\nYou get a Fail!\n\n\n");

30

30

Appendix Outcome 6-7

Appendix Outcome 6-7

Objective : To understand SWITCH control structure with numeric data type

Objective : To understand SWITCH control structure with numeric data type

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
int choice;

// Variable declaration
int choice;

// Print out the choice options


printf("Please select a choice : ");
printf("1 2 3 or 4\n");
// Read in a choice
printf("\nEnter your choice : ");
scanf ("%d", &choice);

// Print out the choice options


printf("Please select a choice : ");
printf("1 2 3 or 4\n");
// Read in a choice
printf("\nEnter your choice : ");
scanf ("%d", &choice);

switch(choice)
{

switch(choice)
{

// Execute when choice equal 1


case 1:
printf("\nYou have entered choice 1\n\n\n");
break;

// Execute when choice equal 1


case 1:
printf("\nYou have entered choice 1\n\n\n");
break;

// Execute when choice equal 2


case 2:
printf("\nYou have entered choice 2\n\n\n");
break;

// Execute when choice equal 2


case 2:
printf("\nYou have entered choice 2\n\n\n");
break;

// Execute when choice equal 3


case 3:
printf("\nYou have entered choice 3\n\n\n");
break;

// Execute when choice equal 3


case 3:
printf("\nYou have entered choice 3\n\n\n");
break;

31

31

// Execute when choice equal 4


case 4:
printf("\nYou have entered choice 4\n\n\n");
break;

// Execute when choice equal 4


case 4:
printf("\nYou have entered choice 4\n\n\n");
break;

// Execute when choice is none of the above


default:
printf("\nInvalid entry\n\n\n");
break;

// Execute when choice is none of the above


default:
printf("\nInvalid entry\n\n\n");
break;

32

32

Appendix Outcome 6-8

Appendix Outcome 6-8

Objective : To understand SWITCH control structure with character data type

Objective : To understand SWITCH control structure with character data type

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
int choice;

// Variable declaration
int choice;

// Print out the choice options


printf("You are allowed to select choice A, B, C and D\n");
// Read in the option
printf("\nEnter your choice : ");
choice = getchar();

// Print out the choice options


printf("You are allowed to select choice A, B, C and D\n");
// Read in the option
printf("\nEnter your choice : ");
choice = getchar();

switch(choice)
{

switch(choice)
{

// Execute when choice equal to A


case 'A':
printf("\nYou have entered choice A\n\n\n");
break;

// Execute when choice equal to A


case 'A':
printf("\nYou have entered choice A\n\n\n");
break;

// Execute when choice equal to B


case 'B':
printf("\nYou have entered choice B\n\n\n");
break;

// Execute when choice equal to B


case 'B':
printf("\nYou have entered choice B\n\n\n");
break;

// Execute when choice equal to C


case 'C':
printf("\nYou have entered choice C\n\n\n");
break;

// Execute when choice equal to C


case 'C':
printf("\nYou have entered choice C\n\n\n");
break;

33

33

// Execute when choice equal to D


case 'D':
printf("\nYou have entered choice D\n\n\n");
break;

// Execute when choice equal to D


case 'D':
printf("\nYou have entered choice D\n\n\n");
break;

// Execute when choice is none of the above


default:
printf("\nInvalid entry!\n\n\n");
break;

// Execute when choice is none of the above


default:
printf("\nInvalid entry!\n\n\n");
break;

34

34

Appendix Outcome 7-1

Appendix Outcome 7-1

Objective : To understand 1-dimensional array declaration and initialization.

Objective : To understand 1-dimensional array declaration and initialization.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Array Variable declaration
int buffer[5] = {50, 20, 30, 98, 71};

// Array Variable declaration


int buffer[5] = {50, 20, 30, 98, 71};

// Print out the value in each array element


printf("Data store in the array are as below\n");
printf("====================================\n\n");
printf("The data inside buffer[0] is %d\n", buffer[0]);
printf("The data inside buffer[1] is %d\n", buffer[1]);
printf("The data inside buffer[2] is %d\n", buffer[2]);
printf("The data inside buffer[3] is %d\n", buffer[3]);
printf("The data inside buffer[4] is %d\n", buffer[4]);

// Print out the value in each array element


printf("Data store in the array are as below\n");
printf("====================================\n\n");
printf("The data inside buffer[0] is %d\n", buffer[0]);
printf("The data inside buffer[1] is %d\n", buffer[1]);
printf("The data inside buffer[2] is %d\n", buffer[2]);
printf("The data inside buffer[3] is %d\n", buffer[3]);
printf("The data inside buffer[4] is %d\n", buffer[4]);

printf("\n\n");

printf("\n\n");

35

35

Appendix Outcome 7-2

Appendix Outcome 7-2

Objective : To understand 1-dimensional array declaration and initialization.

Objective : To understand 1-dimensional array declaration and initialization.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Array Variable declaration
int buffer[5];

// Array Variable declaration


int buffer[5];

// Assign each array element with a value


buffer[0] = 50;
buffer[1] = 34;
buffer[2] = 78;
buffer[3] = 45;
buffer[4] = 88;

// Assign each array element with a value


buffer[0] = 50;
buffer[1] = 34;
buffer[2] = 78;
buffer[3] = 45;
buffer[4] = 88;

// Print out the value in each array element


printf("Data stored in the array are as below\n");
printf("=====================================\n\n");
printf("The data inside buffer[0] is %d\n", buffer[0]);
printf("The data inside buffer[1] is %d\n", buffer[1]);
printf("The data inside buffer[2] is %d\n", buffer[2]);
printf("The data inside buffer[3] is %d\n", buffer[3]);
printf("The data inside buffer[4] is %d\n", buffer[4]);

// Print out the value in each array element


printf("Data stored in the array are as below\n");
printf("=====================================\n\n");
printf("The data inside buffer[0] is %d\n", buffer[0]);
printf("The data inside buffer[1] is %d\n", buffer[1]);
printf("The data inside buffer[2] is %d\n", buffer[2]);
printf("The data inside buffer[3] is %d\n", buffer[3]);
printf("The data inside buffer[4] is %d\n", buffer[4]);

printf("\n\n");

printf("\n\n");

36

36

Appendix Outcome 7-3

Appendix Outcome 7-3

Objective : To understand 1-dimensional array processing with variable as array


index

Objective : To understand 1-dimensional array processing with variable as array


index

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
int buffer[5], i = 2, j = 4, answer;

// Variable declaration
int buffer[5], i = 2, j = 4, answer;

// Assign a value to each array element


buffer[0] = 50;
buffer[1] = 34;
buffer[2] = 78;
buffer[3] = 45;
buffer[4] = 88;

// Assign a value to each array element


buffer[0] = 50;
buffer[1] = 34;
buffer[2] = 78;
buffer[3] = 45;
buffer[4] = 88;

// Manipulate the array values and assign the value to answer


answer = (buffer[i] + buffer[j]) * 6;

// Manipulate the array values and assign the value to answer


answer = (buffer[i] + buffer[j]) * 6;

// Print out the value in each array element


printf("Data stored in the array are as below\n");
printf("=====================================\n\n");
printf("The data inside buffer[0] is %d\n", buffer[0]);
printf("The data inside buffer[1] is %d\n", buffer[1]);
printf("The data inside buffer[2] is %d\n", buffer[2]);
printf("The data inside buffer[3] is %d\n", buffer[3]);
printf("The data inside buffer[4] is %d\n", buffer[4]);

// Print out the value in each array element


printf("Data stored in the array are as below\n");
printf("=====================================\n\n");
printf("The data inside buffer[0] is %d\n", buffer[0]);
printf("The data inside buffer[1] is %d\n", buffer[1]);
printf("The data inside buffer[2] is %d\n", buffer[2]);
printf("The data inside buffer[3] is %d\n", buffer[3]);
printf("The data inside buffer[4] is %d\n", buffer[4]);

// Print out the value of answer


printf("\nThe data associates with variable Answer is %d\n\n\n", answer);

// Print out the value of answer


printf("\nThe data associates with variable Answer is %d\n\n\n", answer);

}
37

37

Appendix Outcome 7-4

Appendix Outcome 7-4

Objective : To understand 1- dimensional array processing using looping


command

Objective : To understand 1- dimensional array processing using looping


command

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
int table[100], number, i;

// Variable declaration
int table[100], number, i;

// Read in the amount of values


printf("How many numbers you wish to enter?\n");
printf("Please enter an amount here : ");
scanf ("%d", &number);

// Read in the amount of values


printf("How many numbers you wish to enter?\n");
printf("Please enter an amount here : ");
scanf ("%d", &number);

// Read in the numbers desire


printf("\n\nYou can start key in the numbers\n");
for(i = 1; i <= number; ++i)
scanf ("%d", &table[i]);

// Read in the numbers desire


printf("\n\nYou can start key in the numbers\n");
for(i = 1; i <= number; ++i)
scanf ("%d", &table[i]);

// Print out the numbers in the array


printf("\n\nThe numbers you key in are\n");
for(i = 1; i <= number; ++i)
printf("%d\t", table[i]);

// Print out the numbers in the array


printf("\n\nThe numbers you key in are\n");
for(i = 1; i <= number; ++i)
printf("%d\t", table[i]);

printf("\n\n\n");

printf("\n\n\n");

38

38

Appendix Outcome 7-5

Appendix Outcome 7-5

Objective : To understand 2-dimensional array declaration and initialization.

Objective : To understand 2-dimensional array declaration and initialization.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Declaration of 2 - dimensional array with values initialized
int buffer[2][3] = {{50, 20, 30}, {1, 3, 5}};

// Declaration of 2 - dimensional array with values initialized


int buffer[2][3] = {{50, 20, 30}, {1, 3, 5}};

// Print out the values stored in the 1st row


printf("Data stored in 1st Row\n");
printf("======================\n\n");
printf("The data inside buffer[0][0] is %d\n", buffer[0][0]);
printf("The data inside buffer[0][1] is %d\n", buffer[0][1]);
printf("The data inside buffer{0][2] is %d\n", buffer[0][2]);

// Print out the values stored in the 1st row


printf("Data stored in 1st Row\n");
printf("======================\n\n");
printf("The data inside buffer[0][0] is %d\n", buffer[0][0]);
printf("The data inside buffer[0][1] is %d\n", buffer[0][1]);
printf("The data inside buffer{0][2] is %d\n", buffer[0][2]);

// Print out the values stored in the 2nd row


printf("\n\nData stored in 2nd Row\n");
printf("==========================\n\n");
printf("The data inside buffer[1][0] is %d\n", buffer[1][0]);
printf("The data inside buffer[1][1] is %d\n", buffer[1][1]);
printf("The data inside buffer[1][2] is %d\n", buffer[1][2]);

// Print out the values stored in the 2nd row


printf("\n\nData stored in 2nd Row\n");
printf("==========================\n\n");
printf("The data inside buffer[1][0] is %d\n", buffer[1][0]);
printf("The data inside buffer[1][1] is %d\n", buffer[1][1]);
printf("The data inside buffer[1][2] is %d\n", buffer[1][2]);

printf("\n\n\n");

printf("\n\n\n");

39

39

Appendix Outcome 7-6

Appendix Outcome 7-6

Objective : To understand 2- dimensional array declaration and initialization.

Objective : To understand 2- dimensional array declaration and initialization.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Array Variable declaration
int buffer[2][3];

// Array Variable declaration


int buffer[2][3];

// Assign a value to each of the array element


buffer[0][0] = 50;
buffer[0][1] = 20;
buffer[0][2] = 30;
buffer[1][0] = 1;
buffer[1][1] = 3;
buffer[1][2] = 5;

// Assign a value to each of the array element


buffer[0][0] = 50;
buffer[0][1] = 20;
buffer[0][2] = 30;
buffer[1][0] = 1;
buffer[1][1] = 3;
buffer[1][2] = 5;

// Print out the values stored in 1st row


printf("Data stored in 1st Row\n");
printf("======================\n\n");
printf("The data inside buffer[0][0] is %d\n", buffer[0][0]);
printf("The data inside buffer[0][1] is %d\n", buffer[0][1]);
printf("The data inside buffer[0][2] is %d\n", buffer[0][2]);

// Print out the values stored in 1st row


printf("Data stored in 1st Row\n");
printf("======================\n\n");
printf("The data inside buffer[0][0] is %d\n", buffer[0][0]);
printf("The data inside buffer[0][1] is %d\n", buffer[0][1]);
printf("The data inside buffer[0][2] is %d\n", buffer[0][2]);

// Print out the values stored in 2nd row


printf("\n\nData stored in 2nd Row\n");
printf("==========================\n\n");
printf("The data inside buffer[1][0] is %d\n", buffer[1][0]);
printf("The data inside buffer[1][1] is %d\n", buffer[1][1]);
printf("The data inside buffer[1][2] is %d\n", buffer[1][2]);

// Print out the values stored in 2nd row


printf("\n\nData stored in 2nd Row\n");
printf("==========================\n\n");
printf("The data inside buffer[1][0] is %d\n", buffer[1][0]);
printf("The data inside buffer[1][1] is %d\n", buffer[1][1]);
printf("The data inside buffer[1][2] is %d\n", buffer[1][2]);

printf("\n\n\n");

printf("\n\n\n");

}
40

40

Appendix Outcome 7-7

Appendix Outcome 7-7

Objective : To understand 2-dimensional array processing with variable as array


index.

Objective : To understand 2-dimensional array processing with variable as array


index.

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main Function

// Main Function

main()
{

main()
{
// Variable declaration
int buffer[2][3], k = 0, m = 1, n = 2, answer;

// Variable declaration
int buffer[2][3], k = 0, m = 1, n = 2, answer;

// Assign a value to each array element


buffer[0][0] = 50;
buffer[0][1] = 34;
buffer[0][2] = 78;
buffer[1][0] = 45;
buffer[1][1] = 88;
buffer[1][2] = 108;

// Assign a value to each array element


buffer[0][0] = 50;
buffer[0][1] = 34;
buffer[0][2] = 78;
buffer[1][0] = 45;
buffer[1][1] = 88;
buffer[1][2] = 108;

// Print out values stored in 1st row


printf("Data stored in 1st Row\n");
printf("======================\n\n");
printf("The data inside buffer[0][0] is %d\n", buffer[0][0]);
printf("The data inside buffer[0][1] is %d\n", buffer[0][1]);
printf("The data inside buffer[0][2] is %d\n", buffer[0][2]);

// Print out values stored in 1st row


printf("Data stored in 1st Row\n");
printf("======================\n\n");
printf("The data inside buffer[0][0] is %d\n", buffer[0][0]);
printf("The data inside buffer[0][1] is %d\n", buffer[0][1]);
printf("The data inside buffer[0][2] is %d\n", buffer[0][2]);

// Print out values stored in 2nd row


printf("\n\nData stored in 2nd Row\n");
printf("======================\n\n");
printf("The data inside buffer[1][0] is %d\n", buffer[1][0]);
printf("The data inside buffer[1][1] is %d\n", buffer[1][1]);
printf("The data inside buffer[1][2] is %d\n", buffer[1][2]);

// Print out values stored in 2nd row


printf("\n\nData stored in 2nd Row\n");
printf("======================\n\n");
printf("The data inside buffer[1][0] is %d\n", buffer[1][0]);
printf("The data inside buffer[1][1] is %d\n", buffer[1][1]);
printf("The data inside buffer[1][2] is %d\n", buffer[1][2]);

// Manipulate the values in array and assign the result to answer


answer = (buffer[k][m] + buffer[m][n]) * 6;

// Manipulate the values in array and assign the result to answer


answer = (buffer[k][m] + buffer[m][n]) * 6;

41

41

// Print out the value of answer


printf("\n\nThe data associates with variable Answer is %d\n\n\n", answer);
}

// Print out the value of answer


printf("\n\nThe data associates with variable Answer is %d\n\n\n", answer);
}

42

42

Appendix Outcome 7-8

Appendix Outcome 7-8

Objective : To understand 2-dimensional array processing using looping


command

Objective : To understand 2-dimensional array processing using looping


command

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Include directives
#include "stdafx.h"
#include <stdio.h>

// Main function

// Main function

main()
{

main()
{
// Variable declaration
int table[100][100], i, j;

// Variable declaration
int table[100][100], i, j;

// Read in numbers key in by user


printf("Please enter 15 numbers\n");
printf("You can start key in the number\n");
for(i = 1; i <= 5; ++i) // Indicate the rows
{
for(j = 1; j <= 3; ++j) // Indicate the columns
scanf ("%d", &table[i][j]);
}

// Read in numbers key in by user


printf("Please enter 15 numbers\n");
printf("You can start key in the number\n");
for(i = 1; i <= 5; ++i) // Indicate the rows
{
for(j = 1; j <= 3; ++j) // Indicate the columns
scanf ("%d", &table[i][j]);
}

// Print out the numbers entered


printf("\n\nThe numbers you key in are as below : \n\n");
for(i = 1; i <= 5; ++i) // Indicate the rows
{
for(j = 1; j <= 3; ++j) // Indicate the columns
{
printf("%d\t", table[i][j]);
}
printf("\n");
}

// Print out the numbers entered


printf("\n\nThe numbers you key in are as below : \n\n");
for(i = 1; i <= 5; ++i) // Indicate the rows
{
for(j = 1; j <= 3; ++j) // Indicate the columns
{
printf("%d\t", table[i][j]);
}
printf("\n");
}

printf("\n\n\n");

printf("\n\n\n");

}
43

43

Appendix Outcome 7-9

Appendix Outcome 7-9

Objective : To observe the usage of the address-of operator sign (&).

Objective : To observe the usage of the address-of operator sign (&).

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
int number1, number2, number3;

/* Variable declaration */
int number1, number2, number3;

/* Print out the title of the data entry */


printf("Please enter 3 integer numbers\n");
printf("==============================\n");
printf("\n");
/* Read in the value of number1 */
printf("Number 1 : ");
scanf ("%d", &number1);
/* Read in the value of number2 */
printf("Number 2 : ");
scanf ("%d", &number2);
/* Read in the value of number3 */
printf("Number 3 : ");
scanf ("%d", &number3);

/* Print out the title of the data entry */


printf("Please enter 3 integer numbers\n");
printf("==============================\n");
printf("\n");
/* Read in the value of number1 */
printf("Number 1 : ");
scanf ("%d", &number1);
/* Read in the value of number2 */
printf("Number 2 : ");
scanf ("%d", &number2);
/* Read in the value of number3 */
printf("Number 3 : ");
scanf ("%d", &number3);

/* Print out the title for values displaying */


printf("\n\nTo display the values\n");
printf("=====================\n");
/* Print out the values for each variable */
printf("\nThe content of number1 is %d", number1);
printf("\nThe content of number2 is %d", number2);
printf("\nThe content of number3 is %d", number3);

/* Print out the title for values displaying */


printf("\n\nTo display the values\n");
printf("=====================\n");
/* Print out the values for each variable */
printf("\nThe content of number1 is %d", number1);
printf("\nThe content of number2 is %d", number2);
printf("\nThe content of number3 is %d", number3);

/* Print out the title for location displaying */


printf("\n\n\nTo display the location\n");
printf("=======================\n");
/* Print out the addresses for each variable */

/* Print out the title for location displaying */


printf("\n\n\nTo display the location\n");
printf("=======================\n");
/* Print out the addresses for each variable */

44

44

printf("\nThe address of number1 is %x", &number1);

printf("\nThe address of number1 is %x", &number1);

printf("\nThe address of number2 is %x", &number2);


printf("\nThe address of number3 is %x", &number3);

printf("\nThe address of number2 is %x", &number2);


printf("\nThe address of number3 is %x", &number3);

printf("\n\n\n");

printf("\n\n\n");

45

45

Appendix Outcome 7-10

Appendix Outcome 7-10

Objective : To observe the command of declaration of pointer, unary operator and


address of operator.

Objective : To observe the command of declaration of pointer, unary operator and


address of operator.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
int u = 45, v, *au, *pv;

/* Variable declaration */
int u = 45, v, *au, *pv;

/* Assign the address of variable u to variable *au */


au = &u;
/* Assign the pointer value of variable au to variable v */
v = *au;
/* Assign the address of variable v to variable *pv */
pv
= &v;

/* Assign the address of variable u to variable *au */


au = &u;
/* Assign the pointer value of variable au to variable v */
v = *au;
/* Assign the address of variable v to variable *pv */
pv
= &v;

/* Print out the title of particular */


printf("Particular for variable u\n");
printf("=========================\n");
/* Print out the value and address of u */
printf("The data holds by variable u is %d", u);
printf("\nThe address of variable u is %x\n\n\n", &u);

/* Print out the title of particular */


printf("Particular for variable u\n");
printf("=========================\n");
/* Print out the value and address of u */
printf("The data holds by variable u is %d", u);
printf("\nThe address of variable u is %x\n\n\n", &u);

/* Print out the title of particular */


printf("Particular for variable au\n");
printf("==========================\n");
/* Print out the value and address of au */
printf("The data holds by variable au is %x", au);
printf("\nThe address of variable au is %x", &au);
printf("\nThe data read by a pointer au is %d\n\n\n", *au);

/* Print out the title of particular */


printf("Particular for variable au\n");
printf("==========================\n");
/* Print out the value and address of au */
printf("The data holds by variable au is %x", au);
printf("\nThe address of variable au is %x", &au);
printf("\nThe data read by a pointer au is %d\n\n\n", *au);

46

46

/* Print out the title of particular */


printf("Particular for variable v\n");
printf("=========================\n");
/* Print out the value and address of v */
printf("The data holds by variable v is %d", v);
printf("\nThe address of variable v is %x\n\n\n", &v);

/* Print out the title of particular */


printf("Particular for variable v\n");
printf("=========================\n");
/* Print out the value and address of v */
printf("The data holds by variable v is %d", v);
printf("\nThe address of variable v is %x\n\n\n", &v);

/* Print out the title of particular */


printf("Particular for variable pv\n");
printf("==========================\n");
/* Print out the value and address of pv */
printf("The data holds by variable pv is %x", pv);
printf("\nThe data address of variable pv is %x", &pv);
printf("\nThe data read by a pointer pv is %d\n\n\n", *pv);

/* Print out the title of particular */


printf("Particular for variable pv\n");
printf("==========================\n");
/* Print out the value and address of pv */
printf("The data holds by variable pv is %x", pv);
printf("\nThe data address of variable pv is %x", &pv);
printf("\nThe data read by a pointer pv is %d\n\n\n", *pv);

47

47

Appendix Outcome 7-11

Appendix Outcome 7-11

Objective : To store the data into the required address / memory location.

Objective : To store the data into the required address / memory location.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
int *pv, temp;

/* Variable declaration */
int *pv, temp;

/* Read in the address */


printf("Enter any address : ");
scanf ("%x", &pv);

/* Read in the address */


printf("Enter any address : ");
scanf ("%x", &pv);

/* Print out the value of the pointer */


printf("The data of %x is %d\n\n\n", pv, *pv);

/* Print out the value of the pointer */


printf("The data of %x is %d\n\n\n", pv, *pv);

/* Read in the value */


printf("Enter any data : ");
scanf ("%d", &temp);

/* Read in the value */


printf("Enter any data : ");
scanf ("%d", &temp);

/* Assign the value of temp to *pv */


*pv = temp;

/* Assign the value of temp to *pv */


*pv = temp;

/* Print out the value of pointer */


printf("The content of %x is %d\n\n\n", pv, *pv);

/* Print out the value of pointer */


printf("The content of %x is %d\n\n\n", pv, *pv);

48

48

Appendix Outcome 7-12

Appendix Outcome 7-12

Objective : To understand the operation of the pointer and array.

Objective : To understand the operation of the pointer and array.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
int array1[10];
int count1;

/* Variable declaration */
int array1[10];
int count1;

/* Print out the title */


printf("Enter 5 integer numbers\n");
printf("=======================\n");
/* Read 5 values into the array1 */
for (count1 = 1; count1 <= 5; ++count1)
{

/* Print out the title */


printf("Enter 5 integer numbers\n");
printf("=======================\n");
/* Read 5 values into the array1 */
for (count1 = 1; count1 <= 5; ++count1)
{

printf("
X%d = ", count1);
scanf ("%d", &array1[count1]);

printf("
X%d = ", count1);
scanf ("%d", &array1[count1]);

/* Space for one line */


printf("\n");

/* Space for one line */


printf("\n");

/* Print out the 5 values' addresses entered just now */


for (count1 = 1; count1 <= 5; ++count1)
printf("\nThe addresses of array1[%d] is %x", count1, &array1[count1]);

/* Print out the 5 values' addresses entered just now */


for (count1 = 1; count1 <= 5; ++count1)
printf("\nThe addresses of array1[%d] is %x", count1, &array1[count1]);

/* Print out the content of the pointer array1 */


printf("\n\n\nThe content of the pointer called array1 is %x\n\n\n", array1);

/* Print out the content of the pointer array1 */


printf("\n\n\nThe content of the pointer called array1 is %x\n\n\n", array1);

}
49

49

Appendix Outcome 7-13

Appendix Outcome 7-13

Objective : To understand the operation of the pointer and array.

Objective : To understand the operation of the pointer and array.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
long array1[10];
int count1;

/* Variable declaration */
long array1[10];
int count1;

/* Print out the title */


printf("Enter 5 integer numbers\n");
printf("=======================\n");
/* Read 5 values into array1 */
for (count1 = 1; count1 <= 5; ++count1)
{

/* Print out the title */


printf("Enter 5 integer numbers\n");
printf("=======================\n");
/* Read 5 values into array1 */
for (count1 = 1; count1 <= 5; ++count1)
{

printf("
X%d = ", count1);
scanf ("%ld", &array1[count1]);

printf("
X%d = ", count1);
scanf ("%ld", &array1[count1]);

/* Space for 2 lines */


printf("\n\n");

/* Space for 2 lines */


printf("\n\n");

/* Print out the address of that 5 values */


for (count1 = 1; count1 <= 5; ++count1)
printf("\nThe address of array1[%d] is %x", count1, &array1[count1]);

/* Print out the address of that 5 values */


for (count1 = 1; count1 <= 5; ++count1)
printf("\nThe address of array1[%d] is %x", count1, &array1[count1]);

/* Print out the content of pointer array1 */


printf("\n\n\nThe content of the pointer called array is %x\n\n\n", array1);

/* Print out the content of pointer array1 */


printf("\n\n\nThe content of the pointer called array is %x\n\n\n", array1);

}
50

50

Appendix Outcome 7-14

Appendix Outcome 7-14

Objective : Return multiple data by using the command of pointer within a


function.

Objective : Return multiple data by using the command of pointer within a


function.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>

/* Sub-function header */
modify(int *p, int *r)
{

/* Sub-function header */
modify(int *p, int *r)
{

/* Substitute variable a to pointer *p and multiple it with 2 */


*p = *p * 2;
/* Substitute variable b to pointer *r and multiple it with 3 */
*r = *r * 3;

/* Substitute variable a to pointer *p and multiple it with 2 */


*p = *p * 2;
/* Substitute variable b to pointer *r and multiple it with 3 */
*r = *r * 3;

/* Print out the title */


printf("During Function\n");
printf("===============\n");
/* Print out the values of *p and *r inside the sub-function */
printf(" a = %d\n", *p);
printf(" b = %d\n\n\n", *r);

/* Print out the title */


printf("During Function\n");
printf("===============\n");
/* Print out the values of *p and *r inside the sub-function */
printf(" a = %d\n", *p);
printf(" b = %d\n\n\n", *r);

/* return the values to Main function */

/* return the values to Main function */

return;

return;

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
int a, b;

/* Variable declaration */
int a, b;

/* Print out the title */


printf("Before Function\n");
printf("===============\n");

/* Print out the title */


printf("Before Function\n");
printf("===============\n");
51

51

/* Read in the values of a and b */


printf(" a = ");
scanf ("%d", &a);
printf(" b = ");
scanf ("%d", &b);

/* Read in the values of a and b */


printf(" a = ");
scanf ("%d", &a);
printf(" b = ");
scanf ("%d", &b);

/* Space for 2 lines */


printf("\n\n");

/* Space for 2 lines */


printf("\n\n");

/* Pass the values of a and b to a function called Modify */


modify(&a, &b);

/* Pass the values of a and b to a function called Modify */


modify(&a, &b);

/* Print out the title */


printf("After Function\n");
printf("==============\n");
/* Print out the values of a and b after passed through the function */
printf(" a = %d\n", a);
printf(" b = %d\n\n\n", b);

/* Print out the title */


printf("After Function\n");
printf("==============\n");
/* Print out the values of a and b after passed through the function */
printf(" a = %d\n", a);
printf(" b = %d\n\n\n", b);

52

52

Appendix Outcome 7-15

Appendix Outcome 7-15

Objective : To practice the command of 'strlen'

Objective : To practice the command of 'strlen'

/* Include directive */
#include "stdafx.h"
#include <stdio.h>
#include <string.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>
#include <string.h>

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
char sent[100];

/* Variable declaration */
char sent[100];

/* Print out the title */


printf("Enter any string\n");
printf("================\n");
/* Read in the characters entered */
scanf ("%[^\n]", sent);

/* Print out the title */


printf("Enter any string\n");
printf("================\n");
/* Read in the characters entered */
scanf ("%[^\n]", sent);

/* Print out the length of the character string */


printf("\n\n\nThe length of the string is %d\n\n\n", strlen(sent));

/* Print out the length of the character string */


printf("\n\n\nThe length of the string is %d\n\n\n", strlen(sent));

53

53

Appendix Outcome 7-16

Appendix Outcome 7-16

Objective : To practice the command of 'strcpy' with array notation.

Objective : To practice the command of 'strcpy' with array notation.

/* Include directive */
#include "stdafx.h"
#include <stdio.h>
#include <string.h>

/* Include directive */
#include "stdafx.h"
#include <stdio.h>
#include <string.h>

/* Function header */

/* Function header */

main()
{

main()
{
/* Variable declaration */
char sent1[100], sent2[100];

/* Variable declaration */
char sent1[100], sent2[100];

/* Print out the title */


printf("Enter the string\n");
printf("================\n");
/* Read in the characters entered and store in variable sent1 */
scanf ("%[^\n]", sent1);

/* Print out the title */


printf("Enter the string\n");
printf("================\n");
/* Read in the characters entered and store in variable sent1 */
scanf ("%[^\n]", sent1);

/* Copy the string in variable sent1 to variable sent2 */


strcpy(sent2, sent1);

/* Copy the string in variable sent1 to variable sent2 */


strcpy(sent2, sent1);

/* Print out the content of variable sent2 */


printf("\n\n\nThe content of sent2 is %s\n\n\n", sent2);

/* Print out the content of variable sent2 */


printf("\n\n\nThe content of sent2 is %s\n\n\n", sent2);

54

54

Appendix Outcome 7-17

Appendix Outcome 7-17

Objective : To practice the command of 'strcpy' with pointer notation.

Objective : To practice the command of 'strcpy' with pointer notation.

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declaration
char *destination_string, source_string[100];

// Variable declaration
char *destination_string, source_string[100];

// Assign destination_string to source_string


destination_string = source_string;

// Assign destination_string to source_string


destination_string = source_string;

// Read in a string for source_string


printf("Enter any string : ");
scanf ("%[^\n]", source_string);

// Read in a string for source_string


printf("Enter any string : ");
scanf ("%[^\n]", source_string);

// Copy the string value of source_string to


strcpy(destination_string, source_string);

// Copy the string value of source_string to


strcpy(destination_string, source_string);

// Print out the string value copied to destination_string


printf("\n\n\nThe content of destination_string is %s\n\n\n", destination_string);

// Print out the string value copied to destination_string


printf("\n\n\nThe content of destination_string is %s\n\n\n", destination_string);

55

55

Appendix Outcome 7-18

Appendix Outcome 7-18

Objective : To practice the command of 'strcpy' with pointer notation.

Objective : To practice the command of 'strcpy' with pointer notation.

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <conio.h>

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <conio.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declarations
int count1, length;
char *source_string, destination_string[100];

// Variable declarations
int count1, length;
char *source_string, destination_string[100];

// Assign destination_string to source_string


source_string = destination_string;

// Assign destination_string to source_string


source_string = destination_string;

// Read in string value for source_string


printf("Enter a string : ");
scanf ("%[^\n]", source_string);

// Read in string value for source_string


printf("Enter a string : ");
scanf ("%[^\n]", source_string);

// Check the length of source_string and assign it to length


length = strlen(source_string);

// Check the length of source_string and assign it to length


length = strlen(source_string);

// Copy the string value of source_string to destination_string


strcpy(destination_string, source_string);

// Copy the string value of source_string to destination_string


strcpy(destination_string, source_string);

// Print out the content of destination_string


printf("\n\nThe content of destination_string is %s\n\n\n", destination_string);

// Print out the content of destination_string


printf("\n\nThe content of destination_string is %s\n\n\n", destination_string);

// Print out the addresses pointed and contents pointed by source_string


for (count1 = 0; count1 < length; count1++)
{

// Print out the addresses pointed and contents pointed by source_string


for (count1 = 0; count1 < length; count1++)
{

56

56

printf("Address %d = %X\t\tContent = %c\n", count1 + 1, source_string,


*source_string);
++source_string;

printf("Address %d = %X\t\tContent = %c\n", count1 + 1, source_string,


*source_string);
++source_string;

printf("\n\n\n");

printf("\n\n\n");

57

57

Appendix Outcome 7-19

Appendix Outcome 7-19

Objective : To practice the command of 'strncpy'

Objective : To practice the command of 'strncpy'

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <conio.h>

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <conio.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declaration
int count;
char sent_1[100], sent_2[100];

// Variable declaration
int count;
char sent_1[100], sent_2[100];

// Assign all the elements in sent_1 and sent_2 to NULL


for (count = 0; count < 100; count++)
{

// Assign all the elements in sent_1 and sent_2 to NULL


for (count = 0; count < 100; count++)
{

sent_1[count] = NULL;
sent_2[count] = NULL;

sent_1[count] = NULL;
sent_2[count] = NULL;

// Read in a string value for sent_1


printf("Enter a string : ");
scanf ("%[^\n]", sent_1);

// Read in a string value for sent_1


printf("Enter a string : ");
scanf ("%[^\n]", sent_1);

// Copy the first 5 characters from sent_1 to sent_2


strncpy(sent_2, sent_1, 5);

// Copy the first 5 characters from sent_1 to sent_2


strncpy(sent_2, sent_1, 5);

// Print out the string value of sent_2


printf("\n\n\nThe content of sent_2 is %s\n\n\n", sent_2);

// Print out the string value of sent_2


printf("\n\n\nThe content of sent_2 is %s\n\n\n", sent_2);

}
58

58

Appendix Outcome 7-20

Appendix Outcome 7-20

Objective : To practice the command of 'strcmp' using array notation.

Objective : To practice the command of 'strcmp' using array notation.

// Include directive headers


#include "stdafx.h"
#include <string.h>
#include <stdio.h>

// Include directive headers


#include "stdafx.h"
#include <string.h>
#include <stdio.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declaration
int result;
char sent_1[100], sent_2[100];

// Variable declaration
int result;
char sent_1[100], sent_2[100];

// Read in a string value for sent_1


printf("Enter first string : ");
scanf ("%[^\n]", sent_1);

// Read in a string value for sent_1


printf("Enter first string : ");
scanf ("%[^\n]", sent_1);

// Read in a string value for sent_2


printf("Enter second string : ");
fflush(stdin);
scanf ("%[^\n]", sent_2);

// Read in a string value for sent_2


printf("Enter second string : ");
fflush(stdin);
scanf ("%[^\n]", sent_2);

// Compare the strings of sent_1 and sent_2 and assign the value to result
result = strcmp(sent_1, sent_2);

// Compare the strings of sent_1 and sent_2 and assign the value to result
result = strcmp(sent_1, sent_2);

// Do if result is smaller than 0


if (result < 0)
printf("\n\nFirst string comes before Second string\n\n\n");

// Do if result is smaller than 0


if (result < 0)
printf("\n\nFirst string comes before Second string\n\n\n");

// Do if result is equal to 0
if (result == 0)
printf("\n\nFirst string and Second string are the same\n\n\n");

// Do if result is equal to 0
if (result == 0)
printf("\n\nFirst string and Second string are the same\n\n\n");

59

59

// Do if result is greater than 0


if (result > 0)
printf("\n\nSecond string comes before First string\n\n\n");
}

// Do if result is greater than 0


if (result > 0)
printf("\n\nSecond string comes before First string\n\n\n");
}

60

60

Appendix Outcome 7-21

Appendix Outcome 7-21

Objective : To practice the command of 'strcmp' using pointer notation.

Objective : To practice the command of 'strcmp' using pointer notation.

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declaration
int result;
char *sent_1, string_1[100], *sent_2, string_2[100];

// Initialize pointers sent_1 and sent_2 to string_1 and string_2


respectively
sent_1 = string_1;
sent_2 = string_2;

// Variable declaration
int result;
char *sent_1, string_1[100], *sent_2, string_2[100];

// Initialize pointers sent_1 and sent_2 to string_1 and string_2


respectively
sent_1 = string_1;
sent_2 = string_2;

// Read in a string value for sent_1


printf("Enter first string : ");
scanf ("%[^\n]", sent_1);

// Read in a string value for sent_1


printf("Enter first string : ");
scanf ("%[^\n]", sent_1);

// Read in a string value for sent_2


printf("Enter second string : ");
fflush(stdin);
scanf ("%[^\n]", sent_2);

// Read in a string value for sent_2


printf("Enter second string : ");
fflush(stdin);
scanf ("%[^\n]", sent_2);

// Compare the string values between sent_1 and sent_2 and assign the
value to result
result = strcmp(sent_1, sent_2);

// Do if result is less than 0


if (result < 0)
printf("\n\nFirst string comes before Second string\n\n\n");
61

// Compare the string values between sent_1 and sent_2 and assign the
value to result
result = strcmp(sent_1, sent_2);

// Do if result is less than 0


if (result < 0)
printf("\n\nFirst string comes before Second string\n\n\n");
61

// Do if result is equal to 0
if (result == 0)
printf("\n\nFirst string and Second string are the same\n\n\n");

// Do if result is equal to 0
if (result == 0)
printf("\n\nFirst string and Second string are the same\n\n\n");

// Do if result is greater than 0


if (result > 0)
printf("\n\nSecond string comes before First string\n\n\n");

// Do if result is greater than 0


if (result > 0)
printf("\n\nSecond string comes before First string\n\n\n");

62

62

Appendix Outcome 7-22

Appendix Outcome 7-22

Objective : To practice the command of 'strncmp' using pointer notation.

Objective : To practice the command of 'strncmp' using pointer notation.

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declaration
int result;
char *sent_1, string_1[100], *sent_2, string_2[100];

// Variable declaration
int result;
char *sent_1, string_1[100], *sent_2, string_2[100];

// Initialize sent_1 and sent_2 to string_1 and string_2 respectively


sent_1 = string_1;
sent_2 = string_2;

// Initialize sent_1 and sent_2 to string_1 and string_2 respectively


sent_1 = string_1;
sent_2 = string_2;

// Read in a string value for sent_1


printf("Enter first string : ");
scanf ("%[^\n]", sent_1);

// Read in a string value for sent_1


printf("Enter first string : ");
scanf ("%[^\n]", sent_1);

// Read in a string value for sent_2


printf("Enter second string : ");
fflush(stdin);
scanf ("%[^\n]", sent_2);

// Read in a string value for sent_2


printf("Enter second string : ");
fflush(stdin);
scanf ("%[^\n]", sent_2);

// Compare the first 4 characters of sent_1 and sent_2 and assign the
value to result
result = strncmp(sent_1, sent_2, 4);

// Do if result is less than 0


if (result < 0)
printf("\n\nFirst string comes before Second string\n\n\n");
63

// Compare the first 4 characters of sent_1 and sent_2 and assign the
value to result
result = strncmp(sent_1, sent_2, 4);

// Do if result is less than 0


if (result < 0)
printf("\n\nFirst string comes before Second string\n\n\n");
63

// Do if result is equal to 0
if (result == 0)
printf("\n\nFirst string and Second string are the same\n\n\n");

// Do if result is equal to 0
if (result == 0)
printf("\n\nFirst string and Second string are the same\n\n\n");

// Do if result is greater than 0


if (result > 0)
printf("\n\nSecond string comes before First string\n\n\n");

// Do if result is greater than 0


if (result > 0)
printf("\n\nSecond string comes before First string\n\n\n");

64

64

Appendix Outcome 7-23

Appendix Outcome 7-23

Objective : To practice the command of 'strstr'

Objective : To practice the command of 'strstr'

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declaration
char *string_1 = "Borland International", *string_2 = "land", *ptr;

// Variable declaration
char *string_1 = "Borland International", *string_2 = "land", *ptr;

// To look for the position of first occurrence of string_2 in string_1


ptr = strstr(string_1, string_2);

// To look for the position of first occurrence of string_2 in string_1


ptr = strstr(string_1, string_2);

printf("The sub-string is : %s\n\n\n", ptr);

printf("The sub-string is : %s\n\n\n", ptr);

65

65

Appendix Outcome 7-24

Appendix Outcome 7-24

Objective : To practice the command of 'strstr'

Objective : To practice the command of 'strstr'

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Include directive headers


#include "stdafx.h"
#include <stdio.h>
#include <string.h>

// Main function header

// Main function header

main()
{

main()
{
// Variable declaration
char string_1[100], string_2[100], *result;

// Variable declaration
char string_1[100], string_2[100], *result;

// Read in a string value for string_1


printf("Enter first string
: ");
scanf ("%[^\n]", string_1);

// Read in a string value for string_1


printf("Enter first string
: ");
scanf ("%[^\n]", string_1);

// Read in a string value for string_2


printf("Enter a string to search : ");
fflush(stdin);
scanf ("%[^\n]", string_2);

// Read in a string value for string_2


printf("Enter a string to search : ");
fflush(stdin);
scanf ("%[^\n]", string_2);

// Look for the possition of the first occurrence of string_2 in string_1


result = strstr(string_1, string_2);

// Look for the possition of the first occurrence of string_2 in string_1


result = strstr(string_1, string_2);

// Do if result is equal to NULL


if (result == NULL)
printf("\n\n\nSorry! Can't find such string in the sentence\n\n\n");
// Do if found
else
{

// Do if result is equal to NULL


if (result == NULL)
printf("\n\n\nSorry! Can't find such string in the sentence\n\n\n");
// Do if found
else
{

printf("\n\n\nYes! The string is managed to be found\n");


printf("The string is in the characters of %s\n\n\n", result);

printf("\n\n\nYes! The string is managed to be found\n");


printf("The string is in the characters of %s\n\n\n", result);

}
66

66

Appendix Outcome 8-1

Appendix Outcome 8-1

Objective : Revision on the topic of Array

Objective : Revision on the topic of Array

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

main()
{

main()
{
int student_batchno[10], count;
char student_name[10][100];
float student_CGPA[10];

int student_batchno[10], count;


char student_name[10][100];
float student_CGPA[10];

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


{

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


{

printf("Student Name : ");


scanf ("%[^\n]", student_name[count]);

printf("Student Name : ");


scanf ("%[^\n]", student_name[count]);

printf("Batch No. : ");


scanf ("%d", &student_batchno[count]);

printf("Batch No. : ");


scanf ("%d", &student_batchno[count]);

printf("Student CGPA : ");


scanf ("%f", &student_CGPA[count]);

printf("Student CGPA : ");


scanf ("%f", &student_CGPA[count]);

fflush(stdin);
printf("\n");

fflush(stdin);
printf("\n");

system ("cls");

system ("cls");

printf("The data you key in are\n");


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

printf("The data you key in are\n");


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

67

67

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


{

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


{

printf("\nStudent Name : %s", student_name[count]);


printf("\nBatch No. : %d", student_batchno[count]);
printf("\nStudent CGPA : %.2f", student_CGPA[count]);

printf("\nStudent Name : %s", student_name[count]);


printf("\nBatch No. : %d", student_batchno[count]);
printf("\nStudent CGPA : %.2f", student_CGPA[count]);

printf("\n");

printf("\n");

printf("\n\n\n");

printf("\n\n\n");

68

68

Appendix Outcome 8-2

Appendix Outcome 8-2

Objective : To understand the declaration , input and output manipulation of a


STRUCTURE

Objective : To understand the declaration , input and output manipulation of a


STRUCTURE

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

struct HND
{

struct HND
{

char name[100];
int batchno;
float CGPA;

char name[100];
int batchno;
float CGPA;

} EE_student[10];

} EE_student[10];

main()
{

main()
{
int count;

int count;

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


{

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


{

printf("Student Name : ");


scanf ("%[^\n]", EE_student[count].name);

printf("Student Name : ");


scanf ("%[^\n]", EE_student[count].name);

printf("Batch No. : ");


scanf ("%d", &EE_student[count].batchno);

printf("Batch No. : ");


scanf ("%d", &EE_student[count].batchno);

printf("Student CGPA : ");


scanf ("%f", &EE_student[count].CGPA);

printf("Student CGPA : ");


scanf ("%f", &EE_student[count].CGPA);

fflush(stdin);
printf("\n");

fflush(stdin);
printf("\n");
69

69

system ("cls");

system ("cls");

printf("The data you key in are\n");


printf("-----------------------\n");
for (count = 1; count <= 3; count++)
{

printf("The data you key in are\n");


printf("-----------------------\n");
for (count = 1; count <= 3; count++)
{

printf("\nStudent Name : %s", EE_student[count].name);


printf("\nBatch No. : %d", EE_student[count].batchno);
printf("\nStudent CGPA : %.2f", EE_student[count].CGPA);

printf("\nStudent Name : %s", EE_student[count].name);


printf("\nBatch No. : %d", EE_student[count].batchno);
printf("\nStudent CGPA : %.2f", EE_student[count].CGPA);

printf("\n");

printf("\n");

printf("\n\n\n");

printf("\n\n\n");

70

70

Appendix Outcome 8-3

Appendix Outcome 8-3

Objective : Observe the advantage of STRUCTURE compare with ARRAY

Objective : Observe the advantage of STRUCTURE compare with ARRAY

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

struct HND
{

struct HND
{

char name[100];
int batchno;
float CGPA;

char name[100];
int batchno;
float CGPA;

} EE_student[10], MM_student[10];

} EE_student[10], MM_student[10];

main()
{

main()
{
int count;

int count;

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


{

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


{

printf("Student Name : ");


scanf ("%[^\n]", MM_student[count].name);

printf("Student Name : ");


scanf ("%[^\n]", MM_student[count].name);

printf("Batch No. : ");


scanf ("%d", &MM_student[count].batchno);

printf("Batch No. : ");


scanf ("%d", &MM_student[count].batchno);

printf("Student CGPA : ");


scanf ("%f", &MM_student[count].CGPA);

printf("Student CGPA : ");


scanf ("%f", &MM_student[count].CGPA);

printf("\n");

printf("\n");

fflush(stdin);

fflush(stdin);
71

71

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


EE_student[count] = MM_student[count];

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


EE_student[count] = MM_student[count];

system ("cls");

system ("cls");

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count = 1; count <= 3; count++)
{

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count = 1; count <= 3; count++)
{

printf("Student Name : %s\n", EE_student[count].name);


printf("Batch No. : %d\n", EE_student[count].batchno);
printf("Student CGPA : %.2f\n", EE_student[count].CGPA);

printf("Student Name : %s\n", EE_student[count].name);


printf("Batch No. : %d\n", EE_student[count].batchno);
printf("Student CGPA : %.2f\n", EE_student[count].CGPA);

printf("\n");

printf("\n");

printf("\n\n\n");

printf("\n\n\n");

72

72

Appendix Outcome 8-4

Appendix Outcome 8-4

Objective : Understand the application of the ARRAY within a STRUCTURE

Objective : Understand the application of the ARRAY within a STRUCTURE

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

struct database
{

struct database
{

char date[100];
int invoiceno[10];
float amount[10];
int no_of_invoice;

char date[100];
int invoiceno[10];
float amount[10];
int no_of_invoice;

} day[10];

} day[10];

main()
{

main()
{
int count_1, count_2, no_day;

int count_1, count_2, no_day;

printf("How many days of data to key in? ");


scanf ("%d", &no_day);

printf("How many days of data to key in? ");


scanf ("%d", &no_day);

for (count_1 = 1; count_1 <= no_day; count_1++)


{

for (count_1 = 1; count_1 <= no_day; count_1++)


{

fflush(stdin);

fflush(stdin);

printf("\n\nDate : ");
scanf ("%[^\n]", day[count_1].date);

printf("\n\nDate : ");
scanf ("%[^\n]", day[count_1].date);

printf("No. of Inoice received on %s : ", day[count_1].date);


scanf ("%d", &day[count_1].no_of_invoice);

printf("No. of Inoice received on %s : ", day[count_1].date);


scanf ("%d", &day[count_1].no_of_invoice);

73

73

for (count_2 = 1; count_2 <= day[count_1].no_of_invoice; count_2++)


{

for (count_2 = 1; count_2 <= day[count_1].no_of_invoice; count_2++)


{

printf("\nInvoice No. : ");


scanf ("%d", &day[count_1].invoiceno[count_2]);

printf("\nInvoice No. : ");


scanf ("%d", &day[count_1].invoiceno[count_2]);

printf("Amount
: ");
scanf ("%f", &day[count_1].amount[count_2]);

printf("Amount
: ");
scanf ("%f", &day[count_1].amount[count_2]);

printf("\n");

printf("\n");

system ("cls");

system ("cls");

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count_1 = 1; count_1 <= no_day; count_1++)
{

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count_1 = 1; count_1 <= no_day; count_1++)
{

printf("Date : %s\n", day[count_1].date);

printf("Date : %s\n", day[count_1].date);

for (count_2 = 1; count_2 <= day[count_1].no_of_invoice; count_2++)


{

for (count_2 = 1; count_2 <= day[count_1].no_of_invoice; count_2++)


{

printf("Invoice No. : %d\n", day[count_1].invoiceno[count_2]);


printf("Amount
: RM%.2f\n", day[count_1].amount[count_2]);

printf("Invoice No. : %d\n", day[count_1].invoiceno[count_2]);


printf("Amount
: RM%.2f\n", day[count_1].amount[count_2]);

printf("\n");

printf("\n");

printf("\n\n");

printf("\n\n");

printf("\n\n\n");

printf("\n\n\n");

}
}
}

}
}
}
74

74

Appendix Outcome 8-5

Appendix Outcome 8-5

Objective : Mathematical operation within a STRUCTURE

Objective : Mathematical operation within a STRUCTURE

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

struct database
{

struct database
{

char date[100];
int invoiceno[10];
float amount[10];
int no_of_invoice;
float total_amount;

char date[100];
int invoiceno[10];
float amount[10];
int no_of_invoice;
float total_amount;

} day[10];

} day[10];

main()
{

main()
{
int count_1, count_2, no_day;

int count_1, count_2, no_day;

printf("How many days of data to key in? : ");


scanf ("%d", &no_day);

printf("How many days of data to key in? : ");


scanf ("%d", &no_day);

for (count_1 = 1; count_1 <= no_day; count_1++)


{

for (count_1 = 1; count_1 <= no_day; count_1++)


{

fflush(stdin);

fflush(stdin);

day[count_1].total_amount = 0;

day[count_1].total_amount = 0;

printf("\n\nDate : ");
scanf ("%[^\n]", day[count_1].date);

printf("\n\nDate : ");
scanf ("%[^\n]", day[count_1].date);

75

75

printf("No. of Invoice received on %s : ", day[count_1].date);


scanf ("%d", &day[count_1].no_of_invoice);

printf("No. of Invoice received on %s : ", day[count_1].date);


scanf ("%d", &day[count_1].no_of_invoice);

for (count_2 = 1; count_2 <= day[count_1].no_of_invoice; count_2++)


{

for (count_2 = 1; count_2 <= day[count_1].no_of_invoice; count_2++)


{

printf("\nInvoice No. : ");


scanf ("%d", &day[count_1].invoiceno[count_2]);

printf("\nInvoice No. : ");


scanf ("%d", &day[count_1].invoiceno[count_2]);

printf("Amount
: ");
scanf ("%f", &day[count_1].amount[count_2]);

printf("Amount
: ");
scanf ("%f", &day[count_1].amount[count_2]);

day[count_1].total_amount += day[count_1].amount[count_2];

day[count_1].total_amount += day[count_1].amount[count_2];

printf("\n");

printf("\n");

printf("\n\n");

printf("\n\n");

system ("cls");

system ("cls");

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count_1 = 1; count_1 <= no_day; count_1++)
{

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count_1 = 1; count_1 <= no_day; count_1++)
{

printf("Date : %s\n", day[count_1].date);


printf("Total Amount : %.2f\n", day[count_1].total_amount);

printf("Date : %s\n", day[count_1].date);


printf("Total Amount : %.2f\n", day[count_1].total_amount);

printf("\n");

printf("\n");

printf("\n\n\n");

printf("\n\n\n");

76

76

Appendix Outcome 8-6

Appendix Outcome 8-6

Objective : To understand the format of STRUCTURE within STRUCTURE

Objective : To understand the format of STRUCTURE within STRUCTURE

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

struct particular
{

struct particular
{

char name[100];
int studentID;
float CGPA;

char name[100];
int studentID;
float CGPA;

};

};

struct HND
{

struct HND
{

int batchno;
int no_of_EE_student;
int no_of_MM_student;
struct particular EE_student[5];
struct particular MM_student[5];

int batchno;
int no_of_EE_student;
int no_of_MM_student;
struct particular EE_student[5];
struct particular MM_student[5];

} batch[10];

} batch[10];

main()
{

main()
{
int count_1, count_2, batch_total;

int count_1, count_2, batch_total;

printf("Total of Batches : ");


scanf ("%d", &batch_total);

printf("Total of Batches : ");


scanf ("%d", &batch_total);

77

77

for (count_1 = 1; count_1 <= batch_total; count_1++)

for (count_1 = 1; count_1 <= batch_total; count_1++)

{
printf("\n\nBatch No. : ");
scanf ("%d", &batch[count_1].batchno);

printf("\n\nBatch No. : ");


scanf ("%d", &batch[count_1].batchno);

printf("No. of EE students : ");


scanf ("%d", &batch[count_1].no_of_EE_student);

printf("No. of EE students : ");


scanf ("%d", &batch[count_1].no_of_EE_student);

fflush(stdin);

fflush(stdin);

for (count_2 = 1; count_2 <= batch[count_1].no_of_EE_student;


count_2++)

for (count_2 = 1; count_2 <= batch[count_1].no_of_EE_student;


count_2++)

{
fflush(stdin);

fflush(stdin);

printf("\nName
: ");
scanf ("%[^\n]", batch[count_1].EE_student[count_2].name);

printf("\nName
: ");
scanf ("%[^\n]", batch[count_1].EE_student[count_2].name);

printf("Student ID : ");
scanf ("%d", &batch[count_1].EE_student[count_2].studentID);

printf("Student ID : ");
scanf ("%d", &batch[count_1].EE_student[count_2].studentID);

printf("Student CGPA : ");


scanf ("%f", &batch[count_1].EE_student[count_2].CGPA);

printf("Student CGPA : ");


scanf ("%f", &batch[count_1].EE_student[count_2].CGPA);

printf("\n");

printf("\n");

printf("\n\n");

printf("\n\n");

system ("cls");

system ("cls");

printf("The data you key in are\n");


printf("-----------------------\n");
for (count_1 = 1; count_1 <= batch_total; count_1++)
{

printf("The data you key in are\n");


printf("-----------------------\n");
for (count_1 = 1; count_1 <= batch_total; count_1++)
{

printf("\n\nBatch %d\n", batch[count_1].batchno);


78

printf("\n\nBatch %d\n", batch[count_1].batchno);


78

for (count_2 = 1; count_2 <= batch[count_1].no_of_EE_student;


count_2++)

for (count_2 = 1; count_2 <= batch[count_1].no_of_EE_student;


count_2++)

printf("Student Name : %s\n",


batch[count_1].EE_student[count_2].name);
printf("Student ID : %d\n",
batch[count_1].EE_student[count_2].studentID);
printf("Student CGPA : %.2f\n",
batch[count_1].EE_student[count_2].CGPA);

printf("Student Name : %s\n",


batch[count_1].EE_student[count_2].name);
printf("Student ID : %d\n",
batch[count_1].EE_student[count_2].studentID);
printf("Student CGPA : %.2f\n",
batch[count_1].EE_student[count_2].CGPA);

printf("\n");

printf("\n");

printf("\n\n");

printf("\n\n");

printf("\n\n\n");

printf("\n\n\n");

79

79

Appendix Outcome 8-7

Appendix Outcome 8-7

Objective : To understand the format of STRUCTURE within STRUCTURE

Objective : To understand the format of STRUCTURE within STRUCTURE

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

struct time
{

struct time
{

int hour, minutes, seconds;

int hour, minutes, seconds;

};

};

struct machine
{

struct machine
{

int
number, sensor, cyclinder;
char
purpose[100];
char
robot_tupe;
struct time downtime;

int
number, sensor, cyclinder;
char
purpose[100];
char
robot_tupe;
struct time downtime;

} station[100];

} station[100];

main()
{

main()
{
int number, count, down[100];

int number, count, down[100];

printf("How many items do you want to key in? : ");


scanf ("%d", &number);

printf("How many items do you want to key in? : ");


scanf ("%d", &number);

for (count = 1; count <= number; count++)


{

for (count = 1; count <= number; count++)


{

80

80

printf("\n\nPlease key in which station is down : ");


scanf ("%d", &station[count].number);

printf("\n\nPlease key in which station is down : ");


scanf ("%d", &station[count].number);

printf("\nFunction of station %d
: ", station[count].number);
scanf ("%s", station[count].purpose);

printf("\nFunction of station %d
: ", station[count].number);
scanf ("%s", station[count].purpose);

printf("No. of sensors in station %d : ", station[count].number);


scanf ("%d", &station[count].sensor);

printf("No. of sensors in station %d : ", station[count].number);


scanf ("%d", &station[count].sensor);

printf("No. of cyclinders in station %d : ", station[count].number);


scanf ("%d", &station[count].cyclinder);

printf("No. of cyclinders in station %d : ", station[count].number);


scanf ("%d", &station[count].cyclinder);

printf("Downtime \n");
printf("hour : ");
scanf ("%d", &station[count].downtime.hour);
printf("minutes : ");
scanf ("%d", &station[count].downtime.minutes);
printf("seconds : ");
scanf ("%d", &station[count].downtime.seconds);

printf("Downtime \n");
printf("hour : ");
scanf ("%d", &station[count].downtime.hour);
printf("minutes : ");
scanf ("%d", &station[count].downtime.minutes);
printf("seconds : ");
scanf ("%d", &station[count].downtime.seconds);

printf("\n\n");

printf("\n\n");

for (count = 1; count <= number; count++)


{

for (count = 1; count <= number; count++)


{

down[count] = station[count].downtime.hour * 3600 +


station[count].downtime.minutes * 60
+ station[count].downtime.seconds;

down[count] = station[count].downtime.hour * 3600 +


station[count].downtime.minutes * 60
+ station[count].downtime.seconds;

system ("cls");

system ("cls");

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count = 1; count <= number; count++)
{

printf("The data you key in are\n");


printf("-----------------------\n\n");
for (count = 1; count <= number; count++)
{

printf("Station %d\n", station[count].number);


printf("Function of station : %s\n", station[count].purpose);
81

printf("Station %d\n", station[count].number);


printf("Function of station : %s\n", station[count].purpose);
81

printf("No. of sensors
: %d\n", station[count].sensor);
printf("No. of cyclinders : %d\n", station[count].cyclinder);
printf("Downtime
: %d hour %d minutes %d seconds\n",
station[count].downtime.hour,
station[count].downtime.minutes,
station[count].downtime.seconds);
printf("Downtime in second is %d\n", down[count]);

printf("No. of sensors
: %d\n", station[count].sensor);
printf("No. of cyclinders : %d\n", station[count].cyclinder);
printf("Downtime
: %d hour %d minutes %d seconds\n",
station[count].downtime.hour,
station[count].downtime.minutes,
station[count].downtime.seconds);
printf("Downtime in second is %d\n", down[count]);

printf("\n\n");

printf("\n\n");

printf("\n\n\n");

printf("\n\n\n");

82

82

Appendix Outcome 8-8

Appendix Outcome 8-8

Objective : To observe the control flow between the calling and called function

Objective : To observe the control flow between the calling and called function

#include "stdafx.h"
#include <stdio.h>

#include "stdafx.h"
#include <stdio.h>

void modify (int b);

void modify (int b);

main()
{

main()
{
int a = 2, b;

int a = 2, b;

printf("a = %d (from Main, before Calling Function)\n", a);

printf("a = %d (from Main, before Calling Function)\n", a);

modify (a);

modify (a);

printf("\n\na = %d (from Main, after Calling Function)\n", a);

printf("\n\na = %d (from Main, after Calling Function)\n", a);

printf("\n\n\n");

printf("\n\n\n");

void modify (int b)


{

void modify (int b)


{

b *= 3;

b *= 3;

printf("\n\nb = %d (within Called Function)\n", b);

printf("\n\nb = %d (within Called Function)\n", b);

return;

return;

}
83

83

Appendix Outcome 8-9

Appendix Outcome 8-9

Objective : To observe the control flow between the calling and called function for
multiple arguments

Objective : To observe the control flow between the calling and called function for
multiple arguments

#include "stdafx.h"
#include <stdio.h>

#include "stdafx.h"
#include <stdio.h>

modify (int data_1, int data_2, int data_3);

modify (int data_1, int data_2, int data_3);

main()
{

main()
{
int number_1 = 200, number_2 = 300, number_3 = 400;

int number_1 = 200, number_2 = 300, number_3 = 400;

printf("Values in Calling Function - Main\n");


printf("=================================\n");
printf("Number 1 = %d\n", number_1);
printf("Number 2 = %d\n", number_2);
printf("Number 3 = %d\n", number_3);

printf("Values in Calling Function - Main\n");


printf("=================================\n");
printf("Number 1 = %d\n", number_1);
printf("Number 2 = %d\n", number_2);
printf("Number 3 = %d\n", number_3);

modify (number_1, number_2, number_3);

modify (number_1, number_2, number_3);

printf("\n\n\n");

printf("\n\n\n");

modify (int data_1, int data_2, int data_3)


{

modify (int data_1, int data_2, int data_3)


{

printf("\n\n\n");

printf("\n\n\n");

printf("Values in Called Function - Modify\n");


printf("==================================\n");
printf("Data 1 = %d\n", data_1);

printf("Values in Called Function - Modify\n");


printf("==================================\n");
printf("Data 1 = %d\n", data_1);

84

84

printf("Data 2 = %d\n", data_2);

printf("Data 2 = %d\n", data_2);

printf("Data 3 = %d\n", data_3);

printf("Data 3 = %d\n", data_3);

return;

return;

85

85

Appendix Outcome 8-10

Appendix Outcome 8-10

Objective : To understand the usage of function with a return value

Objective : To understand the usage of function with a return value

#include "stdafx.h"
#include <stdio.h>

#include "stdafx.h"
#include <stdio.h>

int modify (int data_1, int data_2, int data_3);

int modify (int data_1, int data_2, int data_3);

main()
{

main()
{
int number_1 = 20, number_2 = 3, number_3 = 4, answer;

int number_1 = 20, number_2 = 3, number_3 = 4, answer;

printf("Values in Calling Function - Main\n");


printf("=================================\n");
printf("Number 1 = %d\n", number_1);
printf("Number 2 = %d\n", number_2);
printf("Number 3 = %d\n", number_3);

printf("Values in Calling Function - Main\n");


printf("=================================\n");
printf("Number 1 = %d\n", number_1);
printf("Number 2 = %d\n", number_2);
printf("Number 3 = %d\n", number_3);

answer = modify (number_1, number_2, number_3);

answer = modify (number_1, number_2, number_3);

printf("\n\nAnswer = %d (in Main after return from Called Function)\n", answer);

printf("\n\nAnswer = %d (in Main after return from Called Function)\n", answer);

printf("\n\n\n");

printf("\n\n\n");

int modify (int data_1, int data_2, int data_3)


{

int modify (int data_1, int data_2, int data_3)


{

int final;

int final;

86

86

printf("\n\n\n");

printf("\n\n\n");

printf("Values in Called Function - Modify\n");


printf("==================================\n");
printf("Data 1 = %d\n", data_1);
printf("Data 2 = %d\n", data_2);
printf("Data 3 = %d\n", data_3);

printf("Values in Called Function - Modify\n");


printf("==================================\n");
printf("Data 1 = %d\n", data_1);
printf("Data 2 = %d\n", data_2);
printf("Data 3 = %d\n", data_3);

final = data_1 * data_2 * data_3;

final = data_1 * data_2 * data_3;

return (final);

return (final);

87

87

Appendix Outcome 8-11

Appendix Outcome 8-11

Objective : To understand the usage of function with an array

Objective : To understand the usage of function with an array

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>

int sum (int number[]);

int sum (int number[]);

main()
{

main()
{
int count_1, count_2, array_1[100], array_2[100];

int count_1, count_2, array_1[100], array_2[100];

printf("Calculate Addition of 3 arrays with 5 numbers\n");


printf("---------------------------------------------\n");
for (count_1 = 1; count_1 <= 3; count_1++)
{

printf("Calculate Addition of 3 arrays with 5 numbers\n");


printf("---------------------------------------------\n");
for (count_1 = 1; count_1 <= 3; count_1++)
{

printf("\nARRAY %d values\n", count_1);


printf("==============\n");

printf("\nARRAY %d values\n", count_1);


printf("==============\n");

for (count_2 = 1; count_2 <= 5; count_2++)


{

for (count_2 = 1; count_2 <= 5; count_2++)


{

printf("No. %d = ", count_2);


scanf ("%d", &array_1[count_2]);

printf("No. %d = ", count_2);


scanf ("%d", &array_1[count_2]);

array_2[count_1] = sum (array_1);

array_2[count_1] = sum (array_1);

printf("\n\n\n");

printf("\n\n\n");
88

88

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

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

printf("Addition of ARRAY %d = %d\n", count_1, array_2[count_1]);

printf("Addition of ARRAY %d = %d\n", count_1, array_2[count_1]);

printf("\n\n\n");

printf("\n\n\n");

int sum (int number[])


{

int sum (int number[])


{

int answer = 0, count;

int answer = 0, count;

for (count = 1; count <= 5; count++)


answer += number[count];

for (count = 1; count <= 5; count++)


answer += number[count];

return (answer);

return (answer);

89

89

Appendix Outcome 8-12

Appendix Outcome 8-12

Objective : To understand the usage of function with a structure

Objective : To understand the usage of function with a structure

#include "stdafx.h"
#include <stdio.h>

#include "stdafx.h"
#include <stdio.h>

struct rect
{

struct rect
{

int x_1, x_2;

int x_1, x_2;

} a;

} a;

struct info
{

struct info
{

int y_1, y_2;

int y_1, y_2;

} b;

} b;

struct rect get (struct rect temp);


struct info print (struct info rec);

struct rect get (struct rect temp);


struct info print (struct info rec);

main()
{

main()
{
struct rect data;
struct info stru;

struct rect data;


struct info stru;

data = get (a);

data = get (a);

printf("\n\nValues after Called Function - Get\n");


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

printf("\n\nValues after Called Function - Get\n");


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

90

90

printf("x1 = %d\nx2 = %d\n\n\n", data);

printf("x1 = %d\nx2 = %d\n\n\n", data);

stru = print (b);

stru = print (b);

printf("\n\nValues after Called Function - Info\n");


printf("-----------------------------------\n");
printf("y1 = %d\ny2 = %d\n\n\n", stru);

printf("\n\nValues after Called Function - Info\n");


printf("-----------------------------------\n");
printf("y1 = %d\ny2 = %d\n\n\n", stru);

struct rect get (struct rect temp)


{

struct rect get (struct rect temp)


{

printf("Enter x1 value : ");


scanf ("%d", &temp.x_1);
printf("Enter x2 value : ");
scanf ("%d", &temp.x_2);

printf("Enter x1 value : ");


scanf ("%d", &temp.x_1);
printf("Enter x2 value : ");
scanf ("%d", &temp.x_2);

temp.x_1 += 3;
temp.x_2 += 3;

temp.x_1 += 3;
temp.x_2 += 3;

return (temp);

return (temp);

struct info print (struct info rec)


{

struct info print (struct info rec)


{

int y3;

int y3;

printf("Enter y1 value : ");


scanf ("%d", &rec.y_1);
printf("Enter y2 value : ");
scanf ("%d", &rec.y_2);

printf("Enter y1 value : ");


scanf ("%d", &rec.y_1);
printf("Enter y2 value : ");
scanf ("%d", &rec.y_2);

y3 = rec.y_1;
rec.y_1 = rec.y_2;
rec.y_2 = y3;

y3 = rec.y_1;
rec.y_1 = rec.y_2;
rec.y_2 = y3;

return (rec);

return (rec);

}
91

91

Appendix Outcome 8-13

Appendix Outcome 8-13

Objective : To understand the usage of function with a structure

Objective : To understand the usage of function with a structure

#include "stdafx.h"
#include <stdio.h>

#include "stdafx.h"
#include <stdio.h>

struct rect
{

struct rect
{

int x_1, x_2;

int x_1, x_2;

};

};

struct rect get (void);


struct rect print (void);

struct rect get (void);


struct rect print (void);

main()
{

main()
{
struct rect data;
struct rect rec;

struct rect data;


struct rect rec;

data = get();

data = get();

printf("\n\nValues after Called Function - Get\n");


printf("----------------------------------\n");
printf("data.x_1 = %d\n", data.x_1);
printf("data.x_2 = %d\n\n", data.x_2);

printf("\n\nValues after Called Function - Get\n");


printf("----------------------------------\n");
printf("data.x_1 = %d\n", data.x_1);
printf("data.x_2 = %d\n\n", data.x_2);

printf("x1 = %d\nx2 = %d\n\n\n", data);

printf("x1 = %d\nx2 = %d\n\n\n", data);

rec = print();

rec = print();

printf("\n\nValues after Called Function - Print\n");

printf("\n\nValues after Called Function - Print\n");

92

92

printf("------------------------------------\n");
printf("rec.x_1 = %d\n", rec.x_1);
printf("rec.x_2 = %d\n\n", rec.x_2);

printf("------------------------------------\n");
printf("rec.x_1 = %d\n", rec.x_1);
printf("rec.x_2 = %d\n\n", rec.x_2);

printf("x1 = %d\nx2 = %d\n\n\n", rec);

printf("x1 = %d\nx2 = %d\n\n\n", rec);

struct rect get (void)


{

struct rect get (void)


{

struct rect temp;

struct rect temp;

printf("Enter x1 value : ");


scanf ("%d", &temp.x_1);
printf("Enter x2 value : ");
scanf ("%d", &temp.x_2);

printf("Enter x1 value : ");


scanf ("%d", &temp.x_1);
printf("Enter x2 value : ");
scanf ("%d", &temp.x_2);

return (temp);

return (temp);

struct rect print (void)


{

struct rect print (void)


{

struct rect info;

struct rect info;

printf("Enter x1 value : ");


scanf ("%d", &info.x_1);
printf("Enter x2 value : ");
scanf ("%d", &info.x_2);

printf("Enter x1 value : ");


scanf ("%d", &info.x_1);
printf("Enter x2 value : ");
scanf ("%d", &info.x_2);

return (info);

return (info);

93

93

Appendix Outcome 8-14

Appendix Outcome 8-14

Objective : To understand the usage of function with a structure

Objective : To understand the usage of function with a structure

#include "stdafx.h"
#include <stdio.h>

#include "stdafx.h"
#include <stdio.h>

struct rect
{

struct rect
{

int y_1, y_2;

int y_1, y_2;

} a;

} a;

struct rect get (struct rect temp);


struct rect print (struct rect info);

struct rect get (struct rect temp);


struct rect print (struct rect info);

main()
{

main()
{
struct rect data;
struct rect stru;

struct rect data;


struct rect stru;

data = get (a);

data = get (a);

printf("\n\nValues after Called Function - Get\n");


printf("==================================\n");
printf("y1 = %d\ny2 = %d\n\n\n", data);

printf("\n\nValues after Called Function - Get\n");


printf("==================================\n");
printf("y1 = %d\ny2 = %d\n\n\n", data);

stru = print (a);

stru = print (a);

printf("\n\nValues after Called Function - Print\n");


printf("====================================\n");
printf("y1 = %d\ny2 = %d\n\n\n", stru);

printf("\n\nValues after Called Function - Print\n");


printf("====================================\n");
printf("y1 = %d\ny2 = %d\n\n\n", stru);

}
94

94

struct rect get (struct rect temp)


{

struct rect get (struct rect temp)


{

printf("Enter y1 value : ");


scanf ("%d", &temp.y_1);
printf("Enter y2 value : ");
scanf ("%d", &temp.y_2);

printf("Enter y1 value : ");


scanf ("%d", &temp.y_1);
printf("Enter y2 value : ");
scanf ("%d", &temp.y_2);

return (temp);

return (temp);

struct rect print (struct rect info)


{

struct rect print (struct rect info)


{

printf("Enter y1 value : ");


scanf ("%d", &info.y_1);
printf("Enter y2 value : ");
scanf ("%d", &info.y_2);

printf("Enter y1 value : ");


scanf ("%d", &info.y_1);
printf("Enter y2 value : ");
scanf ("%d", &info.y_2);

return (info);

return (info);

95

95

You might also like