0% found this document useful (0 votes)
3 views153 pages

Snsnbprogramming in C

The document outlines a course on Programming in C, focusing on basic computer organization, hardware components, memory types, and software concepts. It provides detailed information on primary and secondary memory, including RAM and ROM, as well as input and output devices. The learning objectives aim to equip students with foundational knowledge of computer systems and their functionalities by the end of the module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views153 pages

Snsnbprogramming in C

The document outlines a course on Programming in C, focusing on basic computer organization, hardware components, memory types, and software concepts. It provides detailed information on primary and secondary memory, including RAM and ROM, as well as input and output devices. The learning objectives aim to equip students with foundational knowledge of computer systems and their functionalities by the end of the module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 153

lOMoARcPSD|52151628

Programming in C

BCA (Amity University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by ashikmuhammed ([email protected])
lOMoARcPSD|52151628

Programming In C
1
Module I: Introduction
Notes

e
Course Content:
● Basic Computer Organization

in
● Computer Hardware Components
● Primary Memory – RAM, ROM, Secondary Memory

nl
● Types of Software
● Introduction to Compilers, Interpreters, Assembler, Linker, Loader

O
● Introduction to C compiler and its different versions
● Basic Operating System Concepts, Functions of Operating system
● Types of Operating System.

it y
Key Learning Objective :
At the end of this module, you will be able to:
1. Understand and apply basic structure of computers
2. Understand and apply various types of Software and usage
3. Concept of Compiler, Interpreter and Assembler
rs
ve
4. Get familiar with C compiler
5. Concept of operating system, its functions and types
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
2
UNIT 1.1: Basic Computer Organization
Notes

e
Unit Outcomes :

in
At the end of this unit, you will be able to:
1. Define basic structure of computers
2. Categorizes the types of memory

nl
3. Define the types of software and usage
4. Define compiler, interpreter, assembler
5. Define linker and loader

O
6. Differentiate C Compiler from other compilers
7. Define Operating System
8. Summaries types of Operating Systems and its functionalities

it y
1.1.1 Basic Computer Organization
Computer instructions are the basic components of a machine language program.
They are also known as macro operations, since each one is comprised of a sequences

rs
of microoperations. Each instruction instructs a series of microoperations that carry
operands from registers or memory, perhaps perform arithmetic, logic, or shift
operations, and store results in registers or memory. Instructions are encoded as binary
instruction codes. Every instruction code includes of an operation code, or opcode,
ve
which specifies the whole purpose of the instruction. The control unit is accountable
for decoding the opcode and operand bits in the instruction register, and producing the
control signals required to drive all other hardware in the CPU to execute the series of
microoperations that encompass the instruction
ni
U
it y
m

1.1.2 Computer Hardware Components


)A

Computer has five units.

They are:
1. Input Devices
2. Memory Unit
(c

3. Arithmetic & Logic Unit


4. Control Unit.
5. Output Devices

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
3
Input Devices :
Notes
Computers take information through input unit. Keyboard, mouse, Joystick, Light

e
pen, Scanner, Bar code reader are few examples of Input unit. Whenever we press a
key, through cable it is translated to binary code as computers only understand binary
format (i.e. 0 and 1) and then transmitted to either memory or processor.

in
The standard data input unit for a computer is Keyboard . It comprises of several
keys which follows the standard QWERTY layout with numeric keypad and additional
function keys for control purposes.

nl
Another prevalent input device is the Mouse. Movement of mouse is shown on the
screen and an arrow is seen during mouse movement which is known as a ‘cursor’.

O
There are two buttons and a scroll ball present in a mouse. You will require to click the
buttons of the mouse to pick an option and scroll the ball to make the page move up
and down.

Joystick is basically used for gaming purpose. It is a rotary lever. It enables you

it y
to move within the screen’s environment, and is widely used in the computer games
industry.

An Alternative input device called a Light Pen is a pointing device modeled like
a pen and is linked to a Visual Display Unit (VDU). The tip of the light pen contains a

rs
light-sensitive element which, when placed against the screen, detects the light from the
screen facilitating the computer to identify the location of the pen on the screen.

A photo or text to be input into a computer through a device called Scanners


ve
which is an input device. Two types of Scanners are there; one is flatbed scanner and
another is hand-held scanner.

A Bar Code reader is another input device. A Bar Code is a pattern printed in lines
of contrasting thickness. You might have seen bar codes on goods in libraries, in
ni

supermarkets, on magazines etc. Bar codes provide a quick method of recording the
sale of items.

Memory Unit :
U

The accountability of memory unit is to stores data as well as programs. Two


categories of memory units are there , Primary Memory and Secondary Memory. The
capability to store instructions that form a computer program, and the information that
it y

the instructions manipulate is what makes stored program architecture computers


versatile.

1.1.3 Primary Memory:


m

Memory is needed in computers to store data and instructions. Memory is


physically structured as a large number of cells that are competent of storing one bit
each. Logically they are structured as groups of bits called words that are assigned
)A

an address. Data and instructions are accessed through these memory address. The
rapidity with which these memory addresses can be accessed determines the cost of
the memory. Quicker the memory speed, higher the price.

Computer memory can be believed to be arranged in a hierarchical way where


memory with the fastest access speeds and highest costs lies at the top although those
(c

with lowest speeds and hence lowest costs lie at the bottom. Based on this criteria
memory is of two categories – primary and secondary. Here we will look at primary
memory in detail.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
4

Notes

e
in
nl
O
it y
Purpose of Storage

The essential components of a general-purpose computer are arithmetic and


logic unit, control circuitry, storage space, and input/output devices. If storage were

rs
removed, the device we had would be a simple calculator instead of a computer. The
ability to store instructions that form a computer program, and the information that the
instructions manipulate is what makes stored program architecture computers versatile.

Primary memory is very fast which works at electronic speed. Generally, before
ve
getting executed, programs should be stored in memory. Primary memory is essential
but expensive. Primary storage is precisely connected to the central processing unit
(CPU) of the computer. It is used when large number of data & programs are needed
to store, particularly the information that we don’t access very frequently. We have two
ni

types of memory like RAM and ROM.

RAM (Random Access Memory):


U

RAM is a volatile memory. It is also called temporary memory. when you turn off
your computer, the data that are there inside RAM got obliterated. So, before turning
off your computer you must save your work to permanent storage device. If you have
more RAM, the less frequently the computer must access instructions and data from the
it y

sluggishly accessed hard disk.

Types of RAM:

Two types of RAM are used in computers: Dynamic RAM and Static RAM.
m

Dynamic RAM (DRAM): The information stored in Dynamic RAM has to be


refreshed after every few milliseconds otherwise it will get erased. DRAM has higher
)A

storage capacity and is cheaper than Static RAM.

Static RAM (SRAM): The information stored in Static RAM need not be refreshed,
but it remains stable as long as power supply is provided. SRAM is costlier but has
higher speed than DRAM.

Additional kinds of integrated and quickly accessible memory are Read Only
(c

Memory (ROM), Programmable ROM (PROM), and Erasable Programmable ROM


(EPROM). These are used to maintain special programs and data, such as the BIOS,

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
5
that need to be in your computer all the time. ROM is “built-in” computer memory
comprising data that normally can only be read, not written to (hence the name read Notes
only).

e
ROM (Read Only Memory):

in
ROM is non volatile memory i.e. when you switch off your computer, the data and
information which are stored does not get erased. ROM includes the programming that
permits computer to be “boot up” each time you turn it on. The ROM is sustained by a

nl
small long-life battery in the computer called the CMOS battery. It is non volatile, but not
suited to storage of large quantities of data because it is costly to produce. Typically,
ROM ought to be completely expunged before it can be rewritten and that can be done

O
only by the manufacturer.

PROM (Programmable Read Only Memory):

it y
A deviation of the ROM chip is programmable read only memory. PROM can be
programmed to record information using a provision known as PROM-programmer.
Nevertheless, the chip has been programmed the recorded information cannot be
changed, i.e. the PROM becomes a ROM and the information can only be read.

EPROM (Erasable Programmable Read Only Memory):

As the name suggests the Erasable Programmable Read Only Memory, informationrs
can be removed, and the chip programmed a new to record different information using
ve
a special PROM-Programmer. When EPROM is in use information can only be read
and the information persists on the chip until it is erased.

1.1.4 Secondary Memory:


ni

Storage devices consist of hard disks, floppy disks, CDROMs, and tape backup
systems. The phrases auxiliary storage, auxiliary memory, and secondary memory have
also been used for this kind of data repository.
U

STORAGE DEVICES

The objective of storage in a computer is to keep data or information and get that
it y

data to the CPU as swiftly as possible when it is needed. Computers utilize disks for
storage: hard disks that are placed inside the computer, and floppy or compact disks
that are utilized externally.

● Computers Method of storing data & information for long term basis i.e. even after
PC is switched off.
m

● It is non - volatile
● Can be easily removed and moved & attached to some other device
)A

● Memory capacity can be extended to a greater extent


● Cheaper than primary memory

Storage Involves two processes:


(c

a. Writing data
b. Reading data

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
6
Floppy Disks
Notes
The floppy disk drive (FDD) was developed at IBM by Alan Shugart in 1967. The

e
first floppy drives utilized an 8-inch disk (later called a “diskette” as it got smaller), which
progressed into the 5.25-inch disk that was used on the first IBM Personal Computer
in August 1981. The 5.25-inch disk held 360 kilobytes compared to the 1.44 megabyte

in
capacity of today’s 3.5-inch diskette.

The 5.25-inch disks were dubbed “floppy” since the diskette packaging was a very
flexible plastic envelope, unlike the rigid case used to hold today’s 3.5-inch diskettes.

nl
Hard Disks

O
Computer uses two kinds of memory: primary memory which is stored on chips
located on the motherboard, and secondary memory that is stowed in the hard drive.
Primary memory holds all the vital memory while Secondary memory owns the
information that you store in the computer.

it y
Within the hard disk drive case, circular disks are placed that are made from
polished steel. On the disks, there are several tracks or cylinders. Inside the hard drive,
an electronic reading/writing device termed the head passes back and forth over the
cylinders, reading information from the disk or writing information to it. Hard drives roll

rs
at 3600 or more rpm (Revolutions Per Minute) - that means that in one minute, the hard
drive spins around over 7200 times!

Optical Storage
ve
● Compact Disk Read-Only Memory (CD-ROM)
● CD-Recordable (CD-R)/CD-Rewritable (CD-RW)
● Digital Video Disk Read-Only Memory (DVD-ROM)
ni

● DVD Recordable (DVD-R/DVD Rewritable (DVD-RW)


● Photo CD
U

Optical Storage Devices Data is deposited on a reflective surface so it can be


read by a beam of laser light. Two Kinds of Optical Storage Devices

● CD-ROM (compact disk read-only memory)


it y

● DVD-ROM (digital video disk read-only memory)

Compact Disks
m

CDs use pits (microscopic indentations) and lands (flat surfaces) to store
information considerably the same way floppies and hard disks use magnetic and non-
magnetic storage. Inside the CD-Rom, a laser that reflects light off the surface of the
disk to an electric eye. The pattern of reflected light (pit) and no reflected light (land)
)A

establishes a code that represents data.

CDs usually store about 650MB. This is quite a bit more than the 1.44MB that a
floppy disk stores. A DVD or Digital Video Disk holds even additional information than a
CD, because the DVD can store information on two levels, in smaller pits or sometimes
on both sides.
(c

Recordable Optical Technologies


● CD

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
7
● DVD
● Pen Drives / Flash Drives
Notes

e
CD ROM - Compact Disc Read Only Memory.

in
Contrasting magnetic storage device which store data on multiple concentric tracks,
the entire CD formats store data on one physical track, which spirals continuously from
the center to the outer edge of the recording area. Data dwells on the thin aluminium

nl
substrate instantly beneath the label. The data on the CD is recorded as a sequence
of microscopic pits and lands physically embossed on an aluminium substrate. Optical
drives use a low power laser to read data from those discs without physical contact
between the head and the disc which contributes to the high trustworthiness and

O
permanence of storage device.

In order to write the data on a CD a higher power laser are used to record the
data on a CD. It creates the pits and land on aluminium substrate. The data is stored

it y
perpetually on the disc. These types of discs are called as WORM (Write Once Read
Many). Data written to CD cannot consequently be deleted or overwritten which can
be classified as advantage or disadvantage depending upon the requirement of the
user. Nevertheless if the CD is moderately filled then the more data can be added to it
later on till it is full. CDs are usually inexpensive and cost effective in terms of storage

rs
capacity and transferring the data.

The CD‘s were further developed where the data could be deleted and re written.
These types of
ve
CDs are called as CD Rewritable. These types of discs can be used by deleting the
data and making the space for new data. These CD‘s can be written and rewritten at
least 1000 times.
ni

CD ROM Drive

CD ROM drives are so well consistent and have become so ubiquitous that
many treat them as commodity items. Although CD ROM drives differ in reliability,
U

which standards they support and numerous other respects, there are two important
performance measures.

● Data transfer rate


it y

● Average access
The data on a CD is saved on tracks, which spirals from the centre of the CD to
outer edge. The portions of the tracks towards centre are shorter than those towards
the edge. Relocating the data under the head at a constant rate requires spinning the
m

disc faster as the head moves from the centre where there is less data per revolution to
the edge where there is more data. Therefore, the rotation rate of the disc adjustments
as it progresses from inner to outer portions of the disc.
)A

Pen Drives / Flash Drives


● Pen Drives / Flash Drives are flash memory storage devices.
● They are faster, portable and have a capability of storing large data.
(c

● It consists of a small printed circuit board with a LED encased in a robust plastic
● The male type connector is used to connect to the host PC
● They are also used a MP3 players

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
8
A Computer has five operational autonomous units like Input Unit, Memory Unit, Arithmetic
Notes & Logic Unit, Output Unit, Control Unit.

e
Arithmetic & Logic Unit :

in
ALU (Arithmetic & Logical Unit) performs Arithmetic and Logic operations. ALU and this
operation are initiated once the operands are brought into the processor.

Output Unit : It displays the processed result to outside world.

nl
Control Unit:

Control Unit is the portion of the computer’s central processing unit (CPU), which

O
manages the operation of the processor. It was contained as part of the Von Neumann
Architecture by John von Neumann. It is the accountability of the Control Unit to tell the
computer’s memory, arithmetic/logic unit and input and output devices how to react to
the instructions that have been sent to the processor. It brings internal instructions of

it y
the programs from the main memory to the processor instruction register, and based
on this register contents, the control unit generates a control signal that supervises the
execution of these instructions. A control unit works by receiving input information to
which it transforms into control signals, which are then sent to the central processor.
The computer’s processor then tells the enclosed hardware what operations to perform.

rs
The functions that a control unit performs are dependent on the type of CPU because
the architecture of CPU varies from manufacturer to manufacturer.
ve
OUTPUT DEVICES :

An output device is computer hardware that receives data from a computer


and translates that data into either text, audio, video or hard copy such as a printed
document.
ni

The key difference between an input device and an output device is that an input
device takes data from user and an output device deliver output either on monitor or
printer etc.
U

Example of Output devices are Monitor, Printer, Projector, Headphones, Speakers


etc.

A Printer is another popular part of a computer system. It takes what you look at on
it y

the computer screen and prints it on paper.

Speakers are output devices that permit you to hear sound from computer.
Computer speakers are like stereo speakers. There are mostly two of them and they
come in various sizes.
m

Primary Memory – RAM, ROM:

MEMORY OR PRIMARY STORAGE :


)A

Primary Storage

Primary storage is precisely connected to the central processing unit of the


computer. It ought to be present for the CPU to function correctly, just as in a biological
analogy the lungs must be present (for oxygen storage) for the heart to function (to
(c

pump and oxygenate the blood). As shown in the diagram, primary storage typically
consists of three kinds of storage:

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
9

Notes

e
in
nl
O
Processors Register

it y
Processors Registers is the internal to the central processing unit. Registers include
information that the arithmetic and logic unit needs to carry out the current instruction.
They are technically the fastest of all forms of computer storage.

Main memory

Main memory contains the programs that are presently being run and the data
rs
the programs are operating on. The arithmetic and logic unit can very rapidly transfer
information between a processor register and locations in main storage, also known
ve
as a “memory addresses”. In modern computers, electronic solid-state random-access
memory is employed for main storage, and is precisely connected to the CPU via a
“memory bus” and a “data bus”.
ni

Cache memory

Cache memory is a unique type of internal memory used by several central


processing units to enhance their performance or “throughput”. Some of the information
U

in the main memory is duplicated in the cache memory, which is marginally slower but
of much superior capacity than the processor registers, and faster but much tinier than
main memory.
it y

1.1.5 Types of Software:


Generally, there are two main classifications of software, which are namely, System
Software along with the Application Software.
m

1.1.5.1 System Software:


System Software In case of a system software, it helps the user as well as
)A

the hardware to function and even interact with each other easily. Essentially, it is a
software which is used to manage the behaviour of the computer hardware in order to
offer basic functionalities which are needed by the user. In simpler word, it can be said
that system software is essentially an intermediator or even a middle layer between the
user as well as the hardware. These software sanction an environment or platform for
the other software to easily work in. Hence, it is the reason why the system software
(c

is quite important in the management of the entire computer system. Whenever you
turn on the computer first, it is this system software which gets initialized and then gets
loaded in the system’s memory. A system software essentially runs in the background,
and it is not actually utilized by the end users.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
10
1.1.5.2 Application Software :
Notes They are also popularly known as end-user programs or even productivity programs
which assist the user in completing various tasks like conducting online research,

e
making notes, designing graphics, maintaining accounts, carrying out calculations or
even playing computer games. They essentially lie above the system software. They

in
are actually used by the end-user as well as have specific functionality or tasks which
they are designed to perform. These software are often developed through custom
software development, based on the requirements of the users.

nl
1.1.6 Introduction to Computers
Computers are a reasonable mix of software and hardware. Hardware is simply

O
a piece of mechanical device and its functions are being monitored by a compatible
software. Hardware recognizes instructions in the form of electronic charge, which
is the counterpart of binary language in software programming. Binary language
has only two alphabets, 0 and 1. To instruct, the hardware codes must be written in

it y
binary format, which is simply a sequence of 1s and 0s. It would be a challenging and
cumbersome task for computer programmers to write such codes, which is why we
have compilers to write such codes.

rs
Compiler

A Compiler is a program that converts a number of statement of program into binary


language, but it is more intelligent than interpreter because it goes through the entire
code at once and can tell the possible errors and limits and ranges. But this makes it’s
ve
operating time a little slower. it is platform-dependent. its help to detect error and get
displayed after reading the entire code by compiler.

Cross-compiler
ni

A compiler that runs on platform (A) and is capable of generating executable code
for platform (B) is called a cross-compiler.
U
it y
m

Source-to-source Compiler
)A

A compiler that takes the source code of one programming language and translates
it into the source code of another programming language is called a source-to-source
compiler.
(c

Interpreter

An interpreter, like a compiler, translates high-level language into low-level


machine language. The distinction lies in the way they read the source code or input.
A compiler reads the whole source code at once, creates tokens, checks semantics,
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
11
generates intermediate code, executes the whole program and may involve many
passes. In contrast, an interpreter reads a statement from the input, transforms it to an Notes
intermediate code, executes it, then takes the next statement in sequence. If an error

e
occurs, an interpreter stops execution and reports it. though a compiler reads the whole
program even if it encounters several errors.

in
There are several types of interpreter:
● Syntax-directed interpreter

nl
● Threaded interpreter
● Bytecode interpreter

O
Assembler

An assembler translates assembly language programs into machine code. The


output of an assembler is called an object file, which contains a combination of machine

it y
instructions as well as the data required to place these instructions in memory.

Linker

Linker is a computer program that links and combines various object files together
in order to make an executable file. All these files might have been compiled by

rs
independent assemblers. The key task of a linker is to search and locate referenced
module/routines in a program and to ascertain the memory location where these codes
will be loaded, making the program instruction to have absolute references.
ve
1. Dynamic Linker:-

● It is employed during run time.


ni

● It requires less memory.


● In dynamic linking there are many chances of error and failure chances.
U

● Linking stored the program in virtual memory to save RAM, need shared library

2. Static Linker:-
it y

● It is implemented during compilation of source program.


● It requires more memory.
● Linking is implemented before execution in static linking.
● It is faster and portable.
m

● In static linking there are less chances to error and No chances to failure.
)A

Loader

Loader is a element of operating system and is accountable for loading executable


files into memory and execute them. It computes the size of a program (instructions
and data) and creates memory space for it. It initializes various registers to initiate
execution.
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
12
1.1.7 Introduction to C compiler and its different versions:
Notes The C compilation system comprises of a compiler, an assembler, and a link
editor. The cc command invokes each of these components automatically unless you

e
use command-line options to specify otherwise. The C compiler optimizer removes
redundancies, optimally allocates registers, schedules instructions, and reorganizes

in
code. Select from multiple levels of optimization to obtain the best balance between
application speed and use of memory.

nl
O
it y
Fig 1.5: C compiler

1.1.8 Basic Operating System Concepts:


An Operating system is essentially an intermediary agent in the middle of the user

control for applications.


rs
and the computer hardware. It Manages the computer’s resources. Simplifies hardware

All operating systems use one fundamental abstraction: the process. A process
ve
can be described either as “an instance of a program in execution” or as the “execution
context” of a running program. In traditional operating systems, a process executes a
specific sequence of instructions in an address space; the address space is the set
of memory addresses that the process is permissible to reference. Modern operating
ni

systems allow processes with multiple execution flows — that is, multiple sequences of
instructions executed in the same address space.
U

1.1.9 Functions of Operating system:


The operating system utilizes password protection to protect user data and similar
other techniques. it also precludes unauthorized access to programs and user data.
Monitors overall system health to help improve performance. records the response
it y

time between service requests and system response to have a comprehensive view of
the system health .Operating system Keeps track of time and resources employed by
various tasks and users, this information can be used to track resource usage for a
particular user or group of user. Operating system frequently monitors the system to
detect errors and avoid the malfunctioning of computer system.
m

1.1.9.1 Types of Operating System:


)A

1. Simple Batch System


2. Multiprogramming Batch System
3. Multiprocessor System
4. Desktop System
5. Distributed Operating System
(c

6. Clustered System
7. Realtime Operating System
8. Handheld System
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
13
1.1.10 The advantage of using Operating System
● Allows you to conceal details of hardware by establishing an abstraction
Notes

e
● Effortless to use with a GUI
● Presents an environment in which a user may execute programs/applications

in
● The operating system must make sure that the computer system convenient to use
● Operating System acts as an mediator among applications and the hardware

nl
components
● It affords the computer system resources with easy to use format

O
Plays as an intermediator between all hardware’s and software’s of the system

Activity :
1. The simultaneous execution of two or more programs in one computer is called_______

it y
2. What is the function of the controller unit?
3. Give example for a multiuser operating system.
4. Give examples for single user operating systems?

computer?
rs
5. Which smaller unit of the CPU performs all arithmetic and logic functions in a

6. Which register example holds the address of the current instruction being processed?
7. Distinguish RAM and ROM.
ve
8. What are the advantages of Operating Systems
9. What are The two kind of main memory
10. Give an example of non-volatile memory.
ni

11. The storage that supplements the primary internal storage of a computer is known as ?
12. What is the name given to the memory which works on time sharing principle in order
to create an illusion of infinite memory space?
U

13. What is the main advantage of semiconductor RAM


14. What is the basic characteristics of DRAMs?
15. Differentiate Loader and Linker
it y

16. Distinguish Compiler and Interpreter


m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
14
Model II: Programming in C
Notes

e
Course Content:
● History of C

in
● Introduction of C
● Basic structure of C program

nl
● Concept of variables, constants and data types in C
● Operators and expressions: Introduction, arithmetic, relational, Logical, Assignment,

O
Increment and decrement operator, Conditional, bitwise operators, Expressions
● Operator precedence and associativity
● Managing Input and output Operation, formatting I/O.

it y
Key Learning Objective :
1. Understanding of basic C programs
2. Concept of variables and data types
3. Understanding of different types of operators

rs
4. Understand and apply the concept to develop applications
ve
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
15
UNIT 2.1: History of C
Notes

e
Unit Outcomes :

in
At the end of this unit, you will be able to:
1. Understand syntax and semantics - variables, data types , operators
2. Get Familiar with basic structure of C Programs

nl
3. State different types of operators
4. Understand how to work with input and output

O
2.1.1 History of C
The C programming language came out of Bell Labs in the initial 1970s. Rendering
to the Bell Labs paper “The Development of the C Language” by Dennis Ritchie. “The

it y
C programming language was devised in the early 1970s as a system implementation
language for the nascent Unix operating system.

Stemmed from the type less language BCPL, it evolved a type structure; built on a
tiny machine as a tool to enhance a meager programming environment.”

language for the new Unix platform. Thompson adapted the BCPL system language
and invented B. rs
Formerly, Ken Thompson, a Bell Labs employee, preferred to make a programming
ve
However, not many utilities were ever written in B due to its sluggish nature and
inability to take advantage of PDP-11 features in the operating system. This led to
Ritchie bettering on B, and thus producing C.
ni

2.1.2 Introduction of C
C is a general-purpose programming language that is exceptionally popular, simple
and flexible. It is machine-independent, structured programming language which is
U

used significantly in numerous applications.

C was the fundamental language to write the whole lot from operating systems
(Windows and many others) to complex programs resembling the Oracle database, Git,
it y

Python interpreter and more.

It is believed that ‘C’ is a divinity’s programming language. One can say, C is a


center for the programming. If you understand ‘C,’ you can easily grasp the expertise of
the other programming languages that uses the concept of ‘C’
m

2.1.3 Basic structure of C program


)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
16
The components of the above structure are:
Notes 1. Header Files Inclusion: The first and foremost element is the inclusion of the
Header files in a C program. A header file is a file with extension .h which comprises

e
C function declarations and macro definitions to be shared between several source
files.

in
Some of C Header files:
● stddef.h – Describes several useful types and macros.

nl
● stdint.h – Identifies precise width integer types.
● stdio.h – Specifies core input and output functions

O
stdlib.h – Defines numeric conversion functions, pseudo-random network generator,
memory allocation
● string.h – Defines string handling functions

it y
math.h – Defines common mathematical functions

Syntax to include a header file in C:

#include

The syntax to declare the main function is:

Syntax to Declare main method:


rs
Main Method Declaration: The next part of a C program is to declare the main() function.
ve
int main()

{}
ni

Variable Declaration:

The following part of any C program is the variable declaration. It implies to the variables
that are to be used in the function. Please note that in the C program, no variable can be
U

used deprived of being declared. Also in a C program, the variables are to be declared
prior to any operation in the function.
it y

Example:

int main()
m

int a;
)A

Body:
(c

Body of a function in C program, refers to the operations that are staged in the functions.
It can be anything like manipulations, searching, sorting, printing, etc.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
17
Example:
Notes
int main()

e
{

in
int a;

nl
printf(“%d”, a);

O
.

Return Statement:
The preceding part in any C program is the return statement. The return statement

it y
describes to the returning of the values from a function. This return statement and
return value hinge on upon the return type of the function. For example, if the return
type is void, then there will be no return statement. In any new case, there will be a
return statement and the return value will be of the type of the stipulated return type.

Example:

int main() rs
ve
{

int a;
ni

printf(“%d”, a);
U

return 0;

}
it y

2.4 Concept of variables


A variable is a name given to a storage area that our programs can manipulate.
Each variable in C has a specific type, which regulates the size and layout of the
variable’s memory; the range of values that can be stored inside that memory; and the
m

set of operations that can be applied to the variable.

The name of a variable can be comprised of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
)A

letters are distinct because C is case-sensitive. Based on the basic types explained in
the previous chapter, there will be the following basic variable types −

char

Typically a single octet(one byte). It is an integer type.


(c

int

The most natural size of integer for the machine.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
18
float
Notes
A single-precision floating point value.

e
double

in
A double-precision floating point value.

void

nl
Represents the absence of type.
A variable definition identifies the compiler where and how considerably storage to
create for the variable. A variable definition specifies a data type and contains a list of

O
one or more variables of that type as follows −

type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double,

it y
bool, or any user-defined object; and variable_list may comprise of one or more
identifier names divided by commas. Some valid declarations are shown here −

int i, j, k;

rs
char c, ch;
float f, salary;
double d;
ve
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler
to create variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
ni

type variable_name = value;


U

2.1.5 Constants and data types in C


In order to define a variable whose value cannot be altered; you can utilize the
const keyword. This will create a constant. For example,
it y

const double PI = 3.14;


In C programming, data types are declarations for variables. This affects the type
and size of data associated with variables. For example,
m

int myVar;

Type Size (bytes) Format Specifi-er


)A

int at least 2, usually 4 %d, %i


char 1 %c
float 4 %f
double 8 %lf
(c

short int 2 usually %hd


unsigned int at least 2, usually 4 %u

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
19

long int at least 4, usually 8 %ld, %li


Notes
long long int at least 8 %lld, %lli

e
2.1.6 Operators and expressions

in
An operator is a symbol that instructs the compiler to perform specific mathematical or
logical functions. C language is rich in built-in operators and provides the following types
of operators −

nl
● Arithmetic Operators
● Relational Operators

O
● Logical Operators
● Bitwise Operators

it y
Assignment Operators

2.6.1 Arithmetic Operators


These operators do only basic arithmetic operations.

+
Operator
Adds two operands.
Description
rs Example
A + B = 30
ve
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
ni

Modulus Operator and remainder of after an


% B%A=0
integer division.
Increment operator increases the integer value
U

++ A++ = 11
by one.
Decrement operator decreases the integer
-- A-- = 9
value by one.
it y

2.1.6.2 Relational Operators


These operators checks the relations between two operands. If result is true then
returns 1 otherwise returns 0.
m

Operator Description Example


Checks if the values of two operands are
)A

(A == B) is
== equal or not. If yes, then the condition
not true.
becomes true.
Checks if the values of two operands are
(A != B) is
!= equal or not. If the values are not equal, then
true.
the condition becomes true.
(c

Checks if the value of left operand is greater


(A > B) is not
> than the value of right operand. If yes, then the
true.
condition be-comes true.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
20

Checks if the value of left operand is less than


Notes < the value of right operand. If yes, then the
(A < B) is
true.
condition becomes true.

e
Checks if the value of left operand is greater
(A >= B) is
>= than or equal to the value of right operand. If

in
not true.
yes, then the condition becomes true.
Checks if the value of left operand is less than
(A <= B) is
<= or equal to the value of right operand. If yes,

nl
true.
then the condition becomes true.

2.1.6.3 Logical Operators

O
These operators performs logical operations.

Operator Description Example

it y
Called Logical AND operator. If both the
(A && B) is
&& operands are non-zero, then the condition
false.
becomes true.
Called Logical OR Operator. If any of the
(A || B) is
||
becomes true.
rs
two operands is non-zero, then the condition

Called Logical NOT Operator. It is used to


reverse the logical state of its operand. If a
true.

!(A && B) is
ve
!
condition is true, then Logical NOT operator true.
will make it false.

2.1.6.4 Bitwise Operators


ni

1. In C, the bitwise AND (&) takes two numbers as operands and does AND operation
on every bit of two numbers. If both bits are 1then The result comes as 1 in this
operation.
U

2. In C, the bitwise OR ( | ) takes two numbers as operands and does OR operation on


every bit of two numbers. If any of the two bits is 1 then the result comes as 1 in this
operation.
3. The bitwise XOR (^) in C takes two numbers as operands and perform XOR operation
it y

on every bit of two numbers. If the two bits are different then the result of XOR comes
as 1.
4. The left shift (<< ) operator in C takes two numbers and left shifts the bits of the first
operand, the second operand decides the number of places to shift.
5. The right shift ( >> ) in C takes two numbers and right shifts the bits of the first
m

operand, the second operand decides the number of places to shift.


6. The bitwise NOT (~) in C takes one number and inverts all bits of it
)A

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
(c

1 0 0 1 1

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
21
2.1.6.5 Assignment Operators
Notes
Operator Description Example

e
C = A + B will
Simple assignment operator. Assigns values assign the

in
=
from right side operands to left side operand value of A + B
to C
Add AND assignment operator. It adds the C += A is

nl
+= right op-erand to the left operand and assign equivalent to
the result to the left operand. C=C+A
Subtract AND assignment operator. It
C -= A is

O
subtracts the right operand from the left
-= equivalent to
operand and assigns the result to the left
C=C-A
operand.
Multiply AND assignment operator. It multiplies C *= A is

it y
*= the right operand with the left operand and equivalent to
assigns the result to the left operand. C=C*A
Divide AND assignment operator. It divides C /= A is
/= the left operand with the right operand and equivalent to
assigns the result to the left operand. C=C/A

%=
Modulus AND assignment operator. It takes
modulus using two operands and assigns the
result to the left operand.
rs
C %= A is
equivalent to
C=C%A
ve
C <<= 2 is
<<= Left shift AND assignment operator. same as C =
C << 2
C >>= 2 is
ni

>>= Right shift AND assignment operator. same as C =


C >> 2
C &= 2 is
&= Bitwise AND assignment operator. same as C =
U

C&2

Example 1: Arithmetic Operators


it y

// Working of arithmetic operators

#include <stdio.h>

int main()
m

int a = 9,b = 4, c;
)A

c = a+b;

printf(“a+b = %d \n”,c);
(c

c = a-b;

printf(“a-b = %d \n”,c);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
22
c = a*b;
Notes
printf(“a*b = %d \n”,c);

e
c = a/b;

in
printf(“a/b = %d \n”,c);

c = a%b;

nl
printf(“Remainder when a divided by b = %d \n”,c);

O
return 0;

it y
Output :

a+b = 13

rs
a-b = 5

a*b = 36

a/b = 2
ve
Remainder when a divided by b=1

Example 2: Increment and Decrement Operators


ni

// Working of increment and decrement operators

#include <stdio.h>
U

int main()

{
it y

int a = 10, b = 100;

float c = 10.5, d = 100.5;

printf(“++a = %d \n”, ++a);


m

printf(“--b = %d \n”, --b);

printf(“++c = %f \n”, ++c);


)A

printf(“--d = %f \n”, --d);

return 0;
(c

Output :

++a = 11
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
23
--b = 99
Notes
++c = 11.500000

e
--d = 99.500000

in
Example 3: Assignment Operators

// Working of assignment operators

nl
#include <stdio.h>

int main()

O
{

int a = 5, c;

it y
c = a; // c is 5

printf(“c = %d\n”, c);

c += a; // c is 10

printf(“c = %d\n”, c);

c -= a; // c is 5 rs
ve
printf(“c = %d\n”, c);

c *= a; // c is 25

printf(“c = %d\n”, c);


ni

c /= a; // c is 5

printf(“c = %d\n”, c);


U

c %= a; // c = 0

printf(“c = %d\n”, c);


it y

return 0;

Example 4: Relational Operators


m

// Working of relational operators

#include <stdio.h>
)A

int main()

int a = 5, b = 5, c = 10;
(c

printf(“%d == %d is %d \n”, a, b, a == b);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
24
printf(“%d == %d is %d \n”, a, c, a == c);
Notes
printf(“%d > %d is %d \n”, a, b, a > b);

e
printf(“%d > %d is %d \n”, a, c, a > c);

in
printf(“%d < %d is %d \n”, a, b, a < b);

printf(“%d < %d is %d \n”, a, c, a < c);

nl
printf(“%d != %d is %d \n”, a, b, a != b);

printf(“%d != %d is %d \n”, a, c, a != c);

O
printf(“%d >= %d is %d \n”, a, b, a >= b);

printf(“%d >= %d is %d \n”, a, c, a >= c);

printf(“%d <= %d is %d \n”, a, b, a <= b);

it y
printf(“%d <= %d is %d \n”, a, c, a <= c);

rs
return 0;

Output:
ve
c=5

c = 10
ni

c=5

c = 25
U

c=5

c=0
it y

Example 5: Logical Operators

// Working of logical operators


m

#include <stdio.h>

int main()
)A

int a = 5, b = 5, c = 10, result;


(c

result = (a == b) && (c > b);

printf(“(a == b) && (c > b) is %d \n”, result);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
25
result = (a == b) && (c < b);
Notes
printf(“(a == b) && (c < b) is %d \n”, result);

e
result = (a == b) || (c < b);

in
printf(“(a == b) || (c < b) is %d \n”, result);

result = (a != b) || (c < b);

nl
printf(“(a != b) || (c < b) is %d \n”, result);

result = !(a != b);

O
printf(“!(a == b) is %d \n”, result);

result = !(a == b);

printf(“!(a == b) is %d \n”, result);

it y
return 0;

rs
}

Output:

5 == 5 is 1
ve
5 == 10 is 0

5 > 5 is 0
ni

5 > 10 is 0

5 < 5 is 0
U

5 < 10 is 1

5 != 5 is 0

5 != 10 is 1
it y

5 >= 5 is 1

5 >= 10 is 0
m

5 <= 5 is 1

5 <= 10 is 1
)A

Example 6: sizeof Operator

#include <stdio.h>

int main()
(c

int a;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
26
float b;
Notes
double c;

e
char d;

in
printf(“Size of int=%lu bytes\n”,sizeof(a));

printf(“Size of float=%lu bytes\n”,sizeof(b));

nl
printf(“Size of double=%lu bytes\n”,sizeof(c));

printf(“Size of char=%lu byte\n”,sizeof(d));

O
return 0;

it y
Output :
Size of int = 4 bytes

Size of float = 4 bytes

Size of double = 8 bytes

Size of char = 1 byte rs


ve
2.1.7 Managing Input and output Operation
Input means to provide the program with some data to be utilized in the program
and Output means to display data on screen or write the data to a printer or a file.
ni

C programming language provides many built-in functions to read any given input
and to demonstrate data on screen when there is a need to output the result.

In this tutorial, we will understand about such functions, which can be utilized in our
U

program to take input from user and to output the result on screen.

All these built-in functions are present in C header files, will also specify the name
of header files in which a specific function is defined while reviewing about it.
it y

scanf() and printf() functions

The standard input-output header file, named stdio.h encompasses the definition of the
functions printf() and scanf(), which are used to display output on screen and to take input
m

from user correspondingly.

#include <stdio.h>
)A

int main()

float num1;
(c

double num2;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
27
printf(“Enter a number: “);
Notes
scanf(“%f”, &num1);

e
printf(“Enter another number: “);

in
scanf(“%lf”, &num2);

nl
printf(“num1 = %f\n”, num1);

printf(“num2 = %lf”, num2);

O
return 0;

it y
Output:

Enter a number: 12.523

Enter another number: 10.2

num1 = 12.523000 rs
ve
num2 = 10.200000
When you will compile the above code, it will require you to enter a value. When
you will enter the value, it will display the value you have entered on screen.
ni

You must be wondering what is the purpose of %d inside the scanf() or printf()
functions. It is known as format string and this informs the scanf() function, what type
of input to expect and in printf() it is used to give a heads up to the compiler, what type
of output to expect.
U

Format String Meaning


%d Scan or print an integer as signed decimal number
it y

%f Scan or print a floating point number


%c To scan or print a character
To scan or print a character string. The scanning
%s
ends at whitespace.
m

getchar() & putchar() functions


)A

The getchar() function takes a character from the terminal and returns it as an
integer. This function takes only single character at a time. This method can be utilized
in a loop in case you want to read more than one character. The putchar() function
displays the character passed to it on the screen and returns the same character. This
function too exhibits only a single character at a time. In case you want to exhibit more
than one characters, apply putchar() method in a loop.
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
28
gets() & puts() functions
Notes
The gets() function recites a line from stdin(standard input) into the buffer pointed to

e
by str pointer, until either a terminating newline or EOF (end of file) occurs. The puts()
function transcribes the string str and a trailing newline to stdout.

in
formatting I/O
C language extend console input/output functions. As the name reveals, the console input/

nl
output functions permit us to -
● Read the input from the keyboard by the user accessing the console.

O
● Exhibit the output to the user at the console.
Note : These input and output values could be of any primitive data type.

There are two kinds of console input/output functions -

it y
● Formatted input/output functions.
● Unformatted input/output functions.

rs
Functions Description
This function is utilized to read one or multiple inputs from the
scanf()
user at the console.
ve
This function is utilized to display one or multiple values in the
printf()
output to the user at the console.
This function is utilized to read the characters from a string
sscanf()
and stores them in variables.
ni

This function is utilized to read the values stored in various


sprintf()
varia-bles and store these values in a character array.
U

Activity :
1. What would be the output of the program ?
int main()
it y

{
int a = 1;
int b = 1;
m

int c = a || --b;
int d = a-- && --b;
printf(“a = %d, b = %d, c = %d, d = %d”, a, b, c, d);
)A

return 0;
}
Answer : a = 0, b = 0, c = 1, d = 0
(c

2. What will be the output of the C program?


#include <stdio.h>

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
29
int main()
{
Notes

e
int i = 3;
printf(“%d”, (++i)++);

in
return 0;
}

nl
Answer : Compile-time error
3. What will be the output of the C program?
#include <stdio.h>

O
int main()
{

it y
int a = 10, b = 20, c = 30;
if (c > b > a)
printf(“TRUE”);

else

return 0;
printf(“FALSE”);
rs
ve
}

Answer : FALSE
ni

4. Assume size of an integer as 4 bytes. What will be the output of the C program?

#include <stdio.h>
U

int main()

int i = 5, j = 10, k = 15;


it y

printf(“%d “, sizeof(k /= i + j));

printf(“%d”, k);

return 0;
m

Answer : 4 15
)A

1. What will be the output of the C program?

#include<stdio.h>

int main()
(c

int class;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
30
int public = 5;
Notes
int private = 10;

e
int protected = 15;

in
class = public + private + protected;

printf(“%d”,class);

nl
return 0;

Answer : 5

O
2. Write a program in C to show the behavior of relational operators.
3. Write a program in C to show the behavior of logical operators.
4. Write a program in C to show the behavior of assignment operators.

it y
rs
ve
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
31
Model III: Fundamental Features in C
Notes

e
in
Course Content:
● C Statements
● conditional executing using if, else, nesting of if, switch and break

nl
● Concepts of loops, example of loops in C using for, while and do-while, continue
and break

O
● Storage types (automatic, register etc.)
● predefined processor
● Command Line Argument

it y
Key Learning Objective :
1. Better understanding of C statements.
2. Concept of various control statements of C
3. Concept of different types of loops
4. Understanding of continue and break statements rs
ve
5. Understanding of concept of Storage Types
6. Concept of fundamentals as pre processors and command line argument.
7. Command line argument concept
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
32
UNIT 3.1: C Statements
Notes

e
Unit Outcomes :

in
At the end of this unit, you will be able to:
1. Understanding of if-else statement
2. Concept of switch-case and break

nl
3. Concept of different types of loops
4. Understanding of Storage types
5. Concept of predefined processor

O
6. Understanding of command line arguments
7. Apply the concept in developing applications

it y
3.1.1 C Statements
A statement is a command that user gives to the computer in order to get an output
and that command instructs the computer to take a specific action, such as display to
the screen, or collect input. A computer program is made up of a series of statements.

rs
C statements can be of Labeled statement, Compound statement, Expression
statement, Selection statements, Iteration statements and Jump statements.
ve
Labeled Statement
When a statement is preceded by a label, it is known as labeled statement. A simple
identifier followed by : (colon) is a label. Generally we use label in goto statement and
switch-case statements
ni

Compound Statement
When multiple statements is grouped into a single statements, it is known as
U

compound statement. For example, body of function can be consider as compund


statement.

Expression Statement
it y

Expression statement consists of an expression followed by ; (semi colon), if no


expression is there then it is known as null statement. Generally, statement may have a
value when expression is present.

Example:
m

printf(“Hello C language”); is an expression statement.


)A

Selection Statement
Under this division, if, if..else and switch statement fall. Which we are going to learn
in the next part.

Iteration Statement
(c

Generally iteration statements consists of for loop, while loop and do..while loop.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
33
Jump Statement
C language has jump statements by which user can jump from one part of the
Notes
program to another part and to avail this facility C uses goto, break, continue and return

e
expression.

in
3.1.2 Conditional executing
Conditional statements instructs a computer to execute a certain block of code till a

nl
certain condition has been met.

3.1.2.1 Basic if Syntax

O
The if statement permits to control if a program arrives a section of code or not
based on whether a given condition is true or false. One of the crucial functions of the
if statement is that it agrees the program to decide on an action based upon the user’s
input.

it y
The structure of an if statement is as follows:

if ( statement is TRUE )

Execute this line of code

Here is a simple example that shows the syntax:

if ( 5 < 10 )
rs
ve
printf( “Five is now less than ten, that’s a big surprise” );

else syntax
ni

Every So Often when the condition in an if statement calculates to false, it would


be wonderful to execute some code instead of the code executed when the statement
appraises to true. The “else” statement efficiently declares that whatever code after it
(whether a single line or code between brackets) is executed if the if statement is False.
U

It looks like this:

if ( TRUE ) {
it y

/* Execute these statements if TRUE */

else {
m

/* Execute these statements if FALSE */

}
)A

else if syntax
An Additional usage of else is when there are multiple conditional statements that
may all assess to true, yet you want only one if statement’s body to execute. You can
make use of an “else if” statement following an if statement and its body; that way, if
(c

the first statement is true, the “else if” will be overlooked, but if the if statement is false,
it will then check the condition for the else if statement. If the if statement was true, the
else statement will not be verified. It is conceivable to use numerous else if statements
to ensure that only one block of code is executed.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
34
Let’s look at a simple program for you to try out on your own.
Notes
#include <stdio.h>

e
int main() {

in
int number1, number2;

printf(“Enter two integers: “);

nl
scanf(“%d %d”, &number1, &number2);

O
//checks if the two integers are equal.

if(number1 == number2) {

printf(“Result: %d = %d”,number1,number2);

it y
}

rs
//checks if number1 is greater than number2.

else if (number1 > number2) {

printf(“Result: %d > %d”, number1, number2);


ve
}
ni

//checks if both test expressions are false

else {
U

printf(“Result: %d < %d”,number1, number2);

}
it y

return 0;

}
m

Output:
)A

Enter two integers: 12

23
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
35
Result: 12 < 23
Notes

e
in
nl
O
it y
Fig 3.1: Flow chart of conditional statement

if (test-expression) rs
ve
{

//will be executed for True block of statements

}
ni

else

{
U

//will be executed for False block of statements

}
it y

Statements;

Nested if-else Statements

When a sequence of decision is required, nested if-else is applied. Nesting implies using
m

one if-else construct within another one.

Let us create a program to illustrate the use of nested if-else.


)A

#include<stdio.h>

int main()

int num=1;
(c

if(num<10)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
36
if(num==1)
Notes
{

e
printf(“The value is:%d\n”,num);

in
}

else

nl
{

printf(“The value is greater than 1”);

O
}

else

it y
{

printf(“The value is greater than 10”);

rs
}

return 0;

}
ve
3.2.2 switch statement
ni

A switch statement permits a variable to be tested against numerous values for


equality. Each of these values is called a case. As Soon As a matching case is found,
its block of code is executed. It is an complementary to the more common if-else
U

statement

switch(expression)
it y

case constant_1 :

// Code to be executed if expression == constant_1


m

break;
)A

case constant_2 :

// Code to be executed if expression == constant_2;

break;
(c

default : // the default case is optional

// Code to be executed if none of the cases match.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
37
There are several rules to keep in mind while writing switch statements:
● The expression in the switch can be a variable or an expression - but it ought to be
Notes
an integer or a character.

e
● You can have any quantity of cases however there should not be any reproductions.

in
Switch statements can also be nested within each other.
● The optional default case is executed when none of the cases above match.
● The break statement is utilized to break the flow of control once a case block is

nl
executed. While it is not obligatory, without it, all subsequent cases after the
matching case will also get executed. Think About the code below to get a clearer
idea:

O
Example:

int main() {

it y
int var = 10;

switch (var)

case 5:

printf(“Case 1 executed.”); rs
ve
// break;

case 10:

printf(“Case 2 executed. “);


ni

// break;

case 15:
U

printf(“Case 3 executed. “);

// break;
it y

case 20:

printf(“Case 4 executed. “);

// break;
m

default:

printf(“Default case executed. “);


)A

Output : Case 2 executed


(c

// Program to create a simple calculator

#include <stdio.h>

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
38
int main() {
Notes
char operator;

e
double n1, n2;

in
printf(“Enter an operator (+, -, *, /): “);

scanf(“%c”, &operator);

nl
printf(“Enter two operands: “);

scanf(“%lf %lf”,&n1, &n2);

O
switch(operator)

case ‘+’:

it y
printf(“%.1lf + %.1lf = %.1lf”,n1, n2, n1+n2);

break;

case ‘-’:

printf(“%.1lf - %.1lf = %.1lf”,n1, n2, n1-n2);


rs
ve
break;
ni

case ‘*’:

printf(“%.1lf * %.1lf = %.1lf”,n1, n2, n1*n2);


U

break;

case ‘/’:
it y

printf(“%.1lf / %.1lf = %.1lf”,n1, n2, n1/n2);

break;
m

// operator doesn’t match any case constant +, -, *, /

default:
)A

printf(“Error! operator is not correct”);

return 0;

}
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
39
Output:
Notes
Enter an operator (+, -, *,): -

e
Enter two operands: 32.5

in
12.4

32.5 - 12.4 = 20.1

nl
3.1.3 Concept of Loops
A Loop implements the sequence of statements several times until the stated

O
condition becomes false. A loop comprises of two parts, a body of a loop and a control
statement. The control statement is a blend of some conditions that direct the body of
the loop to execute until the specified condition becomes false. The objective of the
loop is to replicate the same code a number of times.

it y
Hinge On the position of a control statement in a program, a loop is categorized into
two types:
1. Entry controlled loop
2. Exit controlled loop

loop. It is also termed as a pre-checking loop.


rs
In an entry-controlled loop, a condition is examined before executing the body of a

In an exit-controlled loop, a condition is verified after executing the body of a loop. It


ve
is also labeled as a post-checking loop.
ni
U
it y
m

Fig 3.2: Flow chart of while loop execution


)A

‘C’ programming language affords us with three types of loop constructs:

1. The while loop

2. The do-while loop

3. The for loop


(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
40
3.1.3.1 Examples of Loops
Notes
Let us look some examples of loops in order to make our concept more clear.

e
3.1.3.1.1 while Loop and do..while loop

in
A while loop is the highly straightforward looping structure. The essential format of while
loop is as follows:

nl
while (condition) {

statements;

O
}

It is an entry-controlled loop. In while loop, a condition is calculated before

it y
processing a body of the loop. If a condition is true then and only then the body of a
loop is completed. After the body of a loop is executed then control again goes back at
the beginning, and the condition is checked if it is true, the identical process is executed
up until the condition becomes false. Once the condition becomes false, the control
turns out of the loop.

Example:

#include<stdio.h>
rs
ve
#include<conio.h>

int main()
ni

int num=1; //initializing the variable


U

while(num<=10) //while loop with condition

printf(“%d\n”,num);
it y

num++; //incrementingoperation

return 0;
m

}
)A

do..while loop

A do-while loop is like the while loop apart from that the condition is constantly executed
after the body of a loop. It is also termed an exit-controlled loop.
(c

The basic format of while loop is as follows:

do {

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
41
statements
Notes
} while (expression);

e
in
As we noticed in a while loop, the body is executed if and only if the condition is
true. In certain cases, we must execute a body of the loop at least one time even if the
condition is false. This kind of operation can be achieved by using a do-while loop.

nl
In the do-while loop, the body of a loop is continually executed at least once. After
the body is executed, then it verifies the condition. If the condition is true, then it will
once again execute the body of a loop otherwise control is shifted out of the loop.

O
Example:

#include<stdio.h>

it y
#include<conio.h>

int main()

int num=1;

do

{
//initializing the variable

//do-while loop rs
ve
printf(“%d\n”,2*num);

num++; //incrementingoperation
ni

}while(num<=10);

return 0;
U

3.1.3.1.2 for loop


it y

A for loop is a further effective loop structure in ‘C’ programming. The general
structure of for loop is as follows:

for (initial value; condition; incrementation or decrementation )


m

statements;
)A

● The initial value of the for loop is staged only once.


● The condition is a Boolean expression that scans and contrasts the counter to a
(c

fixed value following each iteration, stopping the for loop when false is returned.
● The incrementation/decrementation boosts (or decreases) the counter by a set
value.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
42
Example:
Notes
// Print numbers from 1 to 10

e
#include <stdio.h>

in
int main() {

nl
int i;

O
for (i = 1; i < 11; ++i)

printf(“%d “, i);

it y
}

return 0;

rs
}

Output:
ve
1 2 3 4 5 6 7 8 9 10
ni

3.1.3.1.3 continue and break statements in C language


In any loop break is utilized to jump out of loop hopping the code below it without
U

caring about the test condition.

It disrupts the flow of the program by breaking the loop and resumes the execution
of code which is outside the loop.
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
43
Syntax:
Notes
while (test_condition)

e
{

in
statement1;

if (condition )

nl
break;

statement2;

O
}

Like a break statement, continue statement is also utilized with if condition inside

it y
the loop to alter the flow of control.

When used in while, for or do...while loop, it avoids the remaining statements in the
body of that loop and performs the next iteration of the loop.

Unlike break statement, continue statement when encountered does not cease the
loop, rather interrupts a specific iteration.
rs
ve
ni
U

while (test_condition)
it y

statement1;

if (condition )
m

continue;

statement2;
)A

3.1.4 Storage Classes in C


A storage class exemplifies the visibility and a location of a variable. It tells from
(c

what part of code we can access a variable. A storage class is utilized to describe the
following things:

● The variable scope.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
44
● The place where the variable will be stored.
Notes ● The initialized value of a variable.

e
● A lifespan of a variable.

in
3.1.4.1 Automatic
● Automatic variables are allocated memory automatically at runtime.

nl
● The visibility of the automatic variables is limited to the block in which they are
defined.
● The scope of the automatic variables is limited to the block in which they are

O
defined.
● The automatic variables are initialized to garbage by default.
● The memory assigned to automatic variables gets freed upon exiting from the block.

it y
● The keyword used for defining automatic variables is auto.
● Every local variable is automatic in C by default.

3.1.4.2 Static

rs
The variables defined as static specifier can hold their value between the multiple
function calls.
ve
● Static local variables are visible only to the function or the block in which they are
defined.
● A same static variable can be declared many times but can be assigned at only one
time.
ni

● Default initial value of the static integral variable is 0 otherwise null.


● The visibility of the static global variable is limited to the file in which it has declared.
U

● The keyword used to define static variable is static.

3.1.4.3 Register
it y

● The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
● We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
m

● The access time of the register variables is faster than the automatic variables.
● The initial default value of the register local variables is 0.
)A

● The register keyword is used for the variable which should be stored in the CPU
register. However, it is compilers choice whether or not; the variables can be stored
in the register.
● We can store pointers into the register, i.e., a register can store the address of a
variable.
(c

● Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
45
3.1.4.4 External
● The external storage class is used to tell the compiler that the variable defined as
Notes
extern is declared with an external linkage elsewhere in the program.

e
● The variables declared as extern are not allocated any memory. It is only

in
declaration and intended to specify that the variable is declared elsewhere in the
program.
● The default initial value of external integral type is 0 otherwise null.

nl
● We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
● An external variable can be declared many times but can be initialized at only once.

O
● If a variable is declared as external then the compiler searches for that variable to
be initialized somewhere in the program which may be extern or static. If it is not,
then the compiler will show an error.

it y
3.1.5 Pre-processor in C
Pre-processor processes program prior to going to the compiler. You may not get it
right now but will soon comprehend what it means.

Pre-processor directives commence with a hash symbol (#). Preprocessor


directives are preprocessor commands.

The most common preprocessor directive is


rs
ve
#include

Here, #include is a preprocessor directive and it renders header file like “stdio.h” avail-
ni

able for us.

Let us take one more example of a pre-processor directive.

Here, #define is a pre-processor directive. It is employed to define something, like here


U

we have defined that PI is 3.14. So, before going to the compiler, if ‘PI’ comes anywhere
in the program, it will be replaced by 3.14.

It is dissimilar from normal variables because normal variables are processed in the course
it y

of compilation. However, anything defined in #define is substituted with its value before
compilation.

3.1.6 Command Line Arguments


m

It is feasible to pass some values from the command line to your C programs when
they are executed. These values are labeled command line arguments and several
times they are vital for the program notably when you want to control your program from
)A

elsewhere instead of hard coding those values within the code.

The command line arguments are processed using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer array
which points to every single argument passed to the program. Following is a simple
example which verifies if there is any argument delivered from the command line and
(c

take action appropriately.

Example:

#include <stdio.h>
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
46
int main( int argc, char *argv[] ) {
Notes

e
if( argc == 2 ) {

in
printf(“The argument supplied is %s\n”, argv[1]);

nl
else if( argc > 2 ) {

printf(“Too many arguments supplied.\n”);

O
}

else {

printf(“One argument expected.\n”);

it y
}

Storage class
auto
extern
It is a default storage class.
It is a global variable.
rsPurpose
ve
It is a local variable which can return a value even when
static
control is transferred to the function call.
register It is a variable which is stored inside a Register.
ni

Activities :
1. What will be the output of the C program?
U

int main()
it y

int a = 0, i = 0, b;

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


m

a++;
)A

continue;

}
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
47
Output : 5
2. What will be the output of the C program? Notes

e
int main()

in
{

int a = 0, i = 0, b;

nl
for (i = 0;i < 5; i++)

O
a++;

if (i == 3)

break;

it y
}

Output : 4

3. What will be the output of the C program? rs


ve
#include<stdio.h>

int main()

{
ni

int i;

while(0, i < 4)
U

printf(“Loop “);
it y

i++;

return 0;
m

}
)A

4. What will be the output of the C program?

int main()

{
(c

int i = 0;

do

{
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
48
i++;
Notes
if (i == 2)

e
continue;

in
printf(“In while loop “);

} while (i < 2);

nl
printf(“%d\n”, i);

O
Output : In while loop 2
5. Write a short note on pre processor directives in C.
6. Define different types of registers.

it y
7. What do you mean by command line arguments.

rs
ve
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
49
Model IV: Arrays and Functions
Notes

e
Course Content:
● Basic concept of array

in
● Use of two dimensional arrays in matrix
● Concept of sub programming

nl
● Concept of functions
● Function prototype

O
● Concept of returning of values from functions
● Passing of arguments in a function
● Recursion

it y
Key Learning Objective :
1. Understanding of concept of Arrays

rs
2. Better understanding of one dimensional and two dimensional array
3. Understanding of functions
4. Concept of function prototypes
ve
5. Understanding of how function is returning values
6. Concept of passing arguments
7. Concept of recursive function
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
50
UNIT 4.1: Arrays and Functions
Notes

e
Unit Outcomes :

in
At the end of this unit, you will be able to:
1. Define arrays
2. Define function declaration

nl
3. State function prototype
4. Define function with various types of arguments
5. State recursion

O
4.1.1 Arrays and Functions
An array is a assemblage of one or more values of the identical type. Each value is

it y
recognized as an element of the array. The elements of the array contribute to the same
variable name but each element has its own distinctive index number (also known as a
subscript). An array can be of any type, For example: int, float, char etc. If an array is of
type int then it’s elements must be of type int only.

rs
To store roll no. of 100 students, we have to declare an array of size 100 i.e roll_
no[100]. Here size of the array is 100 , so it is efficient of storing 100 values. In C, index
or subscript starts from 0, so roll_no[0] is the first element, roll_no[1] is the second
element and so on. Note that the very last element of the array will be at roll_no[99] not
ve
at roll_no[100] because the index starts at 0.

Arrays can be single or multidimensional. The number of subscript or index


defines the dimensions of the array. An array of one dimension is recognized as a one-
dimensional array or 1-D
ni

4.1.2 One-dimensional array


U

Theoretically you can think of a one-dimensional array as a row, where elements


are stored one after another.

Syntax: datatype array_name[size];


it y

datatype: It implies the type of the elements in the array.

array_name: Name of the array. It must be a valid identifier.

size: Number of elements an array can hold. here is some example of array declarations:
m

2
)A

3 int num[100];

float temp[20];

char ch[50];
(c

The elements of an array can be retrieved by specifying array name followed by


subscript or index inside square brackets (i.e []). Array subscript or index begins at 0.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
51
If the size of an array is 10 then the first element is at index 0, while the last element is
at index 9. The first legitimate subscript (i.e 0) is known as the lower bound, while last Notes
legitimate subscript is known as the upper bound.

e
int my_arr[5];

in
The following program utilizes for loop to take input and print elements of a 1-D
array.

nl
Example:

#include<stdio.h>

O
int main()

int arr[5], i;

it y
for(i = 0; i < 5; i++)

printf(“Enter a[%d]: “, i);

scanf(“%d”, &arr[i]);
rs
ve
}

printf(“\nPrinting elements of the array: \n\n”);


ni

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

printf(“%d “, arr[i]);
U

// signal to operating system program ran fine


it y

return 0;

Output:
m

Enter a[0]: 11

Enter a[1]: 22
)A

Enter a[2]: 34

Enter a[3]: 4

Enter a[4]: 34
(c

Printing elements of the array:

11 22 34 4 34

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
52
When an array is proclaimed inside a function, the elements of the array have
Notes garbage value. If an array is global or static, then its elements are automatically
initialized to 0. We can unequivocally initialize elements of an array at the time of

e
declaration using the following syntax:

in
Syntax:

datatype array_name[size] = { val1, val2, val3, ..... valN };

nl
datatype is the type of elements of an array.

array_name is the variable name, which ought to be any valid identifier.

O
size is the size of the array.

val1, val2 ... are the constants known as initializers. Each value is split up by a comma(,)
and then there is a semi-colon (;) after the closing curly brace (}).

it y
Example:

The following program finds the highest and lowest elements in an array.

#include<stdio.h>

#define SIZE 10

int main() rs
ve
{

int my_arr[SIZE] = {34,56,78,15,43,71,89,34,70,91};

int i, max, min;


ni

max = min = my_arr[0];

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


U

// if value of current element is greater than previous value


it y

// then assign new value to max

if(my_arr[i] > max)

{
m

max = my_arr[i];

}
)A

// if the value of current element is less than previous element

// then assign new value to min


(c

if(my_arr[i] < min)

min = my_arr[i];
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
53
}
Notes
}

e
printf(“Lowest value = %d\n”, min);

in
printf(“Highest value = %d”, max);

// signal to operating system everything works fine

nl
return 0;

O
Output :

Lowest value = 15

Highest value = 91

it y
4.1.3 Two Dimensional Array in C
The two-dimensional array can be described as an array of arrays. The 2D array is
organized as matrices which can be exemplified as the collection of rows and columns.
However, 2D arrays are established to implement a relational database lookalike data
rs
structure. It offers ease of holding the bulk of data at once which can be passed to any
number of functions wherever needed.
ve
The syntax to declare the 2D array is given below.
1. data_type array_name[rows][columns];
2. int twodimen[4][3];
ni

Here, 4 is the number of rows, and 3 is the number of columns.

Example:
U

Two-dimensional array example in C

#include<stdio.h>
it y

int main(){

int i=0,j=0;

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
m

//traversing 2D array

for(i=0;i<4;i++){
)A

for(j=0;j<3;j++){

printf(“arr[%d] [%d] = %d \n”,i,j,arr[i][j]);

}//end of j
(c

}//end of i

return 0;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
54
4.1.3.1 2D array example:
Notes
#include<stdio.h>

e
#define ROW 2

in
#define COL 3

nl
int main()

O
int mat1[ROW][COL], mat2[ROW][COL], mat3[ROW][COL];

int i, j;

it y
printf(“Enter first matrix: \n\n”);

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

for(j = 0; j < COL; j++)


rs
ve
{

printf(“Enter a[%d][%d]: “, i, j);


ni

scanf(“%d”, &mat1[i][j]);

}
U

}
it y

printf(“\nEnter Second matrix: \n\n”);

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


m

for(j = 0; j < COL; j++)


)A

printf(“Enter a[%d][%d]: “, i, j);

scanf(“%d”, &mat2[i][j]);
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
55
// add mat1 and mat2
Notes

e
for(i = 0; i < ROW; i++)

in
{

for(j = 0; j < COL; j++)

nl
{

mat3[i][j] = mat1[i][j] + mat2[i][j] ;

O
}

it y
printf(“\nResultant array: \n\n”);

rs
// print resultant array

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


ve
{

for(j = 0; j < COL; j++)


ni

printf(“%5d “, mat3[i][j]);
U

printf(“\n”);

}
it y

// signal to operating system program ran fine

return 0;
m

Output:
)A

Enter first matrix:

Enter a[0][0]: 12

Enter a[0][1]: 32
(c

Enter a[0][2]: 13

Enter a[1][0]: 35

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
56
Enter a[1][1]: 54
Notes
Enter a[1][2]: 35

e
in
Enter Second matrix:

Enter a[0][0]: 57

nl
Enter a[0][1]: 64

Enter a[0][2]: 58

O
Enter a[1][0]: 72

Enter a[1][1]: 84

Enter a[1][2]: 29

it y
Resultant array:

rs
mat1 + mat2 =

69 96 71
ve
107 138 64

Matrix multiplication in C
ni

We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input
from the user for row number, column number, first matrix elements and second matrix
elements. Then we are performing multiplication on the matrices entered by the user.
U

In matrix multiplication first matrix one row element is multiplied by second matrix all
column elements.

Let’s try to understand the matrix multiplication of 2*2 and 3*3 matrices by the figure
it y

given below:
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
57
Example:
Notes
#include<stdio.h>

e
#include<stdlib.h>

in
int main(){

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;

nl
system(“cls”);

printf(“enter the number of row=”);

O
scanf(“%d”,&r);

printf(“enter the number of column=”);

scanf(“%d”,&c);

it y
printf(“enter the first matrix element=\n”);

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

rs
{

for(j=0;j<c;j++)

{
ve
scanf(“%d”,&a[i][j]);

}
ni

printf(“enter the second matrix element=\n”);


U

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

for(j=0;j<c;j++)
it y

scanf(“%d”,&b[i][j]);
m

}
)A

printf(“multiply of the matrix=\n”);

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

{
(c

for(j=0;j<c;j++)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
58
mul[i][j]=0;
Notes
for(k=0;k<c;k++)

e
{

in
mul[i][j]+=a[i][k]*b[k][j];

nl
}

O
//for printing result

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

it y
for(j=0;j<c;j++)

rs
printf(“%d\t”,mul[i][j]);

printf(“\n”);
ve
}

return 0;
ni

4.1.4 Function
U

A function is a cluster of statements that together accomplish a task. Every C


program has at least one function, which is main(), and all the most trivial programs can
define additional functions.
it y

Code can be separated into separate functions. How you divide up your code
among various functions is up to you, but rationally the division is such that each
function presents a specific task.

A function declaration informs the compiler about a function’s name, return type,
m

and parameters. A function definition delivers the actual body of the function.

Functions are used because of following reasons –


a. To enhance the readability of code.
)A

b. Expands the reusability of the code, same function can be utilized in any program
rather than writing the equivalent code from scratch.
c. Debugging of the code would be simpler if you use functions, as errors are
uncomplicated to be traced.
(c

d. Decreases the size of the code, identical set of statements are substituted by function
calls.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
59
The general form of a function definition in C programming language is as follows:
Notes
return_type function_name( parameter list ) {

e
body of the function

in
}
● Return Type − A function may send back a value. The return_type is the data type
of the value the function returns. Some functions present the desired operations

nl
without returning a value. In this case, the return_type is the keyword void.
● Function Name − This is the authentic name of the function. The function name
and the parameter list collectively constitute the function signature.

O
● Parameters − A parameter is like a placeholder. When a function is stated,
you pass a value to the parameter. This value is referred to as actual parameter
or argument. The parameter list implies to the type, order, and number of the
parameters of a function. Parameters are not obligatory; that is, a function may

it y
contain no parameters.
● Function Body − The function body encompasses a collection of statements that
describe what the function does.

4.1.4.1 Function Declarations


rs
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
ve
A function declaration has the following parts −

return_type function_name( parameter list );


ni

For the above defined function max(), the function declaration is as follows −

int max(int num1, int num2);


U

4.1.4.2 Function Prototype


The Function prototype serves the following purposes –
it y

1. It reveals the return type of the data that the function will return.
2. It informs the number of arguments passed to the function.
3. It informs the data types of the each of the passed arguments.
4. Also it describes the order in which the arguments are passed to the function.
m

4.1.4.3 Calling function


While designing a C function, provide a definition of what the function must do. To
)A

use a function, you will have to call that function to perform the defined task.

When a program requests a function, the program control is shifted to the called
function. A called function implements a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns the program
control back to the main program.
(c

To call a function, pass the requisite parameters along with the function name, and
if the function returns a value, then you can store up the returned value.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
60
Example:
Notes
#include <stdio.h>

e
in
/* function declaration */

int max(int num1, int num2);

nl
int main () {

O
/* local variable definition */

int a = 100;

it y
int b = 200;

int ret;

/* calling a function to get max value */

ret = max(a, b);


rs
ve
printf( “Max value is : %d\n”, ret );
ni

return 0;
U

/* function returning the max between two numbers */


it y

int max(int num1, int num2) {


m

/* local variable declaration */

int result;
)A

if (num1 > num2)

result = num1;

else
(c

result = num2;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
61

Notes
return result;

e
}

in
Output:

Max Value is: 200

nl
4.1.4.4 Function Arguments
If a function is to make use of arguments, it must declare variables that accept the

O
values of the arguments. These variables are termed the formal parameters of the
function.

Formal parameters perform like other local variables inside the function and are
formed upon entry into the function and demolished upon exit.

it y
While calling a function, there are two ways in which arguments can be passed to a
function

Call by value

rs
This method copies the actual value of an argument into the formal parameter of
the function. In this case, changes made to the parameter inside the function have no
effect on the argument.
ve
Call by reference
This method duplicates the address of an argument into the formal parameter.
Inside the function, the address is utilized to access the actual argument used in the
call. This suggests that changes made to the parameter influence the argument.
ni

Difference between Call by value and Call by Reference


U

● In Call by value method original value is not altered whereas, in Call by reference
method, the original value is altered.
● In Call by value, a copy of the variable is passed whereas in Call by reference, a
it y

variable itself is passed.


● In Call by value, actual and formal arguments will be generated in different memory
locations whereas in Call by reference, actual and formal arguments will be created
in the same memory location.
m

● Call by value is the default method in programming languages like C++, PHP, Visual
Basic NET, and C# whereas Call by reference is supported only Java language.

)A

Call by Value, variables are passed using a straightforward method whereas Call by
Reference, pointers are required to store the address of variables.

Local Variables
Variables that are announced inside a function or block are termed local variables.
(c

They can be utilized only by statements that are inside that function or block of code.
Local variables are not known to functions beyond their own. The following example
discloses how local variables are used. Here all the variables a, b, and c are local to
main() function.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
62
Global Variables
Notes Global variables are specified outside a function, generally on top of the program.
Global variables retain their values throughout the life cycle of the program and they

e
can be retrieved inside any of the functions identified for the program.

in
A global variable can be retrieved by any function. That is, a global variable is
obtainable for use throughout the complete program after its declaration.

Swapping numbers using Function Call by Value

nl
#include <stdio.h>

void swapnum( int var1, int var2 )

O
{

int tempnum ;

it y
/*Copying var1 value into temporary variable */

tempnum = var1 ;

/* Copying var2 value into var1*/


rs
ve
var1 = var2 ;

/*Copying temporary variable value into var2 */


ni

var2 = tempnum ;
U

}
it y

int main( )

int num1 = 35, num2 = 45 ;


m

printf(“Before swapping: %d, %d”, num1, num2);


)A

/*calling swap function*/

swapnum(num1, num2);

printf(“\nAfter swapping: %d, %d”, num1, num2);


(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
63
Output:
Notes

e
Before Swapping: 35 , 45

in
After Swapping: 45 ,35

nl
Example of Function call by Reference

#include <stdio.h>

O
void increment(int *var)

/* Although we are achieving the increment on variable

it y
* var, however the var is a pointer that holds the address

* of variable num, which means the increment is actually done

rs
* on the address where value of num is stored.

*/

*var = *var+1;
ve
}

int main()
ni

int num=20;
U

/* This way of calling the function is known as call by

* reference. Instead of passing the variable num, we are

* passing the address of variable num


it y

*/

increment(&num);
m

printf(“Value of num is: %d”, num);

return 0;
)A

4.1.4.5 Recursion
Recursion is the process of duplicating items in a self-similar way. In programming
languages, if a program permits you to call a function inside the same function, then
(c

it is described a recursive call of the function. Recursive functions are very beneficial
to solve many mathematical problems, such as calculating the factorial of a number,
generating Fibonacci series, etc.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
64
The following example calculates the factorial of a given number using a recursive
Notes function.

e
#include <stdio.h>

in
unsigned long long int factorial(unsigned int i) {

nl
if(i <= 1) {

return 1;

O
}

return i * factorial(i - 1);

it y
}

int main() {

int i = 3;

printf(“Factorial of %d is %d\n”, i, factorial(i));


rs
ve
return 0;

}
ni

Output :
U

Factorial of 3 is : 6
it y

4.3.5.1 How recursion works?

void recurse()
m

... .. ...
)A

recurse();

... .. ...

}
(c

int main()

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
65
{
Notes
... .. ...

e
recurse();

in
... .. ...

nl
O
it y
Activities :
Fig 4.2 : Working of recursion

1. What will be the output of the C program?


rs
ve
#include <stdio.h>
ni

void foo(int*);

int main()
U

int i = 10, *p = &i;

foo(p++);
it y

void foo(int *p)


m

printf(“%d\n”, *p);
)A

Answer : 10
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
66
2. What will be the output of the C program?
Notes
#include <stdio.h>

e
int main()

in
{

int i = 97, *p = &i;

nl
foo(&i);

printf(“%d “, *p);

O
}

void foo(int *p)

it y
int j = 2;

p = &j;

rs
printf(“%d “, *p);

Output: 2 97
ve
3. What will be the code to print 5 contains in a[4][1][0]?
ni

#include<stdio.h>

int main()

{
U

int a[1][2][3] = {0};

a[0][1][2] = 5;
it y

printf(“%d”,*(*(*(a+0)+1)+2));

return 0;
m

4. What will be the output of the C program?


)A

#include<stdio.h>

int main()

{
(c

char *ptr;

char string[] = “This is C Programming “;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
67
ptr = string;
Notes
ptr += 6;

e
printf(“%s”,ptr);

in
return 0;

nl
Answer : C Programming

O
5. What will be the output of the C program?

#include<stdio.h>

int main()

it y
{

function();

return 0;

void function()
rs
ve
{

printf(“Function in C is awesome”);
ni

Answer : Function in C is awesome


U

6. What will be the output of the C program?


it y

#include <stdio.h>

enum m{JAN, FEB, MAR};


m

enum m foo();

int main()
)A

enum m i = foo();

printf(“%d\n”, i);
(c

int foo()

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
68
{
Notes
return JAN;

e
}

in
Answer : Compile Time Error

nl
7. What will be the output of the C program?

O
#include <stdio.h>

void m(int k)

it y
printf(“hi”);

void m(double k)

printf(“hello”);
rs
ve
}

void main()
ni

m(3);

}
U

Answer : Compile Time Error


it y

8. What will be the output of the C program?

void foo();

int main()
m

void foo(int);
)A

foo(1);

return 0;

}
(c

void foo(int i)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
69
printf(“2 “);
Notes
}

e
in
Answer : 2

1. Write a program in C to find the square of any number using the function

nl
2. Write a program in C to check a given number is even or odd using the function.
3. Write a program in C to convert decimal number to binary number using the function

O
4. Write a program in C to get the largest element of an array using the function
5. Write a program in C to check armstrong and perfect numbers using the function

it y
rs
ve
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
70
Model V: Advanced features in C
Notes

e
Course Content:
● Pointers

in
● Relationship between arrays and pointers
● Argument passing using pointers

nl
● Array of pointers
● Passing arrays as arguments

O
● Strings and C string library
● Structure and Union
● Defining C structures

it y
● Placing values to members
● Array of structure
● Nested structure


Passing strings as arguments
File Handling rs
ve
Key Learning Objective :
1. Understanding of basic concept of pointers and structures
2. Concept of passing array as argument
ni

3. Understanding of String handling in C language


4. Concept of structures
5. Understand and apply various types file handling mechanism
U

6. Get familiar with Structure and Union


it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
71
UNIT 5.1: Pointers
Notes

e
Unit Outcomes :

in
At the end of this unit, you will be able to:
1. Define pointers
2. Define pointer as argument

nl
3. State function returning pointer variable
4. Use pointer to functions
5. Define how to create and use structure

O
6. State how to create union
7. Define the types of Files and usage

it y
5.1.1 Pointers
A pointer is a variable that stores the address of another variable. Dissimilar other
variables that hold values of a certain type, pointer occupies the address of a variable.
For instance, an integer variable possesses (or you can say stores) an integer value,
however an integer pointer holds the address of a integer variable.

rs
In the following program, we have a variable num of int type. The value of num is
10 and this value ought to be stored somewhere in the memory, right? A memory space
ve
is assigned for each variable that retains the value of that variable, this memory space
has an address.

For example we stay in a house and that has an address, which facilitates other
people to find our house. The similar way the value of the variable is stored in a
ni

memory address, which facilitates the C program to find that value when it is required.
U

Example:

#include <stdio.h>

int main()
it y

int num = 12;


m

printf(“Value of variable num is: %d”, num);

/* To print the address of a variable we use %p format specifier and ampersand (&)
sign just before the variable name like &num.
)A

*/

printf(“\nAddress of variable num is: %p”, &num);

return 0;
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
72
Output:
Notes
Value of variable num is: 12

e
Address of variable num is : 2293340

in
5.1.1.1 Operators that are used with Pointers
“Address of”(&) Operator

nl
We have previously seen in the first example that we can exhibit the address of a
variable using ampersand sign. &num is used to retrieve the address of variable num.
The & operator is also identified as “Address of” Operator.

O
printf(“Address of var is: %p”, &num);

it y
“Value at Address”(*) Operator

The * Operator is also known as Value at address operator.

rs
5.1.1.2 How to declare a pointer?
int *p1 /*Pointer to an integer variable*/

double *p2 /*Pointer to a variable of data type double*/


ve
char *p3 /*Pointer to a character variable*/

float *p4 /*pointer to a float variable*/


ni

Example of Pointer demonstrating the use of & and *


U

#include <stdio.h>

int main()

{
it y

//Pointer of integer type, this can hold the address of a integer type variable.

int *p;
m

int var = 10;


)A

/* Assigning the address of variable var to the pointer * p. The p can hold the address
of var because var is an integer type variable.

*/
(c

p= &var;

printf(“Value of variable var is: %d”, var);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
73
printf(“\nValue of variable var is: %d”, *p);
Notes
printf(“\nAddress of variable var is: %p”, &var);

e
printf(“\nAddress of variable var is: %p”, p);

in
printf(“\nAddress of pointer p is: %p”, &p);

return 0;

nl
}

5.1.2 Arrays and Pointers

O
An array is a block of sequential data. Let us write a program to publish addresses
of array elements.

#include <stdio.h>

it y
int main() {

int x[4];

rs
int i;

for(i = 0; i < 4; ++i) {


ve
printf(“&x[%d] = %p\n”, i, &x[i]);

}
ni

printf(“Address of array x: %p”, x);


U

return 0;

}
it y

x
There is a disparity of 4 bytes between two consecutive elements of array x. It is
because the size of int is 4 bytes (on our compiler).
&x[0] x x
m

Notice that, the address of &x[0] and x is the same. It’s because the variable name
x points to the first element of the array.
)A
(c

Example: Pointers and Arrays

#include <stdio.h>

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
74
int main() {
Notes
int i, x[6], sum = 0;

e
printf(“Enter 6 numbers: “);

in
for(i = 0; i < 6; ++i) {

// Equivalent to scanf(“%d”, &x[i]);

nl
scanf(“%d”, x+i);

O
// Equivalent to sum += x[i]

sum += *(x+i);

it y
printf(“Sum = %d”, sum);

return 0;

rs
}

Output:
ve
Enter 6 numbers: 2

3
ni

4
U

12

Sum = 29
it y

5.1.3 Pointers as Function Argument


m

Pointer as a function parameter is utilized to hold addresses of arguments passed


through function call. This is also identified as call by reference. When a function is
called by reference any adjustment made to the reference variable will alter the original
)A

variable.

Swapping two numbers using Pointer

Example:
(c

#include <stdio.h>

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
75
void swap(int *a, int *b);
Notes

e
int main()

in
{

int m = 10, n = 20;

nl
printf(“m = %d\n”, m);

printf(“n = %d\n\n”, n);

O
swap(&m, &n); //passing address of m and n to the swap function

printf(“After Swapping:\n\n”);

it y
printf(“m = %d\n”, m);

printf(“n = %d”, n);

rs
return 0;

}
ve
// pointer ‘a’ and ‘b’ holds and points to the address of ‘m’ and ‘n’
ni

void swap(int *a, int *b)

{
U

int temp;

temp = *a;

*a = *b;
it y

*b = temp;

}
m

Output:
)A

After Swapping : 20 10

5.1.4 Functions returning Pointer variables


A function can likewise return a pointer to the calling function. In this case you must
be cautious, because local variables of function doesn’t exist outside the function. They
(c

have scope only inside the function. Therefore if you return a pointer linked to a local

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
76
variable, that pointer will be pointing to nothing when the function culminates.
Notes
Example:

e
#include <stdio.h>

in
int* larger(int*, int*);

nl
void main()

O
{

int a = 15;

it y
int b = 92;

int *p;

p = larger(&a, &b);

}
printf(“%d is larger”,*p);

rs
ve
int* larger(int *x, int *y)

{
ni

if(*x > *y)

return x;
U

else

return y;
it y

Output:
m

92 is larger

5.1.5 Pointer to functions


)A

It is feasible to declare a pointer pointing to a function which can be utilized as an


argument in another function. A pointer to a function is proclaimed as follows,

type (*pointer-name)(parameter);
(c

Here is an example :

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
77
int (*sum)(); //legal declaration of pointer to function
Notes
int *sum(); //This is not a declaration of pointer to function

e
A function pointer can point to a specific function when it is assigned the name of that
function.

in
int sum(int, int);

int (*s)(int, int);

nl
s = sum;

O
Example of Pointer to Function

it y
#include <stdio.h>

int sum(int x, int y)

return x+y; rs
ve
}

int main( )
ni

int (*fp)(int, int);


U

fp = sum;

int s = fp(10, 15);


it y

printf(“Sum is %d”, s);

return 0;
m

}
)A

Output:

Sum is 25
A string in the C language is merely an array of characters. Strings ought to have a
NULL or \0 character after the last character to indicate where the string ends. A string
(c

can be asserted as a character array or with a string pointer. Earliest, we take a look at
a character array example:

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
78
char mystr[20];
Notes

e
As you can realize the character array is declared in the identical way as a normal
array. This array can take in only 19 characters, because we ought to leave room for the

in
NULL character.

Example:

nl
#include<stdio.h>

O
int main()

char mystring[20];

it y
mystring[0] = ‘H’;

rs
mystring[1] = ‘E’;

mystring[2] = ‘L’;

mystring[3] = ‘L’;
ve
mystring[4] = ‘O’;

mystring[5] = ‘\n’;
ni

mystring[6] = ‘\0’;
U

printf(“%s”, mystring);
it y

return 0;

}
m

Output:

HELLO
)A

%s is used to print a string. (The 0 without the ” will in most cases also work).
String pointers are proclaimed as a pointer to a char. When there is a value
allocated to the string pointer the NULL is put at the end inevitably.

Example:
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
79
#include<stdio.h>
Notes
int main()

e
{

in
char *ptr_mystring;

nl
ptr_mystring = “HELLO”;

printf(“%s\n”, ptr_mystring);

O
return 0;

it y
It is not feasible to read, with scanf, a string with a string pointer. You must utilize a
character array and a pointer.

Example:

#include<stdio.h> rs
ve
int main()

{
ni

char my_array[10];

char *ptr_section2;
U

printf(“Type hello and enter\n”);


it y

scanf(“%s”, my_array);

ptr_section2 = my_array;

printf(“%s\n”, ptr_section2);
m

return 0;
)A

string.h or strings.h
The C language offers no unequivocal support for strings in the language itself. The
string-handling functions are applied in libraries. String I/O operations are implemented
(c

in <stdio.h> (puts , gets, etc). A set of simple string manipulation functions are
employed in <string.h>, or on some systems in <strings.h>.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
80
The string library (string.h or strings.h) has some handy functions for working with
Notes strings, like strcpy, strcat, strcmp, strlen, strcoll, etc. We will look at a few of these string
operations.

e
in
strcpy
This library function is utilized to copy a string and can be applied like this:
strcpy(destination, source). (It is not possible in C to do this: string1 = string2). Glance

nl
at the following example:

str_one = “abc”;

O
str_two = “def”;

strcpy(str_one , str_two); // str_one becomes “def”

it y
strcmp
This library function is managed to compare two strings and can be applied like this:
strcmp(str1, str2).


returned. rs
If the first string is bigger than the second string a number more than null is

If the first string is less than the second string a number less than null is returned.
ve
● If the first and the second string are identical, a null is returned.

Take look at an example:


ni

printf(“Enter you name: “);

scanf(“%s”, name);
U

if( strcmp( name, “jane” ) == 0 )

printf(“Hello, jane!\n”);
it y

strcat
This library function concatenates a string onto the end of the new string. The result
is returned. Look at the example:
m

printf(“Enter you age: “);

scanf(“%s”, age);
)A

result = strcat( age, “ years old.” ) == 0 )

printf(“You are %s\n”, result);

Note: strcat() will not accomplish any boundary checking, and thus there is a threat of
(c

overrunning the strings.

strlen

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
81
This library function put back the length of a string. (All characters before the null
termination.) View at the example: Notes

e
name = “jane”;

in
result = strlen(name); //Will return size of four.

nl
5.1.6 Structure and Union in C

O
In C we have container for mutually i.e. for same type data and multiple type data.
Storage of data of same type, C offers concept of Array which stores data variables
of identical type while for storing data of different type C has concept of structure and
union that can store data variable of different type as well.

it y
Ever Since both Structure and Union can hold various type of data in them but now
based on internal implementation, we can find numerous differences in both containers.

Structure is the container well-defined in C to store data variables of different type


and supports for the user defined variables storage.

rs
On other hand Union is also similar kind of container in C which can also holds the
different type of variables along with the user defined variable
ve
5.1.6.1 How to create a structure?
‘struct’ keyword is used to create a structure. Following is an example.
ni

struct address

char name[50];
U

char street[100];

char city[50];
it y

char state[20];

int pin;

};
m
)A

5.1.6.2 How to declare structure variables?


A structure variable can either be declared with structure declaration or as a
separate declaration like basic types.

Example:
(c

// A variable declaration with structure declaration.

struct Point

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
82
{
Notes
int x, y;

e
} p1; // The variable p1 is declared with ‘Point’

in
// A variable declaration like basic data types

nl
struct Point

O
int x, y;

};

it y
int main()

rs
struct Point p1; // The variable p1 is declared like a normal variable

}
ve
5.1.6.3 How to initialize structure members?
Structure members cannot be initialized with declaration. For example, the following
ni

C program collapses in compilation.


U

struct Point

int x = 0; // COMPILER ERROR: cannot initialize members here


it y

int y = 0; // COMPILER ERROR: cannot initialize members here


m

};

5.1.6.4 How to access structure elements?


)A

Structure members are accessed using dot (.) operator.

Example:

#include<stdio.h>
(c

struct Point

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
83
{
Notes
int x, y;

e
};

in
int main()

nl
{

struct Point p1 = {0, 1};

O
// Accessing members of point p1

p1.x = 20;

it y
printf (“x = %d, y = %d”, p1.x, p1.y);

rs
return 0;

}
ve
5.1.6.5 What is an array of structures?
Similar to other primitive data types, we can create an array of structures.

Example:
ni

#include<stdio.h>
U

struct Point

{
it y

int x, y;

};
m

int main()

{
)A

// Create an array of structures

struct Point arr[10];


(c

// Access array members

arr[0].x = 10;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
84
arr[0].y = 20;
Notes

e
printf(“%d %d”, arr[0].x, arr[0].y);

in
return 0;

nl
A union is a user-defined type related to structs in C except for one important
distinction. Structs allocate sufficient space to store all its members where’s unions

O
assign the space to store merely the largest member.

5.1.7 How to define a union?

it y
We use the union keyword to define unions. Here’s an example:

union car

char name[50];

int price; rs
ve
};

5.1.7.1 Create union variables


ni

When a union is defined, it produces a user-defined type. However, no memory is


allotted. To allocate memory for a given union type and work with it, we require to create
variables.
U

Here’s how we create union variables.

union car
it y

char name[50];

int price;
m

};
)A

int main()

union car car1, car2, *car3;


(c

return 0;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
85
Access members of a union
We make use of the . operator to access members of a union. To access pointer
Notes
variables, we use also use the -> operator.

e
in
5.1.7.2 Example: Accessing Union Members
#include <stdio.h>

nl
union Job {

float salary;

O
int workerNo;

} j;

it y
int main() {

j.salary = 12.3;

// when j.workerNo is assigned a value,

// j.salary will no longer hold 12.3


rs
ve
j.workerNo = 100;
ni

printf(“Salary = %.1f\n”, j.salary);

printf(“Number of workers = %d”, j.workerNo);


U

return 0;

}
it y

Output:

Salary =12.3
m

Number of workers =100

5.1.8 C Structure and Function


)A

Here is how you can pass structures to a function

Example:

#include <stdio.h>
(c

struct student {

char name[50];

int age;
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
86
};
Notes

e
// function prototype

in
void display(struct student s);

nl
int main() {

struct student s1;

O
printf(“Enter name: “);

it y
// read string input from the user until \n is entered

// \n is discarded

rs
scanf(“%[^\n]%*c”, s1.name);

printf(“Enter age: “);


ve
scanf(“%d”, &s1.age);
ni

display(s1); // passing struct as an argument


U

return 0;

}
it y

void display(struct student s) {

printf(“\nDisplaying information\n”);
m

printf(“Name: %s”, s.name);

printf(“Age: %s”, s.age);


)A

Output :

Enter Name : Smith

Enter Age : 15
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
87
5.1.9 Array of Structures in C
An array of structures in C can be described as the collection of multiple structures
Notes
variables where each variable comprises information about different entities. The array

e
of structures in C are utilized to store information about multiple entities of different data
types. The array of structures is also well-known as the collection of structures.

in
nl
O
it y
5.1.10 How Structures are stored in Memory
Members of a structure are always stored in consecutive memory locations but the
memory occupied by each member may vary.

Example:

#include<stdio.h>
rs
ve
struct book
ni

char title[5];
U

int year;

double price;

};
it y

int main()

{
m

struct book b1 = {“Book1”, 1988, 4.51};


)A

printf(“Address of title = %u\n”, b1.title);

printf(“Address of year = %u\n”, &b1.year);

printf(“Address of price = %u\n”, &b1.price);


(c

printf(“Size of b1 = %d\n”, sizeof(b1));

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
88
// signal to operating system program ran fine
Notes
return 0;

e
}

in
5.1.11 Example using Structure and Pointer : Pointer Within

nl
Structure
#include<stdio.h>

O
struct Student

it y
int *ptr; //Stores address of integer Variable

char *name; //Stores address of Character String

}s1;

int main()
rs
ve
{
ni

int roll = 20;

s1.ptr = &roll;
U

s1.name = “Pritesh”;
it y

printf(“\nRoll Number of Student : %d”,*s1.ptr);

printf(“\nName of Student : %s”,s1.name);

return(0);
m

Output :
)A

Name of Student : Pritesh

Roll Number of Student : 20

5.1.12 C File Handling


(c

When a program is completed, the entire data is dropped. Storing in a file will
safeguard your data even if the program terminates.

If you have to enter a huge number of data, it will take a lot of time to enter them all.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
89
However, if you come up with a file containing all the data, you can effortlessly
access the contents of the file applying a few commands in C. Notes

e
5.1.12.1 Types of Files

in
When dealing with files, there are two types of files you should realize about:
1. Text files
2. Binary files

nl
1. Text files

O
Text files are the normal .txt files. You can easily create text files using any
unsophisticated text editors such as Notepad.

When you open those files, you’ll go to see all the contents within the file as plain
text. You can definitely edit or delete the contents.

it y
2. Binary files

Binary files are predominantly the .bin files in your computer.

rs
Instead of storing data in plain text, they store it in the binary form (0’s and 1’s).

5.1.12.2 File Operations


ve
In C, you can execute four major operations on files, either text or binary:
1. Creating a new file
2. Opening an existing file
ni

3. Closing a file
4. Reading from and writing information to a file
U

5.1.12.2.1 Mode of operations performed on a file in C language:


There are several modes in opening a file. Based on the mode of file, it can be
opened for reading or writing or appending the texts. They are inventoried below.
it y

● r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
● w – Opens a file in write mode. It returns null if file could not be opened. If file
exists, data are overwritten.
m

● a – Opens a file in append mode. It returns null if file couldn’t be opened.


● r+ – Opens a file for read and write mode and sets pointer to the first character in
the file.
)A

● w+ – opens a file for read and write mode and sets pointer to the first character in
the file.
● a+ – Opens a file for read and write mode and sets pointer to the first character in
the file. But, it can’t modify existing contents.
(c

When employed with files, you ought to declare a pointer of type file. This
declaration is essential for communication between the file and the program.

FILE *fptr;
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
90
Opening a file is achieved using the fopen() function described in the stdio.h header file.
Notes
The syntax for opening a file in standard I/O is:

e
ptr = fopen(“fileopen”,”mode”);

in
Closing a file is completed using the fclose() function.

nl
fclose(fptr);

O
Example 1: Write to a text file

#include <stdio.h>

it y
#include <stdlib.h>

rs
int main()

int num;
ve
FILE *fptr;
ni

// make use of appropriate location if you are using MacOS or Linux

fptr = fopen(“C:\\program.txt”,”w”);
U

if(fptr == NULL)

{
it y

printf(“Error!”);

exit(1);
m

}
)A

printf(“Enter num: “);

scanf(“%d”,&num);

fprintf(fptr,”%d”,num);
(c

fclose(fptr);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
91

Notes
return 0;

e
}

in
Example 2: Read from a text file

nl
#include <stdio.h>

O
#include <stdlib.h>

int main()

it y
{

int num;

rs
FILE *fptr;

if ((fptr = fopen(“C:\\program.txt”,”r”)) == NULL){


ve
printf(“Error! opening file”);
ni

// Program exits if the file pointer returns NULL.

exit(1);
U

fscanf(fptr,”%d”, &num);
it y

printf(“Value of n=%d”, num);


m

fclose(fptr);
)A

return 0;

Activity :
(c

1. What will be the output of the C program?

#include<stdio.h>

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
92
int main(){
Notes
int a = 130;

e
char *ptr;

in
ptr = (char *)&a;

printf(“%d “,*ptr);

nl
return 0;

O
Answer : 130

it y
2. What will be the output of the C program?

#include<stdio.h>

int main()

const int a = 5;
rs
ve
const int *ptr;

ptr = &a;
ni

*ptr = 10;

printf(“%d\n”, a);

return 0;
U

}
it y

Answer : Address

3. What will be the output of the C program?


m

#include<stdio.h>
)A

void function(char**);

int main()

{
(c

char *arr[] = { “ant”, “bat”, “cat”, “dog”, “egg”, “fly” };

function(arr);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
93
return 0;
Notes
}

e
void function(char **ptr)

in
{

char *ptr1;

nl
ptr1 = (ptr += sizeof(int))[-2];

printf(“%s\n”, ptr1);

O
}

Answer : Cat

it y
4. What will be the output of the C program?

char p[20];

char *s = “string”;
rs
ve
int length = strlen(s);

int i;
ni

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

p[i] = s[length — i];

printf(“%s”,p);
U

Answer : No output printed


it y

5. What will be the output of the C program?

#include<stdio.h>
m

void swap(char *str1, char *str2)

{
)A

char *temp = str1;

str1 = str2;

str2 = temp;
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
94
int main()
Notes
{

e
char *str1 = “Holiday”;

in
char *str2 = “Home”;

swap(str1, str2);

nl
printf(“str1 is %s, str2 is %s”, str1, str2);

return 0;

O
Answer : Holiday Home

it y
6. Write a Program using C Structure to perform the following

Details of student 1
rs
ve
Name: Jim

Roll no: 10

Marks: 34.50
ni

Enter name of student2: jack


U

Enter roll no of student2: 33

Enter marks of student2: 15.21


Details of student 2
it y

Name: jack
m

Roll no: 33

Marks: 15.21
)A

Details of student 3

Name: King
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
95
Roll no: 34
Notes
Marks: 25.21

e
in
7. Write a C program to create and store information in a text file.
8. Write a C program to read a file and store the lines into an array.
9. Write a program in C to find the content of the file and number of lines in a Text file.

nl
10. Write a program in C to count a number of words and characters in a file.
11. Write a program in C to delete a specific line from a file.

O
Mini Project in C

Here is a project we developed as mini project in C bank management system


during our first semester; it is complete and totally error-free. This project is focused
on customer account services in bank, so it is named “Customer Account Bank

it y
Management System”.

Here, you can create a new account, update information of an existing account,
view and manage transactions, check the details of an existing account, remove
existing account and view customers’ list.

rs
Overall, with this project, you can perform banking activities like in a REAL bank.
Bank management mini project in C is a console application without graphics. It is
compiled in Code::Blocks with gcc compiler.
ve
#include<stdio.h>

#include<stdlib.h>
ni

#include<windows.h>

int i,j;
U

int main_exit;

void menu();

struct date{
it y

int month,day,year;

};
m

struct {
)A

char name[60];

int acc_no,age;

char address[60];
(c

char citizenship[15];

double phone;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
96
char acc_type[10];
Notes
float amt;

e
struct date dob;

in
struct date deposit;

struct date withdraw;

nl
}add,upd,check,rem,transaction;

O
float interest(float t,float amount,int rate)

it y
float SI;

SI=(rate*t*amount)/100.0;

rs
return (SI);

}
ve
void fordelay(int j)

{ int i,k;
ni

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

k=i;
U

void new_acc()
it y

int choice;
m

FILE *ptr;
)A

ptr=fopen(“record.dat”,”a+”);

account_no:

system(“cls”);

printf(“\t\t\t\xB2\xB2\xB2\ ADD RECORD \xB2\xB2\xB2\xB2”);


(c

printf(“\n\n\nEnter today’s date(mm/dd/yyyy):”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
97
scanf(“%d/%d/%d”,&add.deposit.month,&add.deposit.day,&add.deposit.year);
Notes
printf(“\nEnter the account number:”);

e
scanf(“%d”,&check.acc_no);

in
while(fscanf(ptr,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,&add.acc_
no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.
citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.
day,&add.deposit.year)!=EOF)

nl
{

if (check.acc_no==add.acc_no)

O
{printf(“Account no. already in use!”);

fordelay(1000000000);

it y
goto account_no;

add.acc_no=check.acc_no;
rs
ve
printf(“\nEnter the name:”);

scanf(“%s”,add.name);
ni

printf(“\nEnter the date of birth(mm/dd/yyyy):”);

scanf(“%d/%d/%d”,&add.dob.month,&add.dob.day,&add.dob.year);

printf(“\nEnter the age:”);


U

scanf(“%d”,&add.age);

printf(“\nEnter the address:”);


it y

scanf(“%s”,add.address);

printf(“\nEnter the citizenship number:”);

scanf(“%s”,add.citizenship);
m

printf(“\nEnter the phone number: “);

scanf(“%lf”,&add.phone);
)A

printf(“\nEnter the amount to deposit:$”);

scanf(“%f”,&add.amt);

printf(“\nType of account:\n\t#Saving\n\t#Current\n\t#Fixed1(for 1 year)\n\t#Fixed2(for


(c

2 years)\n\t#Fixed3(for 3 years)\n\n\tEnter your choice:”);

scanf(“%s”,add.acc_type);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
98
fprintf(ptr,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.acc_no,add.
Notes name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.
phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);

e
in
fclose(ptr);

printf(“\nAccount created successfully!”);

nl
add_invalid:

printf(“\n\n\n\t\tEnter 1 to go to the main menu and 0 to exit:”);

O
scanf(“%d”,&main_exit);

system(“cls”);

if (main_exit==1)

it y
menu();

else if(main_exit==0)

else

{
close();

rs
ve
printf(“\nInvalid!\a”);

goto add_invalid;
ni

}
U

void view_list()

{
it y

FILE *view;

view=fopen(“record.dat”,”r”);

int test=0;
m

system(“cls”);

printf(“\nACC. NO.\tNAME\t\t\tADDRESS\t\t\tPHONE\n”);
)A

while(fscanf(view,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d”,&add.acc_


no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.
citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.
day,&add.deposit.year)!=EOF)
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
99
printf(“\n%6d\t %10s\t\t\t%10s\t\t%.0lf”,add.acc_no,add.name,add.address,add.
phone); Notes

e
test++;

in
fclose(view);

nl
if (test==0)

{ system(“cls”);

O
printf(“\nNO RECORDS!!\n”);}

it y
view_list_invalid:

printf(“\n\nEnter 1 to go to the main menu and 0 to exit:”);

scanf(“%d”,&main_exit);

system(“cls”);

if (main_exit==1) rs
ve
menu();

else if(main_exit==0)

close();
ni

else

{
U

printf(“\nInvalid!\a”);

goto view_list_invalid;
it y

void edit(void)
m

int choice,test=0;
)A

FILE *old,*newrec;

old=fopen(“record.dat”,”r”);

newrec=fopen(“new.dat”,”w”);
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
100
printf(“\nEnter the account no. of the customer whose info you want to change:”);
Notes
scanf(“%d”,&upd.acc_no);

e
while(fscanf(old,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d”,&add.acc_
no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.

in
citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.
day,&add.deposit.year)!=EOF)

nl
if (add.acc_no==upd.acc_no)

O
test=1;

printf(“\nWhich information do you want to change?\n1.Address\n2.Phone\n\nEnter

it y
your choice(1 for address and 2 for phone):”);

scanf(“%d”,&choice);

system(“cls”);

if(choice==1)

{ rs
ve
printf(“Enter the new address:”);

scanf(“%s”,upd.address);

fprintf(newrec,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.acc_no,add.


ni

name,add.dob.month,add.dob.day,add.dob.year,add.age,upd.address,add.citizenship,add.
phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);

system(“cls”);
U

printf(“Changes saved!”);

}
it y

else if(choice==2)

printf(“Enter the new phone number:”);


m

scanf(“%lf”,&upd.phone);

fprintf(newrec,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.


)A

acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.
citizenship,upd.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.
deposit.year);

system(“cls”);
(c

printf(“Changes saved!”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
101

Notes
}

e
else

in
fprintf(newrec,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.
acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.
citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.
deposit.year);

nl
}

fclose(old);

O
fclose(newrec);

remove(“record.dat”);

it y
rename(“new.dat”,”record.dat”);

if(test!=1)

{ system(“cls”);

printf(“\nRecord not found!!\a\a\a”);


rs
ve
edit_invalid:

printf(“\nEnter 0 to try again,1 to return to main menu and 2 to exit:”);


ni

scanf(“%d”,&main_exit);

system(“cls”);

if (main_exit==1)
U

menu();
it y

else if (main_exit==2)

close();

else if(main_exit==0)
m

edit();

else
)A

{printf(“\nInvalid!\a”);

goto edit_invalid;}

}
(c

else

{printf(“\n\n\nEnter 1 to go to the main menu and 0 to exit:”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
102
scanf(“%d”,&main_exit);
Notes
system(“cls”);

e
if (main_exit==1)

in
menu();

else

nl
close();

O
}

void transact(void)

it y
{ int choice,test=0;

FILE *old,*newrec;

rs
old=fopen(“record.dat”,”r”);

newrec=fopen(“new.dat”,”w”);
ve
printf(“Enter the account no. of the customer:”);

scanf(“%d”,&transaction.acc_no);
ni

while (fscanf(old,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d”,&add.acc_


no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.
citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.
day,&add.deposit.year)!=EOF)
U

{
it y

if(add.acc_no==transaction.acc_no)

{ test=1;

if(strcmpi(add.acc_type,”fixed1”)==0||strcmpi(add.acc_type,”fixed2”)==0||strcmpi(add.
m

acc_type,”fixed3”)==0)

{
)A

printf(“\a\a\a\n\nYOU CANNOT DEPOSIT OR WITHDRAW CASH IN FIXED


ACCOUNTS!!!!!”);

fordelay(1000000000);

system(“cls”);
(c

menu();

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
103
}
Notes
printf(“\n\nDo you want to\n1.Deposit\n2.Withdraw?\n\nEnter your choice(1 for

e
deposit and 2 for withdraw):”);

scanf(“%d”,&choice);

in
if (choice==1)

nl
printf(“Enter the amount you want to deposit:$ “);

scanf(“%f”,&transaction.amt);

O
add.amt+=transaction.amt;

fprintf(newrec,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.


acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.

it y
citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.
deposit.year);

printf(“\n\nDeposited successfully!”);

else rs
ve
{

printf(“Enter the amount you want to withdraw:$ “);

scanf(“%f”,&transaction.amt);
ni

add.amt-=transaction.amt;

fprintf(newrec,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.


U

acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.
citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.
deposit.year);

printf(“\n\nWithdrawn successfully!”);
it y

else
m

{
)A

fprintf(newrec,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.


acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.
citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.
deposit.year);

}
(c

fclose(old);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
104
fclose(newrec);
Notes
remove(“record.dat”);

e
rename(“new.dat”,”record.dat”);

in
if(test!=1)

nl
printf(“\n\nRecord not found!!”);

transact_invalid:

O
printf(“\n\n\nEnter 0 to try again,1 to return to main menu and 2 to exit:”);

scanf(“%d”,&main_exit);

system(“cls”);

it y
if (main_exit==0)

transact();

rs
else if (main_exit==1)

menu();

else if (main_exit==2)
ve
close();

else
ni

printf(“\nInvalid!”);
U

goto transact_invalid;

}
it y

else
m

printf(“\nEnter 1 to go to the main menu and 0 to exit:”);


)A

scanf(“%d”,&main_exit);

system(“cls”);

if (main_exit==1)

menu();
(c

else

close();

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
105
}
Notes

e
}

in
void erase(void)

nl
FILE *old,*newrec;

int test=0;

O
old=fopen(“record.dat”,”r”);

newrec=fopen(“new.dat”,”w”);

printf(“Enter the account no. of the customer you want to delete:”);

it y
scanf(“%d”,&rem.acc_no);

while (fscanf(old,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d”,&add.acc_


no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.
citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.
day,&add.deposit.year)!=EOF)

{
rs
ve
if(add.acc_no!=rem.acc_no)

fprintf(newrec,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d\n”,add.


acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.
ni

citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.
deposit.year);
U

else

{test++;
it y

printf(“\nRecord deleted successfully!\n”);

}
m

fclose(old);

fclose(newrec);
)A

remove(“record.dat”);

rename(“new.dat”,”record.dat”);

if(test==0)
(c

printf(“\nRecord not found!!\a\a\a”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
106
erase_invalid:
Notes
printf(“\nEnter 0 to try again,1 to return to main menu and 2 to exit:”);

e
scanf(“%d”,&main_exit);

in
if (main_exit==1)

nl
menu();

else if (main_exit==2)

O
close();

else if(main_exit==0)

erase();

it y
else

{printf(“\nInvalid!\a”);

rs
goto erase_invalid;}

else
ve
{printf(“\nEnter 1 to go to the main menu and 0 to exit:”);

scanf(“%d”,&main_exit);
ni

system(“cls”);

if (main_exit==1)
U

menu();

else

close();
it y

}
m

}
)A

void see(void)

FILE *ptr;

int test=0,rate;
(c

int choice;

float time;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
107
float intrst;
Notes
ptr=fopen(“record.dat”,”r”);

e
printf(“Do you want to check by\n1.Account no\n2.Name\nEnter your choice:”);

in
scanf(“%d”,&choice);

if (choice==1)

nl
{ printf(“Enter the account number:”);

scanf(“%d”,&check.acc_no);

O
while (fscanf(ptr,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d”,&add.acc_
no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.
citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.

it y
day,&add.deposit.year)!=EOF)

if(add.acc_no==check.acc_no)

{ system(“cls”);

test=1;
rs
ve
printf(“\nAccount NO.:%d\nName:%s \nDOB:%d/%d/%d \nAge:%d \nAddress:%s
\nCitizenship No:%s \nPhone number:%.0lf \nType Of Account:%s \nAmount deposited:$
ni

%.2f \nDate Of Deposit:%d/%d/%d\n\n”,add.acc_no,add.name,add.dob.month,add.dob.


day,add.dob.year,add.age,add.address,add.citizenship,add.phone,

add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
U

if(strcmpi(add.acc_type,”fixed1”)==0)

{
it y

time=1.0;

rate=9;

intrst=interest(time,add.amt,rate);
m

printf(“\n\nYou will get $%.2f as interest on %d/%d/%d”,intrst,add.deposit.


month,add.deposit.day,add.deposit.year+1);
)A

else if(strcmpi(add.acc_type,”fixed2”)==0)

time=2.0;
(c

rate=11;

intrst=interest(time,add.amt,rate);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
108
printf(“\n\nYou will get $.%.2f as interest on %d/%d/%d”,intrst,add.deposit.
Notes month,add.deposit.day,add.deposit.year+2);

e
}

in
else if(strcmpi(add.acc_type,”fixed3”)==0)

nl
time=3.0;

rate=13;

O
intrst=interest(time,add.amt,rate);

printf(“\n\nYou will get $.%.2f as interest on %d/%d/%d”,intrst,add.deposit.


month,add.deposit.day,add.deposit.year+3);

it y
}

else if(strcmpi(add.acc_type,”saving”)==0)

time=(1.0/12.0);
rs
ve
rate=8;

intrst=interest(time,add.amt,rate);
ni

printf(“\n\nYou will get $.%.2f as interest on %d of every month”,intrst,add.


deposit.day);
U

else if(strcmpi(add.acc_type,”current”)==0)
it y

printf(“\n\nYou will get no interest\a\a”);


m

}
)A

}
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
109
}
Notes
else if (choice==2)

e
{ printf(“Enter the name:”);

in
scanf(“%s”,&check.name);

while (fscanf(ptr,”%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d”,&add.acc_


no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.

nl
citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.
day,&add.deposit.year)!=EOF)

O
if(strcmpi(add.name,check.name)==0)

{ system(“cls”);

it y
test=1;

printf(“\nAccount No.:%d\nName:%s \nDOB:%d/%d/%d \nAge:%d \nAddress:%s \


nCitizenship No:%s \nPhone number:%.0lf \nType Of Account:%s \nAmount deposited:$%.2f
\nDate Of Deposit:%d/%d/%d\n\n”,add.acc_no,add.name,add.dob.month,add.dob.day,add.
dob.year,add.age,add.address,add.citizenship,add.phone,

rs
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
ve
if(strcmpi(add.acc_type,”fixed1”)==0)

time=1.0;
ni

rate=9;

intrst=interest(time,add.amt,rate);
U

printf(“\n\nYou will get $.%.2f as interest on %d/%d/%d”,intrst,add.deposit.


month,add.deposit.day,add.deposit.year+1);

}
it y

else if(strcmpi(add.acc_type,”fixed2”)==0)

time=2.0;
m

rate=11;
)A

intrst=interest(time,add.amt,rate);

printf(“\n\nYou will get $.%.2f as interest on %d/%d/%d”,intrst,add.deposit.


month,add.deposit.day,add.deposit.year+2);
(c

else if(strcmpi(add.acc_type,”fixed3”)==0)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
110
{
Notes
time=3.0;

e
rate=13;

in
intrst=interest(time,add.amt,rate);

printf(“\n\nYou will get $.%.2f as interest on %d/%d/%d”,intrst,add.deposit.


month,add.deposit.day,add.deposit.year+3);

nl
}

O
else if(strcmpi(add.acc_type,”saving”)==0)

it y
time=(1.0/12.0);

rate=8;

intrst=interest(time,add.amt,rate);

deposit.day);
rs
printf(“\n\nYou will get $.%.2f as interest on %d of every month”,intrst,add.
ve
}

else if(strcmpi(add.acc_type,”current”)==0)
ni

{
U

printf(“\n\nYou will get no interest\a\a”);


it y

}
m

}
)A

fclose(ptr);
(c

if(test!=1)

{ system(“cls”);

printf(“\nRecord not found!!\a\a\a”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
111
see_invalid:
Notes
printf(“\nEnter 0 to try again,1 to return to main menu and 2 to exit:”);

e
scanf(“%d”,&main_exit);

in
system(“cls”);

if (main_exit==1)

nl
menu();

else if (main_exit==2)

O
close();

else if(main_exit==0)

see();

it y
else

rs
system(“cls”);

printf(“\nInvalid!\a”);

goto see_invalid;}
ve
}

else
ni

{printf(“\nEnter 1 to go to the main menu and 0 to exit:”);

scanf(“%d”,&main_exit);}
U

if (main_exit==1)

system(“cls”);
it y

menu();

}
m

else

{
)A

system(“cls”);

close();

}
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
112
}
Notes

e
in
void close(void)

nl
printf(“\n\n\n\nThis C Mini Project is developed by Code With C team!”);

O
void menu(void)

it y
{ int choice;

system(“cls”);

rs
system(“color 9”);

printf(“\n\n\t\t\tCUSTOMER ACCOUNT BANKING MANAGEMENT SYSTEM”);

printf(“\n\n\n\t\t\t\xB2\xB2\xB2\xB2\xB2\xB2\xB2 WELCOME TO THE MAIN MENU \


ve
xB2\xB2\xB2\xB2\xB2\xB2\xB2”);

printf(“\n\n\t\t1.Create new account\n\t\t2.Update information of existing account\n\t\


t3.For transactions\n\t\t4.Check the details of existing account\n\t\t5.Removing existing
ni

account\n\t\t6.View customer’s list\n\t\t7.Exit\n\n\n\n\n\t\t Enter your choice:”);

scanf(“%d”,&choice);
U

system(“cls”);

switch(choice)
it y

case 1:new_acc();

break;
m

case 2:edit();

break;
)A

case 3:transact();

break;

case 4:see();
(c

break;

case 5:erase();

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
113
break;
Notes
case 6:view_list();

e
break;

in
case 7:close();

break;

nl
}

O
it y
}

int main()

rs
{

char pass[10],password[10]=”codewithc”;

int i=0;
ve
printf(“\n\n\t\tEnter the password to login:”);

scanf(“%s”,pass);
ni

/*do

{
U

//if (pass[i]!=13&&pass[i]!=8)

printf(“*”);
it y

pass[i]=getch();

i++;
m

}while (pass[i]!=13);
)A

pass[10]=’\0’;*/

if (strcmp(pass,password)==0)

{printf(“\n\nPassword Match!\nLOADING”);

for(i=0;i<=6;i++)
(c

fordelay(100000000);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
114
printf(“.”);
Notes
}

e
system(“cls”);

in
menu();

nl
else

{ printf(“\n\nWrong password!!\a\a\a”);

O
login_try:

printf(“\nEnter 1 to try again and 0 to exit:”);

scanf(“%d”,&main_exit);

it y
if (main_exit==1)

system(“cls”);

main();
rs
ve
}
ni

else if (main_exit==0)

{
U

system(“cls”);

close();}

else
it y

{printf(“\nInvalid!”);

fordelay(1000000000);
m

system(“cls”);

goto login_try;}
)A

return 0;

}
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
115
Functions used in Bank Management System:
Notes
The source code for Customer Account Bank Management System is relatively
short and easy to understand. I have divided this C mini project into many functions,

e
most of which are related to different banking activities. Listed below are some of the
more important functions which may help you understand the project better.

in
menu() – This function displays the menu or welcome screen to perform different
banking activities mentioned below.

nl
new_acc() – This function creates a new customer account. It asks for some
personal and banking details of the customer such as name, date of birth, citizenship
number, address and phone number. You can enter the amount to deposit and choose
one type of deposit account – saving, current, fixed for 1 year, fixed for 2 years or fixed

O
for 3 years.

view list() – With this function, you can view the customer’s banking information
such as account number, name, address and phone number provided while creating the

it y
account.

edit() – This function has been used for changing the address and phone number of
a particular customer account.

transact() – With this function, you can deposit and withdraw money to and from a
particular customer account.

erase() – This function is for deleting a customer account. rs


ve
see() – This function shows account number, name, date of birth, citizenship
number, age, address, phone number, type of account, amount deposited and date of
deposit. It also displays the amount of interest corresponding to a particular account
type.
ni

Stack Operations Project


U

A stack is an abstract data type that serves as a collection of elements, with two
principal operations: push, which adds an element to the collection, and pop, which
removes the most recently added element that was not yet removed.
it y

We start our code by including the header files “stdio.h” and “conio.h”. The code
also has a array to hold the values and the variable top for manipulation
m

struct stack /* Structure definition for stack */

{
)A

int stk[MAXSIZE];

int top;

}
(c

There are four options given to the user for executing the stack. They are Push,
Pop, Display and Exit.

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
116

Notes
while (option)

e
{

in
printf (“------------------------------------------\n”);

printf (“ 1 --> PUSH \n”);

nl
printf (“ 2 --> POP \n”);

printf (“ 3 --> DISPLAY \n”);

O
printf (“ 4 --> EXIT \n”);

printf (“------------------------------------------\n”);

it y
printf (“Enter your choice\n”);

scanf (“%d”, &choice);

rs
1

3
ve
4

5
ni

7
U

10
it y

11

while (option)
m

{
)A

printf (“------------------------------------------\n”);

printf (“ 1 --> PUSH \n”);

printf (“ 2 --> POP \n”);

printf (“ 3 --> DISPLAY \n”);


(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
117
printf (“ 4 --> EXIT \n”);
Notes
printf (“------------------------------------------\n”);

e
in
printf (“Enter your choice\n”);

scanf (“%d”, &choice)

nl
Option1 will initiate the push function

O
Option2 will initiate the pop function

Option 3 will initiate the Display function

it y
int num;

if (s.top == (MAXSIZE - 1))

printf (“Stack is Full\n”);


rs
ve
return;

}
ni

else

{
U

printf (“Enter the element to be pushed\n”);

scanf (“%d”, &num);

s.top = s.top + 1;
it y

s.stk[s.top] = num;

}
m

Option 4 will return the program from the loop and the main() will exit
)A

4
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
118
7
Notes
8

e
9

in
10

nl
switch (choice)

O
case 1: push();

break;

case 2: pop();

it y
break;

case 3: display();

rs
break;

case 4: return;

}
ve
Push function -> Its check is the stack is full or not. If not full it adds a number to the array.
Else it will display the error message of “Stack is full”.
ni

Pop function -> Its check is the stack is empty or not. If not empty it pops the last number
from the array. Else it will display the error message of “Stack is Empty”.
U

Top variable is decreased by 1 each time a value is added to the stack

int num;
it y

if (s.top == - 1)

printf (“Stack is Empty\n”);


m

return (s.top);

}
)A

else

num = s.stk[s.top];
(c

printf (“poped element is = %d\n”, s.stk[s.top]);

s.top = s.top - 1;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
119
}
Notes
return(num);

e
in
display function -> Its check is the stack is empty or not. If not empty the using a for loop it
printa all the values of the stack. Else it will display the error message of “Stack is Empty”.

int i;

nl
if (s.top == -1)

O
printf (“Stack is empty\n”);

return;

it y
}

else

printf (“\nThe status of the stack is\n”);

for (i = s.top; i >= 0; i--) rs


ve
{

printf (“%d\n”, s.stk[i]);

}
ni

printf (“\n”);
U

Mini Project in C Employee Record System


In this project, you can manage employee records – add, list, modify and delete
it y

records. Understanding this project will help you learn how to add, view, change and
remove data using file handling.

The main features of this project include basic file handling operations; you will
learn how to add, list, modify and delete data to/from file. The source code is relatively
m

short, so thoroughly go through the mini project, and try to analyze how things such as
functions, pointers, files, and arrays are implemented.

Currently, listed below are the only features that make up this project, but you can
)A

add new features as you like to make this project a better one!

● Add record
● List record
● Modify record
(c

● Delete record

#include <stdio.h> ///for input output functions like printf, scanf

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
120
#include <stdlib.h>
Notes
#include <conio.h>

e
#include <windows.h> ///for windows related functions (not important)

in
#include <string.h> ///string operations

nl
/** List of Global Variable */

COORD coord = {0,0}; /// top-left corner of window

O
/**

function : gotoxy

it y
@param input: x and y coordinates

@param output: moves the cursor in specified position of console

rs
*/

void gotoxy(int x,int y)

{
ve
coord.X = x;

coord.Y = y;
ni

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);

}
U

/** Main function started */


it y

int main()

FILE *fp, *ft; /// file pointers


m

char another, choice;


)A

/** structure that represent a employee */

struct emp

{
(c

char name[40]; ///name of employee

int age; /// age of employee

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
121
float bs; /// basic salary of employee
Notes
};

e
in
struct emp e; /// structure variable creation

nl
char empname[40]; /// string to store name of the employee

O
long int recsize; /// size of each record of employee

/** open the file in binary read and write mode

it y
* if the file EMP.DAT already exists then it open that file in read write mode

* if the file doesn’t exit it simply create a new copy

rs
*/

fp = fopen(“EMP.DAT”,”rb+”);

if(fp == NULL)
ve
{

fp = fopen(“EMP.DAT”,”wb+”);
ni

if(fp == NULL)

{
U

printf(“Connot open file”);

exit(1);

}
it y

}
m

/// sizeo of each record i.e. size of structure variable e

recsize = sizeof(e);
)A

/// infinite loop continues untile the break statement encounter

while(1)

{
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
122
system(“cls”); ///clear the console window
Notes
gotoxy(30,10); /// move the cursor to postion 30, 10 from top-left corner

e
printf(“1. Add Record”); /// option for add record

in
gotoxy(30,12);

printf(“2. List Records”); /// option for showing existing record

nl
gotoxy(30,14);

printf(“3. Modify Records”); /// option for editing record

O
gotoxy(30,16);

printf(“4. Delete Records”); /// option for deleting record

gotoxy(30,18);

it y
printf(“5. Exit”); /// exit from the program

gotoxy(30,20);

rs
printf(“Your Choice: “); /// enter the choice 1, 2, 3, 4, 5

fflush(stdin); /// flush the input buffer

choice = getche(); /// get the input from keyboard


ve
switch(choice)

{
ni

case ‘1’: /// if user press 1

system(“cls”);
U

fseek(fp,0,SEEK_END); /// search the file and move cursor to end of the file

/// here 0 indicates moving 0 distance from the end of the file
it y

another = ‘y’;

while(another == ‘y’) /// if user want to add another record


m

printf(“\nEnter name: “);


)A

scanf(“%s”,e.name);

printf(“\nEnter age: “);

scanf(“%d”, &e.age);

printf(“\nEnter basic salary: “);


(c

scanf(“%f”, &e.bs);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
123
fwrite(&e,recsize,1,fp); /// write the record in the file
Notes

e
printf(“\nAdd another record(y/n) “);

in
fflush(stdin);

another = getche();

nl
}

break;

O
case ‘2’:

system(“cls”);

rewind(fp); ///this moves file cursor to start of the file

it y
while(fread(&e,recsize,1,fp)==1) /// read the file and fetch the record one record
per fetch

rs
printf(“\n%s %d %.2f”,e.name,e.age,e.bs); /// print the name, age and basic salary

}
ve
getch();

break;
ni

case ‘3’: /// if user press 3 then do editing existing record

system(“cls”);
U

another = ‘y’;

while(another == ‘y’)
it y

printf(“Enter the employee name to modify: “);

scanf(“%s”, empname);
m

rewind(fp);

while(fread(&e,recsize,1,fp)==1) /// fetch all record from file


)A

if(strcmp(e.name,empname) == 0) ///if entered name matches with that in file

{
(c

printf(“\nEnter new name,age and bs: “);

scanf(“%s%d%f”,e.name,&e.age,&e.bs);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
124
fseek(fp,-recsize,SEEK_CUR); /// move the cursor 1 step back from cur-
Notes rent position

e
fwrite(&e,recsize,1,fp); /// override the record

break;

in
}

nl
printf(“\nModify another record(y/n)”);

fflush(stdin);

O
another = getche();

it y
break;

case ‘4’:

system(“cls”);

another = ‘y’;

while(another == ‘y’) rs
ve
{

printf(“\nEnter name of employee to delete: “);

scanf(“%s”,empname);
ni

ft = fopen(“Temp.dat”,”wb”); /// create a intermediate file for temporary storage

rewind(fp); /// move record to starting of file


U

while(fread(&e,recsize,1,fp) == 1) /// read all records from file

{
it y

if(strcmp(e.name,empname) != 0) /// if the entered record match

fwrite(&e,recsize,1,ft); /// move all records except the one that is to be


m

deleted to temp file

}
)A

fclose(fp);

fclose(ft);

remove(“EMP.DAT”); /// remove the orginal file


(c

rename(“Temp.dat”,”EMP.DAT”); /// rename the temp file to original file name

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
125
fp = fopen(“EMP.DAT”, “rb+”);
Notes
printf(“Delete another record(y/n)”);

e
fflush(stdin);

in
another = getche();

nl
break;

case ‘5’:

O
fclose(fp); /// close the file

exit(0); /// exit from the program

it y
}

return 0;

rs
}
ve
Customer Billing System C Project

Customer Billing System Project is a simple console application designed to


demonstrate the practical use of C programming language and its features as wells as
to generate an application which can be used in any departmental store, shops, cafes
ni

etc. for billing to the customer.

User Defined Functions Used:


U

Although graphics has not been used in this project, the application of user defined
functions and structures have been effectively used here. The major user defined
functions used in this C project are:
it y

● void input()
● void writefile()
● void search()

m

void output()
The function void input() is used to add the new customer account i.e. with the help
of this functions the parameters such as name, address, phone number, amount paid
)A

etc. are asked and entered. Another function void writefile() has been utilized to create
a file on hard disc of computer for storing the information and data of a customer.

The function void search() has been used to look for previously stored accounts
either by name or by number of the customer. The fourth and the last user defined
function used in this Customer Billing System Project in C is void output() which has
(c

been defined to show the result as console output.

In Customer Billing System, structure has very beautifully used to group the data
type in single unit. The date variables (day, month and year) have been grouped in the

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
126
structures named date where as other variables such as name, number, street, paid
Notes amount etc. are grouped under another structure named account.

Customer Billing System application is so simple to use. In order to use the

e
application, click at the exe file and then, you will have three options to:

in
1. To add account
2. To search account
3. To exit

nl
As per your need, enter 1, 2,or 3 and follow the instructions provided by the application itself.

O
Features:
1. It can hold any number of accounts and account can be added to the program at any
time.
2. The programming of simple calculations such as calculation of due amount, balance

it y
etc. have been embed in the code of project.
3. The Customer Billing System project in C gives you the facility of searching the
account by two ways, either by name of the customer or by the number of customer.
4. The due amount to be paid is shown as negative balance.

rs
5. If you have nothing to do with the program, you can directly exit from the main menu.
ve
#include<stdio.h>

#include<conio.h>

#include<stdlib.h>
ni

void input();
U

void writefile();

void search();
it y

void output();

struct date{
m

int month;

int day;
)A

int year;

};
(c

struct account {

int number;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
127
char name[100];
Notes
int acct_no;

e
float mobile_no;

in
char street[100];

char city[100];

nl
char acct_type;

float oldbalance;

O
float newbalance;

float payment;

struct date lastpayment;

it y
}customer;

int tl,sl,ts;

rs
void main()

int i,n;
ve
char ch;

clrscr();
ni

_setcursortype(_NOCURSOR);
U

printf(“ CUSTOMER BILLING SYSTEM:\n\n”);

printf(“===============================\n”);

printf(“\n1: to add account on list\n”);


it y

printf(“2: to search customer account\n”);

printf(“3: exit\n”);
m

printf(“\n================================\n”);

do{
)A

printf(“\nselect what do you want to do?”);

ch=getche();

}while(ch<=’0’ || ch>’3’);

switch(ch){
(c

case ‘1’:

clrscr();

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
128
printf(“\nhow many customer ac-
Notes counts?”);

e
scanf(“%d”,&n);

for(i=0;i<n;i++){

in
input();

if(customer.payment>0)

nl
customer.
acct_type=(customer.payment<0.1*customer.oldbalance)? ‘O’: ‘D’;

O
else

customer.
acct_type=(customer.oldbalance>0)?’D’ : ‘C’;

it y
c u s t o m e r .
newbalance=customer.oldbalance - customer.payment;

writefile();

rs }

main();
ve
case ‘2’:

clrscr();

printf(“search by what?\n”);
ni

printf(“\n1 --- search by customer


number\n”);

printf(“2 --- search by customer


U

name\n”);

search();
it y

ch=getche();

main();

case ‘3’:
m

clrscr();

delay(700);
)A

textcolor(RED);

gotoxy(25,25);

cprintf(“\nA PROJECT BY BIDUR &


SUJAN”);
(c

delay(1500);

exit(1);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
129
}
Notes
}

e
in
void input()

nl
{

FILE *fp=fopen(“bidur.dat”,”rb”);

O
fseek (fp,0,SEEK_END);

tl=ftell(fp);

sl=sizeof(customer);

it y
ts=tl/sl;

fseek(fp,(ts-1)*sl,SEEK_SET);

rs
fread(&customer,sizeof(customer),1,fp);

printf(“\ncustomer no:%d\n”,++customer.number);

fclose(fp);
ve
printf(“ Account number:”);

scanf(“%d”,&customer.acct_no);
ni

printf(“\n Name:”);

scanf(“%s”,customer.name);
U

printf(“\n mobile no:”);

scanf(“%f”,&customer.mobile_no);

printf(“ Street:”);
it y

scanf(“%s”,customer.street);

printf(“ City:”);
m

scanf(“%s”,customer.city);

printf(“ Previous balance:”);


)A

scanf(“%f”,&customer.oldbalance);

printf(“ Current payment:”);

scanf(“%f”,&customer.payment);

printf(“ Payment date(mm/dd/yyyy):”);


(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
130
scanf(“%d/%d/%d”,&customer.lastpayment.month,&customer.lastpayment.
Notes day,&customer.lastpayment.year);

e
return;

in
void writefile()

nl
{

FILE *fp;

O
fp=fopen(“bidur.dat”,”ab”);

fwrite(&customer,sizeof(customer),1,fp);

it y
fclose(fp);

return;

void search() rs
ve
{

char ch;

char nam[100];
ni

int n,i,m=1;

FILE *fp;
U

fp=fopen(“bidur.dat”,”rb”);

do{
it y

printf(“\nenter your choice:”);

ch=getche();

}while(ch!=’1’ && ch!=’2’);


m

switch(ch){

case ‘1’:
)A

fseek(fp,0,SEEK_END);

tl=ftell(fp);

sl=sizeof(customer);
(c

ts=tl/sl;

do{

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
131
printf(“\nchoose customer number:”);
Notes
scanf(“%d”,&n);

e
if(n<=0 || n>ts)

in
printf(“\nenter correct\n”);

else{

nl
fseek(fp,(n-1)*sl,SEEK_SET);

fread(&customer,sl,1,fp);

O
output();

printf(“\n\nagain?(y/n)”);

it y
ch=getche();

}while(ch==’y’);

rs
fclose(fp);

break;

case ‘2’:
ve
fseek(fp,0,SEEK_END);

tl=ftell(fp);
ni

sl=sizeof(customer);

ts=tl/sl;
U

fseek(fp,(ts-1)*sl,SEEK_SET);

fread(&customer,sizeof(customer),1,fp);

n=customer.number;
it y

do{
m

printf(“\nenter the name:”);

scanf(“%s”,nam);
)A

fseek(fp,0,SEEK_SET);

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

fread(&customer,sizeof(customer)
(c

,1,fp);

if(strcmp(customer.name,nam)==0)

{
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
132
output();
Notes
m=0;

e
break;

in
}

nl
if(m!=0)

printf(“\n\ndoesn’t exist\n”);

O
printf(“\nanother?(y/n)”);

ch=getche();

}while(ch==’y’);

it y
fclose(fp);

rs
return;

}
ve
ni

void output()

{
U

printf(“\n\n Customer no :%d\n”,customer.number);

printf(“ Name :%s\n”,customer.name);

printf(“ Mobile no :%.f\n”,customer.mobile_no);


it y

printf(“ Account number :%d\n”,customer.acct_no);

printf(“ Street :%s\n”,customer.street);


m

printf(“ City :%s\n”,customer.city);

printf(“ Old balance :%.2f\n”,customer.oldbalance);


)A

printf(“ Current payment:%.2f\n”,customer.payment);

printf(“ New balance :%.2f\n”,customer.newbalance);

printf(“ Payment date :%d/%d/%d\n\n”,customer.lastpayment.month,customer.


lastpayment.day,customer.lastpayment.year);
(c

printf(“ Account status :”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
133
textcolor(128+RED);
Notes
switch(customer.acct_type)

e
{

in
case ‘C’:

cprintf(“CURRENT\n\n”);

nl
break;

case ‘O’:

O
cprintf(“OVERDUE\n\n”);

break;

case ‘D’:

it y
cprintf(“DELINQUENT\n\n”);

break;

rs
default:

cprintf(“ERROR\\n\n”);

}
ve
textcolor(WHITE);

return;
ni

Quiz Game Mini Project in C


U

This is a complete and error-free Quiz Game Mini Project in C designed as a simple
console application. In this project, a number of questions are asked, and the user is
awarded cash prize for each correct answer given. n quiz game, questions are chosen
in such a a way that they cover all fields of a typical quiz contest. The user’s general
it y

knowledge is tested with quiz questions regarding science, technology, movies, sports,
general health, geography and many more.

● edit_score() – adds the current cash prize won to the previous one upon giving the
right answer to a question
m

● help() – help menu with game summary and rules


● reset_score() – to reset the highest score/cash prize to default
)A

● show_record() – shows the highest cash prize won by a particular user


● show_score() – to view the highest score
(c

#include<stdio.h>

#include<conio.h>

#include<ctype.h>

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
134
#include<stdlib.h>
Notes
#include<string.h>

e
void show_record();

in
void reset_score();

void help();

nl
void edit_score(float , char []);

int main()

O
{

int countr,r,r1,count,i,n;

float score;

it y
char choice;

char playername[20];

rs
mainhome:

system(“cls”);

printf(“\t\t\tC PROGRAM QUIZ GAME\n”);


ve
printf(“\n\t\t________________________________________”);
ni

printf(“\n\t\t\t WELCOME “);

printf(“\n\t\t\t to “);
U

printf(“\n\t\t\t THE GAME “);

printf(“\n\t\t________________________________________”);

printf(“\n\t\t________________________________________”);
it y

printf(“\n\t\t BECOME A MILLIONAIRE!!!!!!!!!!! “) ;

printf(“\n\t\t________________________________________”);
m

printf(“\n\t\t________________________________________”);

printf(“\n\t\t > Press S to start the game”);


)A

printf(“\n\t\t > Press V to view the highest score “);

printf(“\n\t\t > Press R to reset score”);

printf(“\n\t\t > press H for help “);

printf(“\n\t\t > press Q to quit “);


(c

printf(“\n\t\t________________________________________\n\n”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
135
choice=toupper(getch());
Notes
if (choice==’V’)

e
{

in
show_record();

goto mainhome;

nl
}

else if (choice==’H’)

O
{

help();getch();

goto mainhome;

it y
}

else if (choice==’R’)

rs
{reset_score();

getch();

goto mainhome;}
ve
else if (choice==’Q’)

exit(1);
ni

else if(choice==’S’)

{
U

system(“cls”);

printf(“\n\n\n\n\n\n\n\n\n\n\t\t\tResister your name:”);


it y

gets(playername);

system(“cls”);
m

printf(“\n ------------------ Welcome %s to C Program Quiz Game --------------------------”,play-


ername);

printf(“\n\n Here are some tips you might wanna know before playing:”);
)A

printf(“\n -------------------------------------------------------------------------”);

printf(“\n >> There are 2 rounds in this Quiz Game,WARMUP ROUND & CHALLANGE
ROUND”);
(c

printf(“\n >> In warmup round you will be asked a total of 3 questions to test your”);

printf(“\n general knowledge. You are eligible to play the game if you give atleast 2”);

printf(“\n right answers, otherwise you can’t proceed further to the Challenge Round.”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
136
printf(“\n >> Your game starts with CHALLANGE ROUND. In this round you will be
Notes asked a”);

e
printf(“\n total of 10 questions. Each right answer will be awarded $100,000!”);

printf(“\n By this way you can win upto ONE MILLION cash prize!!!!!..........”);

in
printf(“\n >> You will be given 4 options and you have to press A, B ,C or D for the”);

printf(“\n right option.”);

nl
printf(“\n >> You will be asked questions continuously, till right answers are given”);

printf(“\n >> No negative marking for wrong answers!”);

O
printf(“\n\n\t!!!!!!!!!!!!! ALL THE BEST !!!!!!!!!!!!!”);

printf(“\n\n\n Press Y to start the game!\n”);

it y
printf(“\n Press any other key to return to the main menu!”);

if (toupper(getch())==’Y’)

} rs goto home;
ve
else

goto mainhome;
ni

system(“cls”);

}
U

home:
it y

system(“cls”);

count=0;

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

system(“cls”);
)A

r1=i;
(c

switch(r1)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
137
case 1:
Notes
printf(“\n\nWhich of the following is a Palindrome

e
number?”);

printf(“\n\nA.42042\t\tB.101010\n\nC.23232\t\

in
tD.01234”);

if (toupper(getch())==’C’)

nl
{

printf(“\n\nCorrect!!!”);count++;

O
getch();

break;

it y
else

C.23232”);

getch();
rs
printf(“\n\nWrong!!! The correct answer is
ve
break;

}
ni

case 2:

printf(“\n\n\nThe country with the highest environmental


U

performance index is...”);

printf(“\n\nA.France\t\tB.Denmark\n\nC.Switzerland\t\
tD.Finland”);
it y

if (toupper(getch())==’C’)

{printf(“\n\nCorrect!!!”);count++;

getch();
m

break;}

else
)A

{printf(“\n\nWrong!!! The correct answer is


C.Switzerland”);

getch();
(c

break;}

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
138
case 3:
Notes
printf(“\n\n\nWhich animal laughs like human being?”);

e
printf(“\n\nA.Polar Bear\t\tB.Hyena\n\nC.Donkey\t\
tD.Chimpanzee”);

in
if (toupper(getch())==’B’)

{printf(“\n\nCorrect!!!”);count++;

nl
getch();

break;}

O
else

{printf(“\n\nWrong!!! The correct answer is


B.Hyena”);

it y
getch();

break;}

case 4: rs
printf(“\n\n\nWho was awarded the youngest player
ve
award in Fifa World Cup 2006?”);

printf(“\n\nA.Wayne Rooney\t\tB.Lucas Podolski\n\


nC.Lionel Messi\t\tD.Christiano Ronaldo”);
ni

if (toupper(getch())==’B’)

{printf(“\n\nCorrect!!!”);count++;
U

getch();

break;}
it y

else

{printf(“\n\nWrong!!! The correct answer is B.Lucas


Podolski”);

getch();
m

break;}
)A

case 5:

printf(“\n\n\nWhich is the third highest mountain in the world?”);

printf(“\n\nA.Mt. K2\t\tB.Mt. Kanchanjungha\n\nC.Mt. Makalu\t\tD.Mt. Kilimanjaro”);


(c

if (toupper(getch())==’B’)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
139
{printf(“\n\nCorrect!!!”);count++;
Notes
getch();

e
break;}

in
else

{printf(“\n\nWrong!!! The correct answer is B.Mt.


Kanchanjungha”);

nl
getch();

break;}

O
case 6:

it y
printf(“\n\n\nWhat is the group of frogs known as?”);

printf(“\n\nA.A traffic\t\tB.A toddler\n\nC.A police\t\tD.An


Army”);

if (toupper(getch())==’D’ )

rs
{printf(“\n\nCorrect!!!”);count++;

getch();
ve
break;}

else
ni

{printf(“\n\nWrong!!! The correct answer is D.An


Army”);

getch();
U

break;}}

}
it y

if(count>=2)

{goto test;}
m

else

{
)A

system(“cls”);

printf(“\n\nSORRY YOU ARE NOT ELIGIBLE TO PLAY THIS GAME, BETTER


LUCK NEXT TIME”);
(c

getch();

goto mainhome;

}
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
140
test:
Notes
system(“cls”);

e
printf(“\n\n\t*** CONGRATULATION %s you are eligible to play the Game ***”,player-
name);

in
printf(“\n\n\n\n\t!Press any key to Start the Game!”);

if(toupper(getch())==’p’)

nl
{goto game;}

game:

O
countr=0;

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

it y
{system(“cls”);

r=i;

switch(r)
rs
{
ve
case 1:

printf(“\n\nWhat is the National Game of England?”);

printf(“\n\nA.Football\t\tB.Basketball\n\nC.Cricket\t\
ni

tD.Baseball”);

if (toupper(getch())==’C’)
U

{printf(“\n\nCorrect!!!”);countr++;getch();

break;getch();}
it y

else

{printf(“\n\nWrong!!! The correct answer is


C.Cricket”);getch();

goto score;
m

break;}
)A

case 2:

printf(“\n\n\nStudy of Earthquake is called............,”);

printf(“\n\nA.Seismology\t\tB.Cosmology\n\
(c

nC.Orology\t\tD.Etimology”);

if (toupper(getch())==’A’)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
141
{printf(“\n\nCorrect!!!”);countr++;getch();
Notes
break;}

e
else

in
{printf(“\n\nWrong!!! The correct answer is
A.Seismology”);getch();

goto score;

nl
break;

O
case 3:

it y
printf(“\n\n\nAmong the top 10 highest peaks in the
world, how many lie in Nepal? “);

printf(“\n\nA.6\t\tB.7\n\nC.8\t\tD.9”);

if (toupper(getch())==’C’)

{printf(“\n\nCorrect!!!”);countr++;getch();

break;}
rs
ve
else

{printf(“\n\nWrong!!! The correct answer is


ni

C.8”);getch();

goto score;

break;}
U

case 4:
it y

printf(“\n\n\nThe Laws of Electromagnetic Induction


were given by?”);

printf(“\n\nA.Faraday\t\tB.Tesla\n\nC.Maxwell\t\
tD.Coulomb”);
m

if (toupper(getch())==’A’)

{printf(“\n\nCorrect!!!”);countr++;getch();
)A

break;}

else

{
(c

printf(“\n\nWrong!!! The correct answer is A.Faraday”);getch();

goto score;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
142
break;
Notes
}

e
in
case 5:

printf(“\n\n\nIn what unit is electric power measured?”);

nl
printf(“\n\nA.Coulomb\t\tB.Watt\n\nC.Power\t\
tD.Units”);

if (toupper(getch())==’B’)

O
{ p r i n t f ( “ \ n \
nCorrect!!!”);countr++;getch(); break;}

else

it y
{

printf(“\n\nWrong!!! The correct answer is


B.Power”);

rs getch();

goto score;
ve
break;

}
ni

case 6:

printf(“\n\n\nWhich element is found in Vitamin B12?”);


U

printf(“\n\nA.Zinc\t\tB.Cobalt\n\nC.Calcium\t\tD.Iron”);

if (toupper(getch())==’B’ )
it y

{printf(“\n\nCorrect!!!”);countr++;getch();

break;}

else
m

{printf(“\n\nWrong!!! The correct answer is


B.Cobalt”);goto score;
)A

getch();

break;}
(c

case 7:

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
143
printf(“\n\n\nWhat is the National Name of Japan?”);
Notes
printf(“\n\nA.Polska\t\tB.Hellas\n\nC.Drukyul\t\

e
tD.Nippon”);

if (toupper(getch())==’D’)

in
{printf(“\n\nCorrect!!!”);countr++;getch();

break;}

nl
else

{printf(“\n\nWrong!!! The correct answer is

O
D.Nippon”);getch();

goto score;

break;}

it y
case 8:

folded at the most?”);


rs
printf(“\n\n\nHow many times a piece of paper can be

printf(“\n\nA.6\t\tB.7\n\nC.8\t\tD.Depends on the size


ve
of paper”);

if (toupper(getch())==’B’)

{printf(“\n\nCorrect!!!”);countr++;getch(); break;}
ni

else

{printf(“\n\nWrong!!! The correct answer is


U

B.7”);getch();

goto score;

break;}
it y

case 9:

printf(“\n\n\nWhat is the capital of Denmark?”);


m

printf(“\n\nA.Copenhagen\t\tB.Helsinki\n\nC.Ajax\t\
tD.Galatasaray”);
)A

if (toupper(getch())==’A’)

{printf(“\n\nCorrect!!!”);countr++;
getch();
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
144
break;}
Notes
else

e
{printf(“\n\nWrong!!! The correct answer is
A.Copenhagen”);getch();

in
goto score;

break;}

nl
case 10:

O
printf(“\n\n\nWhich is the longest River in the world?”);

printf(“\n\nA.Nile\t\tB.Koshi\n\nC.Ganga\t\tD.Amazon”);

it y
if (toupper(getch())==’A’)

{printf(“\n\nCorrect!!!”);countr++;getch(); break;}

else

A.Nile”);getch();break;goto score;} rs {printf(“\n\nWrong!!! The correct answer is


ve
case 11:

printf(“\n\n\nWhat is the color of the Black Box in


ni

aeroplanes?”);

printf(“\n\nA.White\t\tB.Black\n\nC.Orange\t\tD.Red”);

if (toupper(getch())==’C’)
U

{printf(“\n\nCorrect!!!”);countr++;getch();

break;}
it y

else

{printf(“\n\nWrong!!! The correct answer is C.Orange”);getch();

break;goto score;}
m

case 12:
)A

printf(“\n\n\nWhich city is known at ‘The City of Seven


Hills’?”);

printf(“\n\nA.Rome\t\tB.Vactican City\n\nC.Madrid\t\
tD.Berlin”);
(c

if (toupper(getch())==’A’)

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
145
{printf(“\n\nCorrect!!!”);countr++;getch();
Notes
break;}

e
else

in
{printf(“\n\nWrong!!! The correct answer is A.Rome”);getch();

break;goto score;}

nl
case 13:

O
printf(“\n\n\nName the country where there no mos-
quitoes are found?”);

printf(“\n\nA.Japan\t\tB.Italy\n\nC.Argentina\t\
tD.France”);

it y
if (toupper(getch())==’D’)

{printf(“\n\nCorrect!!!”);countr++;getch();

else
break;}

rs
{printf(“\n\nWrong!!! The correct answer is
ve
D.France”);getch();

break;goto score;}
ni

case 14:

printf(“\n\n\nWho is the author of ‘Pulpasa Cafe’?”);


U

printf(“\n\nA.Narayan Wagle\t\tB.Lal Gopal Subedi\n\


nC.B.P. Koirala\t\tD.Khagendra Sangraula”);
it y

if (toupper(getch())==’A’)

{printf(“\n\nCorrect!!!”);countr++;getch();

break;}
m

else

{printf(“\n\nWrong!!! The correct answer is


A.Narayan Wagle”);getch();
)A

break;goto score;}

case 15:
(c

printf(“\n\n\nWhich Blood Group is known as the Uni-

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
146
versal Recipient?”);
Notes
printf(“\n\nA.A\t\tB.AB\n\nC.B\t\tD.O”);

e
if (toupper(getch())==’B’)

in
{printf(“\n\nCorrect!!!”);countr++;getch();

break;}

nl
else

{printf(“\n\nWrong!!! The correct answer is


B.AB”);getch();

O
goto score;

break;}

it y
case 16:

printf(“\n\n\nWhat is the unit of measurement of dis-


tance between Stars?”);

Mile\t\tD.Kilometer”);
rs
printf(“\n\nA.Light Year\t\tB.Coulomb\n\nC.Nautical
ve
if (toupper(getch())==’A’)

{printf(“\n\nCorrect!!!”);countr++; getch();
ni

break;

else
U

{printf(“\n\nWrong!!! The correct answer is A.Light


Year”);getch();
it y

goto score;

break;}
m

case 17:

printf(“\n\n\nThe country famous for Samba Dance


is........”);
)A

printf(“\n\nA.Brazil\t\tB.Venezuela\n\nC.Nigeria\t\
tD.Bolivia”);

if (toupper(getch())==’A’)
(c

{printf(“\n\nCorrect!!!”);countr++;
getch();

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
147
break;}
Notes
else

e
{printf(“\n\nWrong!!! The correct answer is
A.Brazil”);getch();goto score;

in
break;}

nl
case 18:

printf(“\n\n\nWind speed is measure by__________?”);

O
printf(“\n\nA.Lysimeter\t\tB.Air vane\n\nC.Hydrometer\t\
tD.Anemometer\n\n”);

if (toupper(getch())==’D’)

it y
{printf(“\n\nCorrect!!!”);countr++;
getch();

break;}

else
rs
{printf(“\n\nWrong!!! The correct answer is
ve
D.Anemometer”);getch();goto score;

break;}
ni

case 19:

printf(“\n\n\nWhich city in the world is popularly known


U

as The City of Temple?”);

printf(“\n\nA.Delhi\tB.Bhaktapur\n\nC.Kathmandu\
tD.Agra\n\n”);
it y

if (toupper(getch())==’C’)

{printf(“\n\nCorrect!!!”);countr++; getch();

break;}
m

else

{printf(“\n\nWrong!!! The correct answer is


)A

C.Kathmandu”);getch();goto score;

break;}

case 20:
(c

printf(“\n\n\nWhich hardware was used in the First


Generation Computer?”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
148
printf(“\n\nA.Transistor\t\tB.Valves\n\nC.I.C\t\tD.S.S.I”);
Notes
if (toupper(getch())==’B’)

e
{printf(“\n\nCorrect!!!”);countr++;
getch();

in
break;}

else

nl
{printf(“\n\nWrong!!! The correct answer is
B.Valves”);getch();goto score;

O
break;}

case 21:

it y
printf(“\n\n\nOzone plate is being destroyed regularly
because of____ ?”);

printf(“\n\nA.L.P.G\t\tB.Nitrogen\n\nC.Methane\t\tD.
C.F.C”);

rs
if (toupper(getch())==’D’)
ve
{printf(“\n\nCorrect!!!”);countr++;
getch();

break;}
ni

else

{printf(“\n\nWrong!!! The correct answer is D.


C.F.C”);getch();goto score;
U

break;}
it y

case 22:

printf(“\n\n\nWho won the Women’s Australian Open


Tennis in 2007?”);

printf(“\n\nA.Martina Hingis\t\tB.Maria Sarapova\n\


m

nC.Kim Clijster\t\tD.Serena Williams”);

if (toupper(getch())==’D’)
)A

{printf(“\n\nCorrect!!!”);countr++;
getch();

break;}
(c

else

{printf(“\n\nWrong!!! The correct answer is D.Serena


Williams”);getch();goto score;

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
149
break;}
Notes

e
case 23:

in
printf(“\n\n\nWhich film was awarded the Best Motion
Picture at Oscar in 2010?”);

printf(“\n\nA.The Secret in their Eyes\t\tB.Shutter

nl
Island\n\nC.The King’s Speech\t\tD.The Reader”);

if (toupper(getch())==’C’)

O
{printf(“\n\nCorrect!!!”);countr++;
getch();

break;}

it y
else

{printf(“\n\nWrong!!! The correct answer is C.The


King’s Speech”);getch();goto score;

score:
break;}}}

rs
ve
system(“cls”);

score=(float)countr*100000;

if(score>0.00 && score<1000000)


ni

printf(“\n\n\t\t**************** CONGRATULATION *****************”);


U

printf(“\n\t You won $%.2f”,score);goto go;}


it y

else if(score==1000000.00)

printf(“\n\n\n \t\t**************** CONGRATULATION ****************”);


m

printf(“\n\t\t\t\t YOU ARE A MILLIONAIRE!!!!!!!!!”);

printf(“\n\t\t You won $%.2f”,score);


)A

printf(“\t\t Thank You!!”);

else
(c

printf(“\n\n\t******** SORRY YOU DIDN’T WIN ANY CASH ********”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
150
printf(“\n\t\t Thanks for your participation”);
Notes
printf(“\n\t\t TRY AGAIN”);goto go;}

e
in
go:

puts(“\n\n Press Y if you want to play next game”);

nl
puts(“ Press any key if you want to go main menu”);

if (toupper(getch())==’Y’)

O
goto home;

else

it y
edit_score(score,playername);

goto mainhome;}}}

void show_record()

{system(“cls”);
rs
ve
char name[20];

float scr;
ni

FILE *f;

f=fopen(“score.txt”,”r”);
U

fscanf(f,”%s%f”,&name,&scr);

printf(“\n\n\t\t*************************************************************”);

printf(“\n\n\t\t %s has secured the Highest Score %0.2f”,name,scr);


it y

printf(“\n\n\t\t*************************************************************”);

fclose(f);
m

getch();}
)A

void reset_score()

{system(“cls”);

float sc;

char nm[20];
(c

FILE *f;

f=fopen(“score.txt”,”r+”);

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
151
fscanf(f,”%s%f”,&nm,&sc);
Notes
sc=0;

e
fprintf(f,”%s,%.2f”,nm,sc);

in
fclose(f);}

nl
void help()

{system(“cls”);

O
printf(“\n\n HELP”);

printf(“\n -------------------------------------------------------------------------”);

printf(“\n ......................... C program Quiz Game...........”);

it y
printf(“\n >> There are two rounds in the game, WARMUP ROUND & CHALLANGE
ROUND”);

printf(“\n >> In warmup round you will be asked a total of 3 questions to test your general”);

printf(“\n

printf(“\n rs
knowledge. You will be eligible to play the game if you can give atleast 2”);

right answers otherwise you can’t play the Game...........”);


ve
printf(“\n >> Your game starts with the CHALLANGE ROUND. In this round you will be
asked”);

printf(“\n total 10 questions each right answer will be awarded $100,000.”);


ni

printf(“\n By this way you can win upto ONE MILLION cash prize in USD...............”);

printf(“\n >> You will be given 4 options and you have to press A, B ,C or D for the”);
U

printf(“\n right option”);

printf(“\n >> You will be asked questions continuously if you keep giving the right an-
swers.”);
it y

printf(“\n >> No negative marking for wrong answers”);

printf(“\n\n\t*********************BEST OF LUCK*********************************”);

printf(“\n\n\t*****C PROGRAM QUIZ GAME is developed by CODE WITH C


m

TEAM********”);}
)A

void edit_score(float score, char plnm[20])

{system(“cls”);

float sc;
(c

char nm[20];

FILE *f;

f=fopen(“score.txt”,”r”);
Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])


lOMoARcPSD|52151628

Programming In C
152
fscanf(f,”%s%f”,&nm,&sc);
Notes
if (score>=sc)

e
{ sc=score;

in
fclose(f);

f=fopen(“score.txt”,”w”);

nl
fprintf(f,”%s\n%.2f”,plnm,sc);

fclose(f);}}

O
it y
rs
ve
ni
U
it y
m
)A
(c

Amity Directorate of Distance & Online Education

Downloaded by ashikmuhammed ([email protected])

You might also like