C Programming - Full Book
C Programming - Full Book
Block 1
Course Content:
Structure:
1. Unit 1
1.1 Basic Computer Organization
1.2 Computer Hardware Components
1.3 Primary Memory – RAM, ROM
1.4 Secondary Memory
1.5 Types of Software
1
1.5.1 System Software
1.5.2 Application Software
1.6 Introduction to Compilers, Interpreters, Assembler, Linker, Loader
1.7 Introduction to C compiler and its different versions
1.8 Basic Operating System Concepts
1.9 Functions of Operating system
1.9.1 Types of Operating System
1.10 The advantage of using Operating System
Unit 1
Unit Outcomes :
At the end of this unit, you will be able to:
1. Define basic structure of computers
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 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, 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
2
control signals required to drive all other hardware in the CPU to execute the series of
microoperations that encompass the instruction
They are:
1. Input Devices
2. Memory Unit
4. Control Unit.
5. Output Devices
Input Devices :
Computers take information through input unit. Keyboard, mouse, Joystick, Light 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.
3
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.
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'. 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 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 light-sensitive element which, when
placed against the screen, detects the light from the screen facilitating the computer to identify the
location of the pen on the screen.
A photo or text to be input into a computer through a device called Scanners which is an input
device. Two types of Scanners are there; one is flatbed scanner and another is hand-held scanner.
A Bar Code reader is another input device. A Bar Code is a pattern printed in lines of contrasting
thickness. You might have seen bar codes on goods in libraries, in supermarkets, on magazines etc.
Bar codes provide a quick method of recording the sale of items.
Memory Unit :
The accountability of memory unit is to stores data as well as programs. Two categories of memory
units are there , Primary Memory and Secondary Memory. The capability to store instructions that
form a computer program, and the information that the instructions manipulate is what makes
stored program architecture computers versatile.
4
Computer memory can be believed to be arranged in a hierarchical way where memory with the
fastest access speeds and highest costs lies at the top although those 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.
Purpose of Storage
The essential components of a general-purpose computer are arithmetic and logic unit, control
circuitry, storage space, and input/output devices. If storage were 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 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 types of memory like RAM and ROM.
5
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 sluggishly accessed hard disk.
Types of RAM:
Two types of RAM are used in computers: Dynamic RAM and Static RAM.
Dynamic RAM (DRAM): The information stored in Dynamic RAM has to be refreshed after every few
milliseconds otherwise it will get erased. DRAM has higher storage capacity and is cheaper than
Static RAM.
Static RAM (SRAM): The information stored in Static RAM need not be refreshed, but it
remains stable as long as power supply is provided. SRAM is costlier but has higher speed than
DRAM.
Additional kinds of integrated and quickly accessible memory are Read Only Memory (ROM),
Programmable ROM (PROM), and Erasable Programmable ROM (EPROM). These are used to
maintain special programs and data, such as the BIOS, 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 only).
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 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 only by the manufacturer.
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.
6
EPROM (Erasable Programmable Read Only Memory):
As the name suggests the Erasable Programmable Read Only Memory, information can be removed,
and the chip programmed a new to record different information using 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.
STORAGE DEVICES
The objective of storage in a computer is to keep data or information and get that 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.
• It is non - volatile
• Can be easily removed and moved & attached to some other device
a) Writing data
b) Reading data
Floppy Disks
7
The floppy disk drive (FDD) was developed at IBM by Alan Shugart in 1967. The 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 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.
Hard Disks
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.
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 at 3600 or more rpm (Revolutions Per Minute) - that means
that in one minute, the hard drive spins around over 7200 times!
Optical Storage
• Photo CD
Optical Storage Devices Data is deposited on a reflective surface so it can be read by a beam of
laser light. Two Kinds of Optical Storage Devices
Compact Disks
8
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) establishes a code that represents data.
CDs usually store about 650MB. This is quite a bit more than the 1.44MB that a floppy disk stores. A
DVD or Digital Video Disk holds even additional information than a CD, because the DVD can store
information on two levels, in smaller pits or sometimes on both sides.
CD
DVD
Pen Drives / Flash Drives
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 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
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 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
capacity and transferring the data.
The CD‘s were further developed where the data could be deleted and re written. These types of
9
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.
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, 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 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.
· They are faster, portable and have a capability of storing large data.
· It consists of a small printed circuit board with a LED encased in a robust plastic
A Computer has five operational autonomous units like Input Unit, Memory Unit, Arithmetic & Logic
Unit, Output Unit, Control Unit.
10
ALU (Arithmetic & Logical Unit) performs Arithmetic and Logic operations. ALU and this operation
are initiated once the operands are brought into the processor.
Output Unit : It displays the processed result to outside world.
Control Unit:
Control Unit is the portion of the computer’s central processing unit (CPU), which 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 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. The
functions that a control unit performs are dependent on the type of CPU because the architecture of
CPU varies from manufacturer to manufacturer.
OUTPUT DEVICES :
An output device is computer hardware that receives data from a computer and translates that data
into either text, audio, video or hard copy such as a printed document.
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.
Example of Output devices are Monitor, Printer, Projector, Headphones, Speakers etc.
A Printer is another popular part of a computer system. It takes what you look at on the computer
screen and prints it on paper.
Speakers are output devices that permit you to hear sound from computer. Computer speakers are
like stereo speakers. There are mostly two of them and they come in various sizes.
Primary Storage
Primary storage is precisely connected to the central processing unit of the computer. It ought to be
present for the CPU to function correctly, just as in a biological analogy the lungs must be present
11
(for oxygen storage) for the heart to function (to pump and oxygenate the blood). As shown in the
diagram, primary storage typically consists of three kinds of storage:
Processors Register
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 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 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".
Cache memory
Cache memory is a unique type of internal memory used by several central processing units to
enhance their performance or "throughput". Some of the information 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.
12
Generally, there are two main classifications of software, which are namely, System Software along
with the Application Software.
System Software In case of a system software, it helps the user as well as 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 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.
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, making notes, designing graphics,
maintaining accounts, carrying out calculations or even playing computer games. They essentially lie
above the system software. They 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.
Computers are a reasonable mix of software and hardware. Hardware is simply 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 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.
Compiler
A Compiler is a program that converts a number of statement of program into binary language, but it
is more intelligent than interpreter because it goes through the entire code at once and can tell the
13
possible errors and limits and ranges. But this makes it’s operating time a little slower. it is platform-
dependent. its help to detect error and get displayed after reading the entire code by compiler.
Cross-compiler
A compiler that runs on platform (A) and is capable of generating executable code for platform (B) is
called a cross-compiler.
Source-to-source Compiler
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.
Interpreter
An interpreter, like a compiler, translates high-level language into low-level machine language. The
distinction lies in the way they read the source code or input. A compiler reads the whole source
code at once, creates tokens, checks semantics, 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 intermediate code, executes it, then takes the next statement in
sequence. If an error occurs, an interpreter stops execution and reports it. though a compiler reads
the whole program even if it encounters several errors.
Syntax-directed interpreter
Threaded interpreter
Bytecode interpreter
14
Assembler
An assembler translates assembly language programs into machine code. The output of an
assembler is called an object file, which contains a combination of machine 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 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.
1. Dynamic Linker:-
2. Static Linker:-
Loader
Loader is a element of operating system and is accountable for loading executable files into
memory and execute them. It computes the size of a program (instructions and data) and creates
memory space for it. It initializes various registers to initiate execution.
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 use command-line options to specify
otherwise. The C compiler optimizer removes redundancies, optimally allocates registers, schedules
15
instructions, and reorganizes code. Select from multiple levels of optimization to obtain the best
balance between application speed and use of memory.
An Operating system is essentially an intermediary agent in the middle of the user and the computer
hardware. It Manages the computer’s resources. Simplifies hardware control for applications.
All operating systems use one fundamental abstraction: the process. A process 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 systems allow processes with multiple execution flows — that is,
multiple sequences of instructions executed in the same address space.
The operating system utilizes password protection to protect user data and similar other techniques.
it also precludes unauthorized access to programs and user data. Monitors overall system health to
help improve performance. records the response 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.
16
1.9.1 Types of Operating System:
17
Activity :
18
Block 2
Course Content:
History of C
Introduction of C
Basic structure of C program
Concept of variables, constants and data types in C
Operators and expressions: Introduction, arithmetic, relational, Logical, Assignment, Increment
and decrement operator, Conditional, bitwise operators, Expressions
Operator precedence and associativity
Managing Input and output Operation, formatting I/O.
Structure:
2. Unit 2
2.1 History of C
2.2 Introduction of C
2.3 Basic structure of C Program
2.4 Concept of Variables
2.5 Constants and data types
19
2.6 Operators and expressions
2.6.1 Arithmetic Operators
2.6.2 Relational Operators
2.6.3 Logical Operators
2.6.4 Bitwise Operators
2.6.5 Assignment Operators
2.7 Managing Input and output Operation
Unit 2:
Unit Outcomes :
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 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.”
Formerly, Ken Thompson, a Bell Labs employee, preferred to make a programming language for the new
Unix platform. Thompson adapted the BCPL system language and invented B.
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.
2.2 Introduction of C
20
C is a general-purpose programming language that is exceptionally popular, simple and flexible. It is
machine-independent, structured programming language which is used significantly in numerous
applications.
C was the fundamental language to write the whole lot from operating systems (Windows and many
others) to complex programs resembling the Oracle database, Git, Python interpreter and more.
It is believed that 'C' is a divinity's programming language. One can say, C is a center for the
programming. If you understand 'C,' you can easily grasp the expertise of the other programming
languages that uses the concept of 'C'
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 C function declarations and
macro definitions to be shared between several source files.
21
o stddef.h – Describes several useful types and macros.
o stdint.h – Identifies precise width integer types.
o stdio.h – Specifies core input and output functions
o stdlib.h – Defines numeric conversion functions, pseudo-random network generator,
memory allocation
o string.h – Defines string handling functions
o math.h – Defines common mathematical functions
#include
Main Method Declaration: The next part of a C program is to declare the main() function. The syntax to
declare the main function is:
int main()
{}
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 used deprived of being
declared. Also in a C program, the variables are to be declared prior to any operation in the function.
Example:
int main()
{
int a;
.
.
Body:
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.
22
Example:
int main()
{
int a;
printf("%d", a);
.
.
Return Statement:
The preceding part in any C program is the return statement. The return statement 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()
{
int a;
printf("%d", a);
return 0;
}
A variable is a name given to a storage area that our programs can manipulate. Each variable in C has a
specific type, which regulates the size and layout of the variable's memory; the range of values that can
be stored inside that memory; and the set of operations that can be applied to the variable.
The name of a variable can be comprised of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase 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
23
int
float
double
void
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 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, 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;
char c, ch;
float f, salary;
double d;
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 −
24
In order to define a variable whose value cannot be altered; you can utilize the const keyword. This will
create a constant. For example,
In C programming, data types are declarations for variables. This affects the type and size of data
associated with variables. For example,
int myVar;
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 −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
25
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
Modulus Operator and remainder of after an integer
% B%A=0
division.
These operators checks the relations between two operands. If result is true then returns 1 otherwise
returns 0.
26
the value of right operand. If yes, then the condition
becomes true.
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.
2. In C, the bitwise OR ( | ) takes two numbers as operands and does OR operation on every bit of
two numbers. If any of the two bits is 1 then the result comes as 1 in this operation.
3. The bitwise XOR (^) in C takes two numbers as operands and perform XOR operation 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 operand, the
second operand decides the number of places to shift.
6. The bitwise NOT (~) in C takes one number and inverts all bits of it
27
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
#include <stdio.h>
int main()
28
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
return 0;
}
#include <stdio.h>
int main()
{
int a = 5, c;
29
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
return 0;
}
30
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}
31
Input means to provide the program with some data to be utilized in the program and Output means to
display data on screen or write the data to a printer or a file.
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 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.
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 from user
correspondingly.
#include<stdio.h>
void main()
{
// defining a variable
int i;
scanf("%d", &i);
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.
32
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.
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.
The gets() function recites a line from stdin(standard input) into the buffer pointed to 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.
formatting I/O
C language extend console input/output functions. As the name reveals, the console input/output
functions permit us to -
Read the input from the keyboard by the user accessing the console.
Exhibit the output to the user at the console.
33
Note : These input and output values could be of any primitive data type.
Functions Description
This function is utilized to read one or multiple inputs from the user
scanf()
at the console.
34
Activity :
printf("%d",++a);
printf("%d",a++);
printf("%d",--a);
printf("%d",a--);
#include<stdio.h>
int main()
{
int x[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
printf("%d",sizeof(x));
return 0;
}
#include<stdio.h>
int main()
{
35
int x = 2;
(x & 1) ? printf("true") : printf("false");
return 0;
#include<stdio.h>
int main(){
int default = 5, a = 3;
if(a > 2)
printf("%d",default);
return 0;
}
#include<stdio.h>
int main()
{
int class;
int public = 5;
int private = 10;
int protected = 15;
class = public + private + protected;
printf("%d",class);
return 0;
}
36
7. Write a program in C to show the behavior of relational operators.
8. Write a program in C to show the behavior of logical operators.
9. Write a program in C to show the behavior of assignment operators.
37
Block 3
Course Content:
C Statements
conditional executing using if, else, nesting of if, switch and break
Concepts of loops, example of loops in C using for, while and do-while, continue and break
Storage types (automatic, register etc.)
predefined processor
Command Line Argument
Structure:
3. Unit 3
3.1 C Statements
38
3.3 Concepts of loops
3.4.3 Register
Unit 3:
Unit Outcomes :
39
3.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.
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
Compound Statement
When multiple statements is grouped into a single statements, it is known as compound statement. For
example, body of function can be consider as compund statement.
Expression Statement
Expression statement consists of an expression followed by ; (semi colon), if no expression is there then
it is known as null statement. Generally, statement may have a value when expression is present.
Example:
Selection Statement
Under this division, if, if..else and switch statement fall. Which we are going to learn in the next part.
40
Iteration Statement
Generally iteration statements consists of for loop, while loop and do..while loop.
Jump Statement
C language has jump statements by which user can jump from one part of the program to another part
and to avail this facility C uses goto, break, continue and return expression.
Conditional statements instructs a computer to execute a certain block of code till a certain condition
has been met.
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.
if ( statement is TRUE )
Execute this line of code
Here is a simple example that shows the syntax:
if ( 5 < 10 )
printf( "Five is now less than ten, that's a big surprise" );
else syntax
Every So Often when the condition in an if statement calculates to false, it would be wonderful to
execute some code instead of the code executed when the statement appraises to true. The "else"
statement efficiently declares that whatever code after it (whether a single line or code between
brackets) is executed if the if statement is False.
if ( TRUE ) {
/* Execute these statements if TRUE */
41
}
else {
/* Execute these statements if FALSE */
}
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 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.
Let's look at a simple program for you to try out on your own.
#include <stdio.h>
42
Fig 3.1: Flow chart of conditional statement
if (test-expression)
{
//will be executed for True block of statements
}
else
{
//will be executed for False block of statements
}
Statements;
When a sequence of decision is required, nested if-else is applied. Nesting implies using one if-else
construct within another one.
#include<stdio.h>
int main()
{
43
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}
A switch statement permits a variable to be tested against numerous values for equality. Each of these
values is called a case. As Soon As a matching case is found, its block of code is executed. It is an
complementary to the more common if-else statement
switch(expression)
case constant_1 :
break;
case constant_2 :
break;
44
default : // the default case is optional
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 an integer or
a character.
You can have any quantity of cases however there should not be any reproductions. 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 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:
Example:
int main() {
switch (var)
case 5:
printf("Case 1 executed.");
// break;
case 10:
// break;
case 15:
// break;
case 20:
45
// break;
default:
A Loop implements the sequence of statements several times until the stated 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.
Hinge On the position of a control statement in a program, a loop is categorized into two types:
In an entry-controlled loop, a condition is examined before executing the body of a loop. It is also
termed as a pre-checking loop.
In an exit-controlled loop, a condition is verified after executing the body of a loop. It is also labeled as a
post-checking loop.
46
Fig 3.2: Flow chart of while loop execution
Let us look some examples of loops in order to make our concept more clear.
A while loop is the highly straightforward looping structure. The essential format of while loop is as
follows:
while (condition) {
statements;
}
It is an entry-controlled loop. In while loop, a condition is calculated before 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.
47
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}
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.
do {
statements
} while (expression);
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.
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.
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
48
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}
A for loop is a further effective loop structure in 'C' programming. The general structure of for loop is as
follows:
Example:
#include<stdio.h>
int main()
int number;
return 0;
49
3.3.1.3 continue and break statements in C language
In any loop break is utilized to jump out of loop hopping the code below it without caring about the test
condition.
It disrupts the flow of the program by breaking the loop and resumes the execution of code which is
outside the loop.
Syntax:
while (test_condition)
{
statement1;
if (condition )
break;
statement2;
}
Like a break statement, continue statement is also utilized with if condition inside the loop to alter the
flow of control.
50
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.
while (test_condition)
{
statement1;
if (condition )
continue;
statement2;
}
A storage class exemplifies the visibility and a location of a variable. It tells from what part of code we
can access a variable. A storage class is utilized to describe the following things:
51
3.4.1 Automatic
The scope of the automatic variables is limited to the block in which they are defined.
3.4.2 Static
The variables defined as static specifier can hold their value between the multiple function calls.
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.
Default initial value of the static integral variable is 0 otherwise null.
The visibility of the static global variable is limited to the file in which it has declared.
The keyword used to define static variable is static.
3.4.3 Register
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.
The access time of the register variables is faster than the automatic variables.
The initial default value of the register local variables is 0.
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.
Static variables can not be stored into the register since we can not use more than one storage
specifier for the same variable.
52
3.4.4 External
The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program.
The variables declared as extern are not allocated any memory. It is only 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.
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.
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.
3.5 Pre-processor in C
Pre-processor processes program prior to going to the compiler. You may not get it right now but will
soon comprehend what it means.
Pre-processor directives commence with a hash symbol (#). Preprocessor directives are preprocessor
commands.
#include
Here, #include is a preprocessor directive and it renders header file like "stdio.h" available for us.
Here, #define is a pre-processor directive. It is employed to define something, like here 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.
53
It is dissimilar from normal variables because normal variables are processed in the course 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 elsewhere instead of hard coding those values
within the code.
The command line arguments are processed using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to every single argument passed
to the program. Following is a simple example which verifies if there is any argument delivered from the
command line and take action appropriately.
Example:
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
54
Activities :
#include<stdio.h>
int x = -1;
int main(){
while(x++ == 1)
printf("loop");
return 0;
}
#include<stdio.h>
55
int main()
{
int i = 0;
while(i < 4, 5)
{
printf("Loop ");
i++;
}
return 0;
}
#include<stdio.h>
int main()
{
int i;
while(0, i < 4)
{
printf("Loop ");
i++;
}
return 0;
}
#include<stdio.h>
int main()
{
switch(2/3)
{
case 1:
printf("case 1 executed ");
case 2:
printf("case 2 execcuted ");
break;
default:
printf("Default block executed");
}
return 0;
56
}
57
Block 4
Course Content:
Concept of functions
Function prototype
Recursion
3. Understanding of functions
Structure
4. Unit 4
58
4.2 2-D arrays Use in matrix computations.
4.3.5 Recursion
Unit 4
Unit Outcomes :
An array is a assemblage of one or more values of the identical type. Each value is 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.
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 at roll_no[100] because the index starts at 0.
59
Arrays can be single or multidimensional. The number of subscript or index defines the dimensions of
the array. An array of one dimension is recognized as a one-dimensional array or 1-D
Theoretically you can think of a one-dimensional array as a row, where elements are stored one after
another.
size: Number of elements an array can hold. here is some example of array declarations:
int num[100];
1
float temp[20];
2
char ch[50];
3
The elements of an array can be retrieved by specifying array name followed by subscript or index inside
square brackets (i.e []). Array subscript or index begins at 0. 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 legitimate subscript is known as the upper bound.
int my_arr[5];
The following program utilizes for loop to take input and print elements of a 1-D array.
Example:
#include<stdio.h>
int main()
int arr[5], i;
60
for(i = 0; i < 5; i++)
scanf("%d", &arr[i]);
return 0;
When an array is proclaimed inside a function, the elements of the array have 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 declaration using the following syntax:
Syntax:
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 (}).
61
Example:
The following program finds the highest and lowest elements in an array.
#include<stdio.h>
#define SIZE 10
int main()
{
int my_arr[SIZE] = {34,56,78,15,43,71,89,34,70,91};
int i, max, min;
max = min = my_arr[0];
for(i = 0; i < SIZE; i++)
{
// if value of current element is greater than previous value
// then assign new value to max
if(my_arr[i] > max)
{
max = my_arr[i];
}
62
4.2 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 structure. It offers ease of holding the bulk of data at
once which can be passed to any number of functions wherever needed.
1. data_type array_name[rows][columns];
2. int twodimen[4][3];
Example:
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
}//end of j
}//end of i
return 0;
63
4.2.1 2D array example:
#include <stdio.h>
void main ()
int arr[3][3],i,j;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
scanf("%d",&arr[i][j]);
for(i=0;i<3;i++)
printf("\n");
for (j=0;j<3;j++)
printf("%d\t",arr[i][j]);
64
}
Matrix multiplication in C
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.
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 given below:
65
Fig 4.1 : Matrix multiplication
Example:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
scanf("%d",&r);
scanf("%d",&c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
for(i=0;i<r;i++)
66
for(j=0;j<c;j++)
scanf("%d",&b[i][j]);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
mul[i][j]=0;
for(k=0;k<c;k++)
mul[i][j]+=a[i][k]*b[k][j];
for(i=0;i<r;i++)
for(j=0;j<c;j++)
67
{
printf("%d\t",mul[i][j]);
printf("\n");
return 0;
4.3 Function
A function is a cluster of statements that together accomplish a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
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, and parameters. A
function definition delivers the actual body of the function.
68
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 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.
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 contain no parameters.
Function Body − The function body encompasses a collection of statements that describe what
the function does.
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
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.
69
While designing a C function, provide a definition of what the function must do. To 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.
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.
Example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
70
return result;
}
If a function is to make use of arguments, it must declare variables that accept the 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.
While calling a function, there are two ways in which arguments can be passed to a function
Call by value
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.
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.
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 variable itself is
passed.
71
In Call by value, actual and formal arguments will be generated in different memory locations
whereas in Call by reference, actual and formal arguments will be created in the same memory
location.
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.
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. 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.
Global Variables
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 can be retrieved inside any of the
functions identified for the program.
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.
#include <stdio.h>
void swapnum( int var1, int var2 )
{
int tempnum ;
72
/*Copying temporary variable value into var2 */
var2 = tempnum ;
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: %d, %d", num1, num2);
#include <stdio.h>
void increment(int *var)
{
/* Although we are achieving the increment on variable
* var, however the var is a pointer that holds the address
* of variable num, which means the increment is actually done
* on the address where value of num is stored.
*/
*var = *var+1;
}
int main()
{
int num=20;
/* This way of calling the function is known as call by
* reference. Instead of passing the variable num, we are
* passing the address of variable num
*/
increment(&num);
printf("Value of num is: %d", num);
return 0;
}
4.3.5 Recursion
73
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 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.
The following example calculates the factorial of a given number using a recursive function.
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
74
Fig 4.2 : Working of recursion
Activities :
75
#include<stdio.h>
int main(void)
{
int arr[5] = { 1, 2, 3, 5, 7 };
int *ptr = (&arr + 1);
printf("%d %d\n", *(arr + 1), *(ptr - 1));
return 0;
}
#include<stdio.h>
int main()
{
int a[][3] = {0, 1, 2, 3, 4, 5};
int (*ptr)[3] = a;
printf("%d %d ", (*ptr)[0], (*ptr)[1]);
++ptr;
printf("%d %d\n", (*ptr)[0], (*ptr)[1]);
return 0;
}
#include<stdio.h>
int main()
{
int a[1][2][3] = {0};
a[0][1][2] = 5;
printf("%d",*(*(*(a+0)+1)+2));
return 0;
#include<stdio.h>
void fun(char**);
int main()
{
char *arr[] = { "bat", "cat", "fat", "hat", "mat", "pat" };
fun(arr);
return 0;
}
76
void fun(char **p)
{
char *t;
t = (p += sizeof(int))[-1];
printf("%s\n", t);
}
#include<stdio.h>
int main()
{
function();
return 0;
}
void function()
{
printf("Function in C is awesome");
}
#include<stdio.h>
a()
{
printf("Function");
}
b()
{
printf("Function in C");
}
c()
{
printf("C function");
}
main()
{
77
int (*ptr[3])();
ptr[0] = a;
ptr[1] = b;
ptr[2] = c;
ptr[2]();
return 0;
}
#include<stdio.h>
int function();
main()
{
int i;
i = function();
printf("%d", i);
return 0;
}
function()
{
int a;
a = 250;
return 0;
}
#include<stdio.h>
int function();
main()
{
int i;
i = function();
printf("%d", i);
return 0;
}
function()
{
int a;
a = 250;
}
78
9. Write a program in C to find the square of any number using the function
10. Write a program in C to check a given number is even or odd using the function.
11. Write a program in C to convert decimal number to binary number using the function
12. Write a program in C to get the largest element of an array using the function
13. Write a program in C to check armstrong and perfect numbers using the function
79
Block 5
Course Content:
Pointers
Relationship between arrays and pointers
Argument passing using pointers
Array of pointers
Passing arrays as arguments
Strings and C string library
Structure and Union
Defining C structures
Placing values to members
Array of structure
Nested structure
Passing strings as arguments
File Handling
5. Unit 5
5.1 Pointers
5.1.1 Operators that are used with Pointers
5.1.2 How to Declare a Pointer
5.2 Arrays and Pointers
5.3 Pointers as Function Argument
80
5.4 Functions returning Pointer variables
5.5 Pointer to functions
5.6 Structure and Union in C
5.6.1 How to Create Structure
5.6.2 How to declare structure variables?
5.6.3 How to initialize structure members?
5.6.4 How to access structure elements?
5.6.5 What is an array of structures?
5.7 How to define a union?
5.7.1 Create union variables
5.7.2 Accessing Union Members
5.7.3 Accessing Union Members
5.8 C Structure and Function
5.9 Array of Structures in C
5.10 Structure Store in Memory
5.11 Pointer Within Structure
5.12 File Handling in C
5.12.1 Types of Files
5.12.2 File Operations
5.12.2.1 Mode of operations performed on a file
Unit 5
Unit Outcomes :
1. Define pointers
81
7. Define the types of Files and usage
5.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.
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 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 memory address, which facilitates the C
program to find that value when it is required.
Example:
#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p format specifier and ampersand (&) sign just
before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}
82
“Address of”(&) Operator
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.
#include <stdio.h>
int main()
{
//Pointer of integer type, this can hold the address of a integer type variable.
int *p;
/* 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.
*/
p= &var;
83
printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}
An array is a block of sequential data. Let us write a program to publish addresses of array elements.
#include <stdio.h>
int main() {
int x[4];
int i;
return 0;
}
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).
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.
84
Example: Pointers and Arrays
#include <stdio.h>
int main() {
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
Pointer as a function parameter is utilized to hold addresses of arguments passed through function call.
This is also identified as call by reference. When a function is called by reference any adjustment made
to the reference variable will alter the original variable.
#include <stdio.h>
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
85
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
// pointer 'a' and 'b' holds and points to the address of 'm' and 'n'
A function can likewise return a pointer to the calling function. In this case you must be cautious,
because local variables of function doesn't exist outside the function. They have scope only inside the
function. Therefore if you return a pointer linked to a local variable, that pointer will be pointing to
nothing when the function culminates.
Example:
#include <stdio.h>
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
86
if(*x > *y)
return x;
else
return y;
}
It is feasible to declare a pointer pointing to a function which can be utilized as an argument in another
function. A pointer to a function is proclaimed as follows,
type (*pointer-name)(parameter);
Here is an example :
A function pointer can point to a specific function when it is assigned the name of that function.
#include <stdio.h>
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
87
}
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 can be asserted as a character array or
with a string pointer. Earliest, we take a look at a character array example:
char mystr[20];
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 NULL character.
Example:
#include<stdio.h>
int main()
{
char mystring[20];
mystring[0] = 'H';
mystring[1] = 'E';
mystring[2] = 'L';
mystring[3] = 'L';
mystring[4] = 'O';
mystring[5] = '\n';
mystring[6] = '\0';
printf("%s", mystring);
return 0;
}
%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:
88
#include<stdio.h>
int main()
{
char *ptr_mystring;
ptr_mystring = "HELLO";
printf("%s\n", ptr_mystring);
return 0;
}
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>
int main()
{
char my_array[10];
char *ptr_section2;
return 0;
}
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 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>.
89
The string library (string.h or strings.h) has some handy functions for working with strings, like strcpy,
strcat, strcmp, strlen, strcoll, etc. We will look at a few of these string operations.
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 at the following example:
str_one = "abc";
str_two = "def";
strcpy(str_one , str_two); // str_one becomes "def"
strcmp
This library function is managed to compare two strings and can be applied like this: strcmp(str1, str2).
If the first string is bigger than the second string a number more than null is returned.
If the first string is less than the second string a number less than null is returned.
If the first and the second string are identical, a null is returned.
strcat
This library function concatenates a string onto the end of the new string. The result is returned. Look at
the example:
90
printf("Enter you age: ");
scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);
Note: strcat() will not accomplish any boundary checking, and thus there is a threat of overrunning the
strings.
strlen
This library function put back the length of a string. (All characters before the null termination.) View at
the example:
name = "jane";
result = strlen(name); //Will return size of four.
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.
Ever Since both Structure and Union can hold various type of data in them but now based on internal
implementation, we can find numerous differences in both containers.
Structure is the container well-defined in C to store data variables of different type and supports for the
user defined variables storage.
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
91
‘struct’ keyword is used to create a structure. Following is an example.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
A structure variable can either be declared with structure declaration or as a separate declaration like
basic types.
Example:
int main()
{
struct Point p1; // The variable p1 is declared like a normal
variable
}
92
Structure members cannot be initialized with declaration. For example, the following C program
collapses in compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
Example:
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
return 0;
}
93
Similar to other primitive data types, we can create an array of structures.
Example:
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
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 assign the space to store merely the
largest member.
union car
{
char name[50];
int price;
};
94
5.7.1 Create union variables
When a union is defined, it produces a user-defined type. However, no memory is allotted. To allocate
memory for a given union type and work with it, we require to create variables.
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
We make use of the . operator to access members of a union. To access pointer variables, we use also
use the -> operator.
#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
int main() {
j.salary = 12.3;
95
// j.salary will no longer hold 12.3
j.workerNo = 100;
Example:
#include <stdio.h>
struct student {
char name[50];
int age;
};
// function prototype
void display(struct student s);
int main() {
struct student s1;
return 0;
}
96
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
An array of structures in C can be described as the collection of multiple structures variables where each
variable comprises information about different entities. The array 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.
Members of a structure are always stored in consecutive memory locations but the memory occupied by
each member may vary.
Example:
#include<stdio.h>
struct book
{
char title[5];
int year;
double price;
};
97
int main()
{
struct book b1 = {"Book1", 1988, 4.51};
#include<stdio.h>
struct Student
}s1;
int main()
s1.ptr = &roll;
s1.name = "Pritesh";
98
return(0);
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.
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.
When dealing with files, there are two types of files you should realize about:
1. Text files
2. Binary files
1. Text files
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.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
In C, you can execute four major operations on files, either text or binary:
99
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
There are several modes in opening a file. Based on the mode of file, it can be opened for reading or
writing or appending the texts. They are inventoried below.
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.
a – Opens a file in append mode. It returns null if file couldn’t be opened.
r+ – Opens a file for read and write mode and sets pointer to the first character in the file.
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.
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;
Opening a file is achieved using the fopen() function described in the stdio.h header file.
ptr = fopen("fileopen","mode");
fclose(fptr);
#include <stdio.h>
#include <stdlib.h>
100
int main()
{
int num;
FILE *fptr;
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
101
fscanf(fptr,"%d", &num);
return 0;
}
Activity :
102
return 0;
}
#include<stdio.h>
int main(){
int i = 3;
int *j;
int **k;
j = &i;
k = &j;
k++;
printf("%d ",**k);
return 0;
}
#include<stdio.h>
int main(){
int i = 3;
int *j;
j = &i;
j++;
printf("%d ",*j);
return 0;
}
#include<stdio.h>
#include<string.h>
int main(){
char *ptr = "hello";
char a[22];
103
strcpy(a, "world");
printf("\n%s %s",ptr, a);
return 0;
}
#include<stdio.h>
#include<string.h>
int main(){
char *ptr = "hello";
char a[22];
*ptr = "world";
printf("\n%s %s",ptr, a);
return 0;
}
Details of student 1
Name: Jim
Roll no: 10
Marks: 34.50
Details of student 2
Name: jack
Roll no: 33
Marks: 15.21
Details of student 3
Name: King
Roll no: 34
Marks: 25.21
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.
104
10. Write a program in C to count a number of words and characters in a file.
Mini Project in C
Here is a project we developed as mini project in C bank management system during our first semester;
it is complete and totally error-free. This project is focused on customer account services in bank, so it is
named “Customer Account Bank 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.
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.
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int i,j;
int main_exit;
void menu();
struct date{
int month,day,year;
};
struct {
char name[60];
int acc_no,age;
105
char address[60];
char citizenship[15];
double phone;
char acc_type[10];
float amt;
}add,upd,check,rem,transaction;
float SI;
SI=(rate*t*amount)/100.0;
return (SI);
void fordelay(int j)
{ int i,k;
for(i=0;i<j;i++)
k=i;
void new_acc()
int choice;
FILE *ptr;
106
ptr=fopen("record.dat","a+");
account_no:
system("cls");
scanf("%d/%d/%d",&add.deposit.month,&add.deposit.day,&add.deposit.year);
scanf("%d",&check.acc_no);
if (check.acc_no==add.acc_no)
fordelay(1000000000);
goto account_no;
add.acc_no=check.acc_no;
scanf("%s",add.name);
scanf("%d/%d/%d",&add.dob.month,&add.dob.day,&add.dob.year);
scanf("%d",&add.age);
107
scanf("%s",add.address);
scanf("%s",add.citizenship);
scanf("%lf",&add.phone);
scanf("%f",&add.amt);
scanf("%s",add.acc_type);
fclose(ptr);
add_invalid:
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if(main_exit==0)
close();
else
printf("\nInvalid!\a");
108
goto add_invalid;
void view_list()
FILE *view;
view=fopen("record.dat","r");
int test=0;
system("cls");
printf("\nACC. NO.\tNAME\t\t\tADDRESS\t\t\tPHONE\n");
printf("\n%6d\t %10s\t\t\t%10s\t\t%.0lf",add.acc_no,add.name,add.address,add.phone);
test++;
fclose(view);
if (test==0)
{ system("cls");
printf("\nNO RECORDS!!\n");}
view_list_invalid:
scanf("%d",&main_exit);
system("cls");
109
if (main_exit==1)
menu();
else if(main_exit==0)
close();
else
printf("\nInvalid!\a");
goto view_list_invalid;
void edit(void)
int choice,test=0;
FILE *old,*newrec;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
printf("\nEnter the account no. of the customer whose info you want to change:");
scanf("%d",&upd.acc_no);
if (add.acc_no==upd.acc_no)
test=1;
110
scanf("%d",&choice);
system("cls");
if(choice==1)
scanf("%s",upd.address);
system("cls");
printf("Changes saved!");
else if(choice==2)
scanf("%lf",&upd.phone);
system("cls");
printf("Changes saved!");
else
fclose(old);
111
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test!=1)
{ system("cls");
edit_invalid:
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
edit();
else
{printf("\nInvalid!\a");
goto edit_invalid;}
else
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
112
else
close();
void transact(void)
{ int choice,test=0;
FILE *old,*newrec;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
scanf("%d",&transaction.acc_no);
if(add.acc_no==transaction.acc_no)
{ test=1;
if(strcmpi(add.acc_type,"fixed1")==0||strcmpi(add.acc_type,"fixed2")==0||
strcmpi(add.acc_type,"fixed3")==0)
fordelay(1000000000);
system("cls");
menu();
113
}
scanf("%d",&choice);
if (choice==1)
scanf("%f",&transaction.amt);
add.amt+=transaction.amt;
printf("\n\nDeposited successfully!");
else
scanf("%f",&transaction.amt);
add.amt-=transaction.amt;
printf("\n\nWithdrawn successfully!");
else
114
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.citizenshi
p,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test!=1)
transact_invalid:
scanf("%d",&main_exit);
system("cls");
if (main_exit==0)
transact();
else if (main_exit==1)
menu();
else if (main_exit==2)
close();
else
printf("\nInvalid!");
goto transact_invalid;
115
}
else
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else
close();
void erase(void)
FILE *old,*newrec;
int test=0;
old=fopen("record.dat","r");
newrec=fopen("new.dat","w");
scanf("%d",&rem.acc_no);
if(add.acc_no!=rem.acc_no)
116
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.citizenshi
p,add.phone,add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
else
{test++;
fclose(old);
fclose(newrec);
remove("record.dat");
rename("new.dat","record.dat");
if(test==0)
erase_invalid:
scanf("%d",&main_exit);
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
erase();
else
{printf("\nInvalid!\a");
117
goto erase_invalid;}
else
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else
close();
void see(void)
FILE *ptr;
int test=0,rate;
int choice;
float time;
float intrst;
ptr=fopen("record.dat","r");
scanf("%d",&choice);
if (choice==1)
scanf("%d",&check.acc_no);
118
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.addr
ess,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.d
eposit.year)!=EOF)
if(add.acc_no==check.acc_no)
{ system("cls");
test=1;
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
else if(strcmpi(add.acc_type,"fixed2")==0)
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
119
}
else if(strcmpi(add.acc_type,"fixed3")==0)
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
else if(strcmpi(add.acc_type,"saving")==0)
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
else if(strcmpi(add.acc_type,"current")==0)
120
else if (choice==2)
scanf("%s",&check.name);
if(strcmpi(add.name,check.name)==0)
{ system("cls");
test=1;
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
else if(strcmpi(add.acc_type,"fixed2")==0)
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
121
printf("\n\nYou will get $.%.2f as interest on
%d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+2);
else if(strcmpi(add.acc_type,"fixed3")==0)
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
else if(strcmpi(add.acc_type,"saving")==0)
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
else if(strcmpi(add.acc_type,"current")==0)
122
}
fclose(ptr);
if(test!=1)
{ system("cls");
see_invalid:
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
see();
else
system("cls");
printf("\nInvalid!\a");
goto see_invalid;}
else
scanf("%d",&main_exit);}
123
if (main_exit==1)
system("cls");
menu();
else
system("cls");
close();
void close(void)
void menu(void)
{ int choice;
system("cls");
system("color 9");
124
printf("\n\n\n\t\t\t\xB2\xB2\xB2\xB2\xB2\xB2\xB2 WELCOME TO THE MAIN MENU \xB2\xB2\xB2\
xB2\xB2\xB2\xB2");
scanf("%d",&choice);
system("cls");
switch(choice)
case 1:new_acc();
break;
case 2:edit();
break;
case 3:transact();
break;
case 4:see();
break;
case 5:erase();
break;
case 6:view_list();
break;
case 7:close();
break;
125
}
int main()
char pass[10],password[10]="codewithc";
int i=0;
scanf("%s",pass);
/*do
//if (pass[i]!=13&&pass[i]!=8)
printf("*");
pass[i]=getch();
i++;
}while (pass[i]!=13);
pass[10]='\0';*/
if (strcmp(pass,password)==0)
{printf("\n\nPassword Match!\nLOADING");
for(i=0;i<=6;i++)
fordelay(100000000);
printf(".");
system("cls");
menu();
else
126
{ printf("\n\nWrong password!!\a\a\a");
login_try:
scanf("%d",&main_exit);
if (main_exit==1)
system("cls");
main();
else if (main_exit==0)
system("cls");
close();}
else
{printf("\nInvalid!");
fordelay(1000000000);
system("cls");
goto login_try;}
return 0;
127
Functions used in Bank Management System:
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, 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.
menu() – This function displays the menu or welcome screen to perform different banking activities
mentioned below.
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 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 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.
see() – This function shows account number, name, date of birth, citizenship number, age, address,
phone number, type of account, amount deposited and date of deposit. It also displays the amount of
interest corresponding to a particular account type.
128
Stack Operations Project
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.
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
int stk[MAXSIZE];
int top;
There are four options given to the user for executing the stack. They are Push, Pop, Display and Exit.
while (option)
printf ("------------------------------------------\n");
129
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");
10
11
while (option)
printf ("------------------------------------------\n");
130
printf ("------------------------------------------\n");
int num;
return;
else
s.top = s.top + 1;
s.stk[s.top] = num;
131
Option 4 will return the program from the loop and the main() will exit
10
switch (choice)
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return;
132
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”.
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”.
int num;
if (s.top == - 1)
return (s.top);
else
num = s.stk[s.top];
s.top = s.top - 1;
return(num);
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;
if (s.top == -1)
133
return;
else
printf ("\n");
In this project, you can manage employee records – add, list, modify and delete 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 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 add new features as
you like to make this project a better one!
Add record
List record
Modify record
Delete record
134
#include <stdio.h> ///for input output functions like printf, scanf
#include <stdlib.h>
#include <conio.h>
/**
function : gotoxy
*/
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
135
/** Main function started */
int main()
struct emp
};
* if the file EMP.DAT already exists then it open that file in read write mode
136
*/
fp = fopen("EMP.DAT","rb+");
if(fp == NULL)
fp = fopen("EMP.DAT","wb+");
if(fp == NULL)
exit(1);
recsize = sizeof(e);
while(1)
gotoxy(30,10); /// move the cursor to postion 30, 10 from top-left corner
gotoxy(30,12);
gotoxy(30,14);
137
printf("3. Modify Records"); /// option for editing record
gotoxy(30,16);
gotoxy(30,18);
gotoxy(30,20);
switch(choice)
system("cls");
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
another = 'y';
scanf("%s",e.name);
scanf("%d", &e.age);
138
scanf("%f", &e.bs);
fflush(stdin);
another = getche();
break;
case '2':
system("cls");
while(fread(&e,recsize,1,fp)==1) /// read the file and fetch the record one record per fetch
printf("\n%s %d %.2f",e.name,e.age,e.bs); /// print the name, age and basic salary
getch();
break;
system("cls");
another = 'y';
while(another == 'y')
139
printf("Enter the employee name to modify: ");
scanf("%s", empname);
rewind(fp);
scanf("%s%d%f",e.name,&e.age,&e.bs);
fseek(fp,-recsize,SEEK_CUR); /// move the cursor 1 step back from current position
break;
fflush(stdin);
another = getche();
break;
case '4':
system("cls");
another = 'y';
while(another == 'y')
140
printf("\nEnter name of employee to delete: ");
scanf("%s",empname);
fwrite(&e,recsize,1,ft); /// move all records except the one that is to be deleted to temp
file
fclose(fp);
fclose(ft);
fp = fopen("EMP.DAT", "rb+");
fflush(stdin);
another = getche();
break;
case '5':
141
exit(0); /// exit from the program
return 0;
Customer Billing System Project is a simple console application designed to demonstrate the practical
use of C programming language and its features as wells as to generate an application which can be used
in any departmental store, shops, cafes etc. for billing to the customer.
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:
void input()
void writefile()
void search()
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 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 been defined to show the result as console output.
In Customer Billing System, structure has very beautifully used to group the data type in single unit. The
date variables (day, month and year) have been grouped in the structures named date where as other
variables such as name, number, street, paid amount etc. are grouped under another structure named
account.
Customer Billing System application is so simple to use. In order to use the application, click at the exe
file and then, you will have three options to:
142
1. To add account
2. To search account
3. To exit
As per your need, enter 1, 2,or 3 and follow the instructions provided by the application itself.
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 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.
5. If you have nothing to do with the program, you can directly exit from the main menu.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void input();
void writefile();
void search();
void output();
struct date{
int month;
int day;
int year;
};
struct account {
int number;
143
char name[100];
int acct_no;
float mobile_no;
char street[100];
char city[100];
char acct_type;
float oldbalance;
float newbalance;
float payment;
}customer;
int tl,sl,ts;
void main()
int i,n;
char ch;
clrscr();
_setcursortype(_NOCURSOR);
printf("===============================\n");
printf("3: exit\n");
printf("\n================================\n");
do{
ch=getche();
144
}while(ch<='0' || ch>'3');
switch(ch){
case '1':
clrscr();
scanf("%d",&n);
for(i=0;i<n;i++){
input();
if(customer.payment>0)
else
customer.acct_type=(customer.oldbalance>0)?'D' : 'C';
customer.newbalance=customer.oldbalance - customer.payment;
writefile();
main();
case '2':
clrscr();
printf("search by what?\n");
search();
ch=getche();
main();
case '3':
clrscr();
delay(700);
145
textcolor(RED);
gotoxy(25,25);
delay(1500);
exit(1);
void input()
FILE *fp=fopen("bidur.dat","rb");
fseek (fp,0,SEEK_END);
tl=ftell(fp);
sl=sizeof(customer);
ts=tl/sl;
fseek(fp,(ts-1)*sl,SEEK_SET);
fread(&customer,sizeof(customer),1,fp);
printf("\ncustomer no:%d\n",++customer.number);
fclose(fp);
scanf("%d",&customer.acct_no);
printf("\n Name:");
scanf("%s",customer.name);
scanf("%f",&customer.mobile_no);
printf(" Street:");
scanf("%s",customer.street);
146
printf(" City:");
scanf("%s",customer.city);
scanf("%f",&customer.oldbalance);
scanf("%f",&customer.payment);
scanf("%d/%d/%d",&customer.lastpayment.month,&customer.lastpayment.day,&customer.lastpaymen
t.year);
return;
void writefile()
FILE *fp;
fp=fopen("bidur.dat","ab");
fwrite(&customer,sizeof(customer),1,fp);
fclose(fp);
return;
void search()
char ch;
char nam[100];
int n,i,m=1;
FILE *fp;
147
fp=fopen("bidur.dat","rb");
do{
ch=getche();
switch(ch){
case '1':
fseek(fp,0,SEEK_END);
tl=ftell(fp);
sl=sizeof(customer);
ts=tl/sl;
do{
scanf("%d",&n);
if(n<=0 || n>ts)
printf("\nenter correct\n");
else{
fseek(fp,(n-1)*sl,SEEK_SET);
fread(&customer,sl,1,fp);
output();
printf("\n\nagain?(y/n)");
ch=getche();
}while(ch=='y');
fclose(fp);
break;
case '2':
fseek(fp,0,SEEK_END);
148
tl=ftell(fp);
sl=sizeof(customer);
ts=tl/sl;
fseek(fp,(ts-1)*sl,SEEK_SET);
fread(&customer,sizeof(customer),1,fp);
n=customer.number;
do{
scanf("%s",nam);
fseek(fp,0,SEEK_SET);
for(i=1;i<=n;i++)
fread(&customer,sizeof(customer),1,fp);
if(strcmp(customer.name,nam)==0)
output();
m=0;
break;
if(m!=0)
printf("\n\ndoesn't exist\n");
printf("\nanother?(y/n)");
ch=getche();
}while(ch=='y');
fclose(fp);
149
return;
void output()
textcolor(128+RED);
switch(customer.acct_type)
case 'C':
cprintf("CURRENT\n\n");
break;
case 'O':
cprintf("OVERDUE\n\n");
break;
150
case 'D':
cprintf("DELINQUENT\n\n");
break;
default:
cprintf("ERROR\\n\n");
textcolor(WHITE);
return;
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 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
help() – help menu with game summary and rules
reset_score() – to reset the highest score/cash prize to default
show_record() – shows the highest cash prize won by a particular user
show_score() – to view the highest score
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
151
void show_record();
void reset_score();
void help();
int main()
int countr,r,r1,count,i,n;
float score;
char choice;
char playername[20];
mainhome:
system("cls");
printf("\n\t\t________________________________________");
printf("\n\t\t\t to ");
printf("\n\t\t________________________________________");
printf("\n\t\t________________________________________");
printf("\n\t\t________________________________________");
printf("\n\t\t________________________________________");
152
printf("\n\t\t________________________________________\n\n");
choice=toupper(getch());
if (choice=='V')
show_record();
goto mainhome;
else if (choice=='H')
help();getch();
goto mainhome;
else if (choice=='R')
{reset_score();
getch();
goto mainhome;}
else if (choice=='Q')
exit(1);
else if(choice=='S')
system("cls");
gets(playername);
system("cls");
printf("\n\n Here are some tips you might wanna know before playing:");
153
printf("\n -------------------------------------------------------------------------");
printf("\n >> There are 2 rounds in this Quiz Game,WARMUP ROUND & CHALLANGE ROUND");
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.");
printf("\n >> Your game starts with CHALLANGE ROUND. In this round you will be asked a");
printf("\n By this way you can win upto ONE MILLION cash prize!!!!!..........");
printf("\n >> You will be given 4 options and you have to press A, B ,C or D for the");
printf("\n >> You will be asked questions continuously, till right answers are given");
if (toupper(getch())=='Y')
goto home;
else
goto mainhome;
system("cls");
home:
system("cls");
count=0;
154
for(i=1;i<=3;i++)
system("cls");
r1=i;
switch(r1)
case 1:
printf("\n\nA.42042\t\tB.101010\n\nC.23232\t\tD.01234");
if (toupper(getch())=='C')
printf("\n\nCorrect!!!");count++;
getch();
break;
else
getch();
break;
case 2:
printf("\n\nA.France\t\tB.Denmark\n\nC.Switzerland\t\tD.Finland");
if (toupper(getch())=='C')
155
{printf("\n\nCorrect!!!");count++;
getch();
break;}
else
getch();
break;}
case 3:
printf("\n\nA.Polar Bear\t\tB.Hyena\n\nC.Donkey\t\tD.Chimpanzee");
if (toupper(getch())=='B')
{printf("\n\nCorrect!!!");count++;
getch();
break;}
else
getch();
break;}
case 4:
printf("\n\n\nWho was awarded the youngest player award in Fifa World Cup 2006?");
if (toupper(getch())=='B')
{printf("\n\nCorrect!!!");count++;
getch();
break;}
156
else
getch();
break;}
case 5:
if (toupper(getch())=='B')
{printf("\n\nCorrect!!!");count++;
getch();
break;}
else
getch();
break;}
case 6:
if (toupper(getch())=='D' )
{printf("\n\nCorrect!!!");count++;
getch();
break;}
else
getch();
break;}}
157
}
if(count>=2)
{goto test;}
else
system("cls");
printf("\n\nSORRY YOU ARE NOT ELIGIBLE TO PLAY THIS GAME, BETTER LUCK NEXT TIME");
getch();
goto mainhome;
test:
system("cls");
if(toupper(getch())=='p')
{goto game;}
game:
countr=0;
for(i=1;i<=10;i++)
{system("cls");
r=i;
switch(r)
case 1:
printf("\n\nA.Football\t\tB.Basketball\n\nC.Cricket\t\tD.Baseball");
158
if (toupper(getch())=='C')
{printf("\n\nCorrect!!!");countr++;getch();
break;getch();}
else
goto score;
break;}
case 2:
printf("\n\nA.Seismology\t\tB.Cosmology\n\nC.Orology\t\tD.Etimology");
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
goto score;
break;
case 3:
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;}
else
159
goto score;
break;}
case 4:
printf("\n\nA.Faraday\t\tB.Tesla\n\nC.Maxwell\t\tD.Coulomb");
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
goto score;
break;
case 5:
printf("\n\nA.Coulomb\t\tB.Watt\n\nC.Power\t\tD.Units");
if (toupper(getch())=='B')
{printf("\n\nCorrect!!!");countr++;getch(); break;}
else
getch();
goto score;
break;
160
case 6:
printf("\n\nA.Zinc\t\tB.Cobalt\n\nC.Calcium\t\tD.Iron");
if (toupper(getch())=='B' )
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
getch();
break;}
case 7:
printf("\n\nA.Polska\t\tB.Hellas\n\nC.Drukyul\t\tD.Nippon");
if (toupper(getch())=='D')
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
goto score;
break;}
case 8:
if (toupper(getch())=='B')
{printf("\n\nCorrect!!!");countr++;getch(); break;}
161
else
goto score;
break;}
case 9:
printf("\n\nA.Copenhagen\t\tB.Helsinki\n\nC.Ajax\t\tD.Galatasaray");
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
goto score;
break;}
case 10:
printf("\n\nA.Nile\t\tB.Koshi\n\nC.Ganga\t\tD.Amazon");
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++;getch(); break;}
else
case 11:
printf("\n\nA.White\t\tB.Black\n\nC.Orange\t\tD.Red");
if (toupper(getch())=='C')
162
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
break;goto score;}
case 12:
printf("\n\nA.Rome\t\tB.Vactican City\n\nC.Madrid\t\tD.Berlin");
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
break;goto score;}
case 13:
printf("\n\nA.Japan\t\tB.Italy\n\nC.Argentina\t\tD.France");
if (toupper(getch())=='D')
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
break;goto score;}
case 14:
163
printf("\n\nA.Narayan Wagle\t\tB.Lal Gopal Subedi\n\nC.B.P. Koirala\t\tD.Khagendra
Sangraula");
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
break;goto score;}
case 15:
printf("\n\nA.A\t\tB.AB\n\nC.B\t\tD.O");
if (toupper(getch())=='B')
{printf("\n\nCorrect!!!");countr++;getch();
break;}
else
goto score;
break;}
case 16:
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++; getch();
break;
else
164
{printf("\n\nWrong!!! The correct answer is A.Light Year");getch();
goto score;
break;}
case 17:
printf("\n\nA.Brazil\t\tB.Venezuela\n\nC.Nigeria\t\tD.Bolivia");
if (toupper(getch())=='A')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
break;}
case 18:
printf("\n\nA.Lysimeter\t\tB.Air vane\n\nC.Hydrometer\t\tD.Anemometer\n\n");
if (toupper(getch())=='D')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
break;}
case 19:
printf("\n\nA.Delhi\tB.Bhaktapur\n\nC.Kathmandu\tD.Agra\n\n");
165
if (toupper(getch())=='C')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
break;}
case 20:
printf("\n\nA.Transistor\t\tB.Valves\n\nC.I.C\t\tD.S.S.I");
if (toupper(getch())=='B')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
break;}
case 21:
printf("\n\nA.L.P.G\t\tB.Nitrogen\n\nC.Methane\t\tD. C.F.C");
if (toupper(getch())=='D')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
break;}
case 22:
166
printf("\n\n\nWho won the Women's Australian Open Tennis in 2007?");
if (toupper(getch())=='D')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
break;}
case 23:
printf("\n\n\nWhich film was awarded the Best Motion Picture at Oscar in 2010?");
if (toupper(getch())=='C')
{printf("\n\nCorrect!!!");countr++; getch();
break;}
else
break;}}}
score:
system("cls");
score=(float)countr*100000;
167
else if(score==1000000.00)
else
go:
if (toupper(getch())=='Y')
goto home;
else
edit_score(score,playername);
goto mainhome;}}}
void show_record()
{system("cls");
char name[20];
float scr;
FILE *f;
168
f=fopen("score.txt","r");
fscanf(f,"%s%f",&name,&scr);
printf("\n\n\t\t*************************************************************");
printf("\n\n\t\t*************************************************************");
fclose(f);
getch();}
void reset_score()
{system("cls");
float sc;
char nm[20];
FILE *f;
f=fopen("score.txt","r+");
fscanf(f,"%s%f",&nm,&sc);
sc=0;
fprintf(f,"%s,%.2f",nm,sc);
fclose(f);}
void help()
{system("cls");
printf("\n\n HELP");
printf("\n -------------------------------------------------------------------------");
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 knowledge. You will be eligible to play the game if you can give atleast 2");
169
printf("\n >> Your game starts with the CHALLANGE ROUND. In this round you will be asked");
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");
printf("\n >> You will be asked questions continuously if you keep giving the right answers.");
printf("\n\n\t*********************BEST OF LUCK*********************************");
{system("cls");
float sc;
char nm[20];
FILE *f;
f=fopen("score.txt","r");
fscanf(f,"%s%f",&nm,&sc);
if (score>=sc)
{ sc=score;
fclose(f);
f=fopen("score.txt","w");
fprintf(f,"%s\n%.2f",plnm,sc);
fclose(f);}}
170
171