Snsnbprogramming in C
Snsnbprogramming in C
Programming in C
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
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
They are:
1. Input Devices
2. Memory Unit
(c
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 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
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.
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.
Programming In C
4
Notes
e
in
nl
O
it y
Purpose of Storage
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
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
Types of RAM:
Two types of RAM are used in computers: Dynamic RAM and Static RAM.
m
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
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.
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.
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.
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
a. Writing data
b. Reading data
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
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
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
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.
● 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
● 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
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.
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 :
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
A Printer is another popular part of a computer system. It takes what you look at on
it y
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 Storage
pump and oxygenate the blood). As shown in the diagram, primary storage typically
consists of three kinds of storage:
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
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
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.
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
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
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
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:-
● Linking stored the program in virtual memory to save RAM, need shared library
2. Static Linker:-
it y
● In static linking there are less chances to error and No chances to failure.
)A
Loader
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
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
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
6. Clustered System
7. Realtime Operating System
8. Handheld System
Amity Directorate of Distance & Online Education
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
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
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
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
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
#include
{}
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.
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
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
int
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
int myVar;
Programming In C
19
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
+
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
++ A++ = 11
by one.
Decrement operator decreases the integer
-- A-- = 9
value by one.
it y
(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
Programming In C
20
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.
O
These operators performs logical operations.
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
!(A && B) is
ve
!
condition is true, then Logical NOT operator true.
will make it false.
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
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
1 0 0 1 1
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
C&2
#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);
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
#include <stdio.h>
U
int main()
{
it y
return 0;
(c
Output :
++a = 11
Amity Directorate of Distance & Online Education
Programming In C
23
--b = 99
Notes
++c = 11.500000
e
--d = 99.500000
in
Example 3: Assignment Operators
nl
#include <stdio.h>
int main()
O
{
int a = 5, c;
it y
c = a; // c is 5
c += a; // c is 10
c -= a; // c is 5 rs
ve
printf(“c = %d\n”, c);
c *= a; // c is 25
c /= a; // c is 5
c %= a; // c = 0
return 0;
#include <stdio.h>
)A
int main()
int a = 5, b = 5, c = 10;
(c
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);
nl
printf(“%d != %d is %d \n”, a, b, a != b);
O
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
#include <stdio.h>
int main()
)A
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);
nl
printf(“(a != b) || (c < b) is %d \n”, result);
O
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
#include <stdio.h>
int main()
(c
int a;
Programming In C
26
float b;
Notes
double c;
e
char d;
in
printf(“Size of int=%lu bytes\n”,sizeof(a));
nl
printf(“Size of double=%lu bytes\n”,sizeof(c));
O
return 0;
it y
Output :
Size of int = 4 bytes
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
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
#include <stdio.h>
)A
int main()
float num1;
(c
double num2;
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);
O
return 0;
it y
Output:
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
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
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.
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
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
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()
printf(“%d”, k);
return 0;
m
Answer : 4 15
)A
#include<stdio.h>
int main()
(c
int class;
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
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
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
Expression Statement
it y
Example:
m
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.
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.
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 )
if ( 5 < 10 )
rs
ve
printf( “Five is now less than ten, that’s a big surprise” );
else syntax
ni
if ( TRUE ) {
it y
else {
m
}
)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.
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;
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 {
U
}
it y
return 0;
}
m
Output:
)A
23
(c
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
{
}
ni
else
{
U
}
it y
Statements;
When a sequence of decision is required, nested if-else is applied. Nesting implies using
m
#include<stdio.h>
int main()
int num=1;
(c
if(num<10)
Programming In C
36
if(num==1)
Notes
{
e
printf(“The value is:%d\n”,num);
in
}
else
nl
{
O
}
else
it y
{
rs
}
return 0;
}
ve
3.2.2 switch statement
ni
statement
switch(expression)
it y
case constant_1 :
break;
)A
case constant_2 :
break;
(c
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:
// break;
case 15:
U
// break;
it y
case 20:
// break;
m
default:
#include <stdio.h>
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: “);
O
switch(operator)
case ‘+’:
it y
printf(“%.1lf + %.1lf = %.1lf”,n1, n2, n1+n2);
break;
case ‘-’:
case ‘*’:
break;
case ‘/’:
it y
break;
m
default:
)A
return 0;
}
(c
Programming In C
39
Output:
Notes
Enter an operator (+, -, *,): -
e
Enter two operands: 32.5
in
12.4
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
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 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
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
do {
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
A for loop is a further effective loop structure in ‘C’ programming. The general
structure of for loop is as follows:
statements;
)A
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.
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
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
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
what part of code we can access a variable. A storage class is utilized to describe the
following things:
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
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.
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.
Here, #include is a preprocessor directive and it renders header file like “stdio.h” avail-
ni
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.
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
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
Example:
#include <stdio.h>
Amity Directorate of Distance & Online Education
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 ) {
O
}
else {
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;
a++;
)A
continue;
}
(c
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
int main()
{
ni
int i;
while(0, i < 4)
U
printf(“Loop “);
it y
i++;
return 0;
m
}
)A
int main()
{
(c
int i = 0;
do
{
Amity Directorate of Distance & Online Education
Programming In C
48
i++;
Notes
if (i == 2)
e
continue;
in
printf(“In while loop “);
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
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
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.
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
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++)
scanf(“%d”, &arr[i]);
rs
ve
}
printf(“%d “, arr[i]);
U
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
11 22 34 4 34
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:
nl
datatype is the type of elements of an array.
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
{
{
m
max = my_arr[i];
}
)A
min = my_arr[i];
Amity Directorate of Distance & Online Education
Programming In C
53
}
Notes
}
e
printf(“Lowest value = %d\n”, min);
in
printf(“Highest value = %d”, max);
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
Example:
U
#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++){
}//end of j
(c
}//end of i
return 0;
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”);
scanf(“%d”, &mat1[i][j]);
}
U
}
it y
scanf(“%d”, &mat2[i][j]);
(c
Programming In C
55
// add mat1 and mat2
Notes
e
for(i = 0; i < ROW; i++)
in
{
nl
{
O
}
it y
printf(“\nResultant array: \n\n”);
rs
// print resultant array
printf(“%5d “, mat3[i][j]);
U
printf(“\n”);
}
it y
return 0;
m
Output:
)A
Enter a[0][0]: 12
Enter a[0][1]: 32
(c
Enter a[0][2]: 13
Enter a[1][0]: 35
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
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”);
O
scanf(“%d”,&r);
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
for(i=0;i<r;i++)
for(j=0;j<c;j++)
it y
scanf(“%d”,&b[i][j]);
m
}
)A
for(i=0;i<r;i++)
{
(c
for(j=0;j<c;j++)
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
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.
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.
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.
For the above defined function max(), the function declaration is as follows −
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
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.
Programming In C
60
Example:
Notes
#include <stdio.h>
e
in
/* function declaration */
nl
int main () {
O
/* local variable definition */
int a = 100;
it y
int b = 200;
int ret;
return 0;
U
int result;
)A
result = num1;
else
(c
result = num2;
Programming In C
61
Notes
return result;
e
}
in
Output:
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
● 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
● 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.
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.
nl
#include <stdio.h>
O
{
int tempnum ;
it y
/*Copying var1 value into temporary variable */
tempnum = var1 ;
var2 = tempnum ;
U
}
it y
int main( )
swapnum(num1, num2);
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)
it y
* var, however the var is a pointer that holds the address
rs
* on the address where value of num is stored.
*/
*var = *var+1;
ve
}
int main()
ni
int num=20;
U
*/
increment(&num);
m
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.
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
}
it y
}
int main() {
int i = 3;
}
ni
Output :
U
Factorial of 3 is : 6
it y
void recurse()
m
... .. ...
)A
recurse();
... .. ...
}
(c
int main()
Programming In C
65
{
Notes
... .. ...
e
recurse();
in
... .. ...
nl
O
it y
Activities :
Fig 4.2 : Working of recursion
void foo(int*);
int main()
U
foo(p++);
it y
printf(“%d\n”, *p);
)A
Answer : 10
(c
Programming In C
66
2. What will be the output of the C program?
Notes
#include <stdio.h>
e
int main()
in
{
nl
foo(&i);
printf(“%d “, *p);
O
}
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
a[0][1][2] = 5;
it y
printf(“%d”,*(*(*(a+0)+1)+2));
return 0;
m
#include<stdio.h>
int main()
{
(c
char *ptr;
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
#include <stdio.h>
enum m foo();
int main()
)A
enum m i = foo();
printf(“%d\n”, i);
(c
int foo()
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
void foo();
int main()
m
void foo(int);
)A
foo(1);
return 0;
}
(c
void foo(int i)
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
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
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
/* To print the address of a variable we use %p format specifier and ampersand (&)
sign just before the variable name like &num.
)A
*/
return 0;
(c
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
rs
5.1.1.2 How to declare a pointer?
int *p1 /*Pointer to an integer variable*/
#include <stdio.h>
int main()
{
it y
//Pointer of integer type, this can hold the address of a integer type variable.
int *p;
m
/* 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;
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
}
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;
}
ni
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
#include <stdio.h>
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) {
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
variable.
Example:
(c
#include <stdio.h>
Programming In C
75
void swap(int *a, int *b);
Notes
e
int main()
in
{
nl
printf(“m = %d\n”, m);
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);
rs
return 0;
}
ve
// pointer ‘a’ and ‘b’ holds and points to the address of ‘m’ and ‘n’
ni
{
U
int temp;
temp = *a;
*a = *b;
it y
*b = temp;
}
m
Output:
)A
After Swapping : 20 10
have scope only inside the function. Therefore if you return a pointer linked to a local
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
return x;
U
else
return y;
it y
Output:
m
92 is larger
type (*pointer-name)(parameter);
(c
Here is an example :
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);
nl
s = sum;
O
Example of Pointer to Function
it y
#include <stdio.h>
return x+y; rs
ve
}
int main( )
ni
fp = sum;
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:
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
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
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>.
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”;
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.
scanf(“%s”, name);
U
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
scanf(“%s”, age);
)A
Note: strcat() will not accomplish any boundary checking, and thus there is a threat of
(c
strlen
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.
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
Example:
(c
struct Point
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
struct Point
};
Example:
#include<stdio.h>
(c
struct Point
Programming In C
83
{
Notes
int x, y;
e
};
in
int main()
nl
{
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
arr[0].x = 10;
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.
it y
We use the union keyword to define unions. Here’s an example:
union car
char name[50];
int price; rs
ve
};
union car
it y
char name[50];
int price;
m
};
)A
int main()
return 0;
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;
return 0;
}
it y
Output:
Salary =12.3
m
Example:
#include <stdio.h>
(c
struct student {
char name[50];
int age;
Amity Directorate of Distance & Online Education
Programming In C
86
};
Notes
e
// function prototype
in
void display(struct student s);
nl
int main() {
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);
return 0;
}
it y
printf(“\nDisplaying information\n”);
m
Output :
Enter Age : 15
(c
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
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
}s1;
int main()
rs
ve
{
ni
s1.ptr = &roll;
U
s1.name = “Pritesh”;
it y
return(0);
m
Output :
)A
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.
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
rs
Instead of storing data in plain text, they store it in the binary form (0’s and 1’s).
3. Closing a file
4. Reading from and writing information to a file
U
● 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
● 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
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
fptr = fopen(“C:\\program.txt”,”w”);
U
if(fptr == NULL)
{
it y
printf(“Error!”);
exit(1);
m
}
)A
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
(c
fclose(fptr);
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;
exit(1);
U
fscanf(fptr,”%d”, &num);
it y
fclose(fptr);
)A
return 0;
Activity :
(c
#include<stdio.h>
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
#include<stdio.h>
)A
void function(char**);
int main()
{
(c
function(arr);
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
printf(“%s”,p);
U
#include<stdio.h>
m
{
)A
str1 = str2;
str2 = temp;
(c
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
Name: jack
m
Roll no: 33
Marks: 15.21
)A
Details of student 3
Name: King
(c
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
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;
Programming In C
96
char acc_type[10];
Notes
float amt;
e
struct date dob;
in
struct date deposit;
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”);
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
scanf(“%d/%d/%d”,&add.dob.month,&add.dob.day,&add.dob.year);
scanf(“%d”,&add.age);
scanf(“%s”,add.address);
scanf(“%s”,add.citizenship);
m
scanf(“%lf”,&add.phone);
)A
scanf(“%f”,&add.amt);
scanf(“%s”,add.acc_type);
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);
nl
add_invalid:
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
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:
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
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;
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);
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)
scanf(“%lf”,&upd.phone);
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!”);
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”);
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
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
{
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
fordelay(1000000000);
system(“cls”);
(c
menu();
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;
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
{
scanf(“%f”,&transaction.amt);
ni
add.amt-=transaction.amt;
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
}
(c
fclose(old);
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
scanf(“%d”,&main_exit);
system(“cls”);
if (main_exit==1)
menu();
(c
else
close();
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”);
it y
scanf(“%d”,&rem.acc_no);
{
rs
ve
if(add.acc_no!=rem.acc_no)
citizenship,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.
deposit.year);
U
else
{test++;
it y
}
m
fclose(old);
fclose(newrec);
)A
remove(“record.dat”);
rename(“new.dat”,”record.dat”);
if(test==0)
(c
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;
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
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
else if(strcmpi(add.acc_type,”fixed2”)==0)
time=2.0;
(c
rate=11;
intrst=interest(time,add.amt,rate);
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);
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
else if(strcmpi(add.acc_type,”current”)==0)
it y
}
)A
}
(c
Programming In C
109
}
Notes
else if (choice==2)
e
{ printf(“Enter the name:”);
in
scanf(“%s”,&check.name);
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;
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
}
it y
else if(strcmpi(add.acc_type,”fixed2”)==0)
time=2.0;
m
rate=11;
)A
intrst=interest(time,add.amt,rate);
else if(strcmpi(add.acc_type,”fixed3”)==0)
Programming In C
110
{
Notes
time=3.0;
e
rate=13;
in
intrst=interest(time,add.amt,rate);
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
}
m
}
)A
fclose(ptr);
(c
if(test!=1)
{ system(“cls”);
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
scanf(“%d”,&main_exit);}
U
if (main_exit==1)
system(“cls”);
it y
menu();
}
m
else
{
)A
system(“cls”);
close();
}
(c
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”);
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();
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);
Programming In C
114
printf(“.”);
Notes
}
e
system(“cls”);
in
menu();
nl
else
{ printf(“\n\nWrong password!!\a\a\a”);
O
login_try:
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
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.
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
{
)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.
Programming In C
116
Notes
while (option)
e
{
in
printf (“------------------------------------------\n”);
nl
printf (“ 2 --> POP \n”);
O
printf (“ 4 --> EXIT \n”);
printf (“------------------------------------------\n”);
it y
printf (“Enter your choice\n”);
rs
1
3
ve
4
5
ni
7
U
10
it y
11
while (option)
m
{
)A
printf (“------------------------------------------\n”);
Programming In C
117
printf (“ 4 --> EXIT \n”);
Notes
printf (“------------------------------------------\n”);
e
in
printf (“Enter your choice\n”);
nl
Option1 will initiate the push function
O
Option2 will initiate the pop function
it y
int num;
}
ni
else
{
U
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
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
int num;
it y
if (s.top == - 1)
return (s.top);
}
)A
else
num = s.stk[s.top];
(c
s.top = s.top - 1;
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
}
ni
printf (“\n”);
U
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
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 */
O
/**
function : gotoxy
it y
@param input: x and y coordinates
rs
*/
{
ve
coord.X = x;
coord.Y = y;
ni
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
U
int main()
struct emp
{
(c
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
it y
* if the file EMP.DAT already exists then it open that file in read write mode
rs
*/
fp = fopen(“EMP.DAT”,”rb+”);
if(fp == NULL)
ve
{
fp = fopen(“EMP.DAT”,”wb+”);
ni
if(fp == NULL)
{
U
exit(1);
}
it y
}
m
recsize = sizeof(e);
)A
while(1)
{
(c
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);
nl
gotoxy(30,14);
O
gotoxy(30,16);
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
{
ni
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’;
scanf(“%s”,e.name);
scanf(“%d”, &e.age);
scanf(“%f”, &e.bs);
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”);
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
system(“cls”);
U
another = ‘y’;
while(another == ‘y’)
it y
scanf(“%s”, empname);
m
rewind(fp);
{
(c
scanf(“%s%d%f”,e.name,&e.age,&e.bs);
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
{
scanf(“%s”,empname);
ni
{
it y
}
)A
fclose(fp);
fclose(ft);
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
it y
}
return 0;
rs
}
ve
Customer Billing System C Project
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
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
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.
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;
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;
it y
}customer;
int tl,sl,ts;
rs
void main()
int i,n;
ve
char ch;
clrscr();
ni
_setcursortype(_NOCURSOR);
U
printf(“===============================\n”);
printf(“3: exit\n”);
m
printf(“\n================================\n”);
do{
)A
ch=getche();
}while(ch<=’0’ || ch>’3’);
switch(ch){
(c
case ‘1’:
clrscr();
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
name\n”);
search();
it y
ch=getche();
main();
case ‘3’:
m
clrscr();
delay(700);
)A
textcolor(RED);
gotoxy(25,25);
delay(1500);
exit(1);
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
scanf(“%f”,&customer.mobile_no);
printf(“ Street:”);
it y
scanf(“%s”,customer.street);
printf(“ City:”);
m
scanf(“%s”,customer.city);
scanf(“%f”,&customer.oldbalance);
scanf(“%f”,&customer.payment);
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
ch=getche();
switch(ch){
case ‘1’:
)A
fseek(fp,0,SEEK_END);
tl=ftell(fp);
sl=sizeof(customer);
(c
ts=tl/sl;
do{
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
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
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
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
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
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
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(“\n\t\t\t to “);
U
printf(“\n\t\t________________________________________”);
printf(“\n\t\t________________________________________”);
it y
printf(“\n\t\t________________________________________”);
m
printf(“\n\t\t________________________________________”);
printf(“\n\t\t________________________________________\n\n”);
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”);
gets(playername);
system(“cls”);
m
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.”);
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”);
nl
printf(“\n >> You will be asked questions continuously, till right answers are given”);
O
printf(“\n\n\t!!!!!!!!!!!!! ALL THE BEST !!!!!!!!!!!!!”);
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)
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\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
getch();
(c
break;}
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
it y
getch();
break;}
case 4: rs
printf(“\n\n\nWho was awarded the youngest player
ve
award in Fifa World Cup 2006?”);
if (toupper(getch())==’B’)
{printf(“\n\nCorrect!!!”);count++;
U
getch();
break;}
it y
else
getch();
m
break;}
)A
case 5:
if (toupper(getch())==’B’)
Programming In C
139
{printf(“\n\nCorrect!!!”);count++;
Notes
getch();
e
break;}
in
else
nl
getch();
break;}
O
case 6:
it y
printf(“\n\n\nWhat is the group of frogs known as?”);
if (toupper(getch())==’D’ )
rs
{printf(“\n\nCorrect!!!”);count++;
getch();
ve
break;}
else
ni
getch();
U
break;}}
}
it y
if(count>=2)
{goto test;}
m
else
{
)A
system(“cls”);
getch();
goto mainhome;
}
Amity Directorate of Distance & Online Education
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\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
goto score;
m
break;}
)A
case 2:
printf(“\n\nA.Seismology\t\tB.Cosmology\n\
(c
nC.Orology\t\tD.Etimology”);
if (toupper(getch())==’A’)
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
C.8”);getch();
goto score;
break;}
U
case 4:
it y
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
goto score;
Programming In C
142
break;
Notes
}
e
in
case 5:
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
{
rs getch();
goto score;
ve
break;
}
ni
case 6:
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
getch();
break;}
(c
case 7:
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
O
D.Nippon”);getch();
goto score;
break;}
it y
case 8:
if (toupper(getch())==’B’)
{printf(“\n\nCorrect!!!”);countr++;getch(); break;}
ni
else
B.7”);getch();
goto score;
break;}
it y
case 9:
printf(“\n\nA.Copenhagen\t\tB.Helsinki\n\nC.Ajax\t\
tD.Galatasaray”);
)A
if (toupper(getch())==’A’)
{printf(“\n\nCorrect!!!”);countr++;
getch();
(c
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
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
break;goto score;}
m
case 12:
)A
printf(“\n\nA.Rome\t\tB.Vactican City\n\nC.Madrid\t\
tD.Berlin”);
(c
if (toupper(getch())==’A’)
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:
if (toupper(getch())==’A’)
{printf(“\n\nCorrect!!!”);countr++;getch();
break;}
m
else
break;goto score;}
case 15:
(c
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
O
goto score;
break;}
it y
case 16:
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
goto score;
break;}
m
case 17:
printf(“\n\nA.Brazil\t\tB.Venezuela\n\nC.Nigeria\t\
tD.Bolivia”);
if (toupper(getch())==’A’)
(c
{printf(“\n\nCorrect!!!”);countr++;
getch();
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:
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\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
C.Kathmandu”);getch();goto score;
break;}
case 20:
(c
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
break;}
it y
case 22:
if (toupper(getch())==’D’)
)A
{printf(“\n\nCorrect!!!”);countr++;
getch();
break;}
(c
else
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?”);
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
score:
break;}}}
rs
ve
system(“cls”);
score=(float)countr*100000;
else if(score==1000000.00)
else
(c
Programming In C
150
printf(“\n\t\t Thanks for your participation”);
Notes
printf(“\n\t\t TRY AGAIN”);goto go;}
e
in
go:
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*************************************************************”);
fclose(f);
m
getch();}
)A
void reset_score()
{system(“cls”);
float sc;
char nm[20];
(c
FILE *f;
f=fopen(“score.txt”,”r+”);
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 -------------------------------------------------------------------------”);
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”);
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 >> You will be asked questions continuously if you keep giving the right an-
swers.”);
it y
printf(“\n\n\t*********************BEST OF LUCK*********************************”);
TEAM********”);}
)A
{system(“cls”);
float sc;
(c
char nm[20];
FILE *f;
f=fopen(“score.txt”,”r”);
Amity Directorate of Distance & Online Education
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