You are on page 1of 140

Computer System and Programming in C

(GCS101/201)

Notes

RAJEEV RANJAN KUMAR TRIPATHI

ASSISTATNT PROFESSOR, IET

DDU, GORAKHPUR UNIVERSITY

1
UNIT-1
Basics of computer and number system

Number system- A number system of base r is a system that uses distinct symbols for r
digits.
There are four types of number system-
1. Decimal number system
2. Binary number system
3. Octal number system
4. Hexadecimal number system

Decimal Number System: Decimal number system has base 10. This number system contains
10 digits. These are 0,1,2,3,4,5,6,7,8,9. So this number system has base 10. For e.g. (456) 10

Binary Number System: In Binary number system number can be represented using 2 digits
(0 and 1) only .so it has base 2. For e.g. (101101)2
Octal Number System: In Octal number system number can be represented using 8 digits These
are 0,1,2,3,4,5,6,7.so it has base 8 . For e.g. (3457)8

Hexadecimal Number System: In Hexadecimal number system number can be represented


using 16 digits These are 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F where A=10 B=11,C=12,D=13,E14,F=15
For e.g. (345A) 16

Conversion of Number System:-


1. Decimal Number System to Binary Number System:-
(25.625)10 = (X)2
For 25
Output Remainder
25 / 2 = 12 1
12 / 2 = 6 0
6 / 2 = 3 0
3 / 2 = 1 1
1 / 2 = 0 1
For conversion arrange the remainder from bottom to top order.
Therefore RESULT for 25 is (11001)2

2
For fraction part .625 , we follow given procedure:-
0.625*2=1.250 integer part =1
0.250*2 = 0.500 integer part =0
0.500*2 = 1.000 integer part =1
For conversion arrange the Integer Part from top to bottom order.
Therefore RESULT is .1012
Answer is:- (25.625)10 = (11001.101)2

2. Decimal Number System to Octal Number System:-


(25.40)10 = (X)8
For 25
Output Remainder
25 / 8 = 3 1
3 / 8 = 0 3
For conversion arrange the remainder from bottom to top order.
Therefore RESULT for 25 is (31)8
For fraction part .40, we follow given procedure:-
0.40*8=3.20 integer part =3
0.20*8 = 1.60 integer part =1
0.60*8 = 4.80 integer part =4
0.80*8 = 6.40 integer part =6
For conversion arrange the Integer Part from top to bottom order.
Therefore RESULT is (.3146)8
Answer is:- (25.40)10 = (31.3146)8

3. Decimal Number System to Hexadecimal Number System:-


(590.0628)10 = (X)16
For 25
Output Remainder
590 / 16 = 36 14(E)
36 / 16 = 2 4
2 / 16 = 0 2

For conversion arrange the remainder from bottom to top order.


Therefore RESULT for 25 is (24E) 16

For fraction part .40, we follow given procedure:-


0.0628*16=1.0048 integer part =1
0. 0048*16 = 0.0768 integer part =0
0. 0768*16 = 1.2288 integer part =1

3
0. 2288*16 = 3.6608 integer part =3
For conversion arrange the Integer Part from top to bottom order.
Therefore RESULT is (.1013)16
Answer is:- (590.0628)10 = (24E.1013)16

4. Binary Number System to Decimal Number System:-


(1101.101)2 = (X)10

= (1 1 0 1. 1 0 1)2
↑ ↑ ↑ ↑ ↑ ↑ ↑
23 22 21 20 2-1 2-2 2-3

= (1x 23 +1x 22 0x 21 +1x 20 ) . ( 1 x 2-1 + 0 x 2-2 +1 x 2-3 )

= (8+4+0+1).(0.50+0.25+0.125)

= (13 .875) 10

5. Octal Number System to Decimal Number System:-


(121.12)8 = (X)10

= (1 2 1. 1 2 )8
↑ ↑ ↑ ↑ ↑
82 81 80 8-1 8-2

= (1x 82 + 2x 81 +1x 80) . (1 x 8-1 + 2 x 8-2)

= (64+16+8).(0.125+0.03125)

= (88 .15625) 10

6. Hexadecimal Number System to Decimal Number System:-


(1A.B1)16= (X)10

= (1 A. B 1 )2
↑ ↑ ↑ ↑
16 16 16-1 16-2
1 0

= (1x 161 + 10x 160). (11 x 16-1 +1 x 16-2)

= (16+10). (0.6875+0.0039)

= (26 .6914) 10

4
7. Octal Number System to Binary Number System:-
(42.65)8 = (X)2
(4 2. 6 5 )2
↑ ↑ ↑ ↑
100 010 110 101

Answer is:- (42.65)8 = (100010.110101)2

8. Binary Number System to Octal Number System:-


(11101.1111)2 = (X) 8
(0 1 1 1 0 1. 1 1 1 1 0 0 )2
↑ ↑ ↑ ↑
3 5 7 4
Answer is:- (11101.1111)2 = (35.74)8

9. Hexadecimal Number System to Binary Number System:-


(42A.65B)8 = (X)2
(4 2 A. 6 5 B)2
↑ ↑ ↑ ↑ ↑ ↑
0100 0010 1010 0110 0101 1101

Answer is:- (42A.65B)16 = (010000101010.011001011101)2

10. Binary Number System to Hexadecimal Number System:-


(11101.11111)2 = (X)16
(0 0 0 1 1 1 0 1. 1 1 1 1 1 0 0 0 )2
↑ ↑ ↑ ↑
1 D F 8
Answer is:- (11101.11111)2 = (1D.F8)16

11. From Any Number System to Any other Number System:-


(435)6 = (X)4
For this firstly convert base 6 number system into decimal number system. Then convert decimal
number system to Base 4 number system.

(4 3 5) 6
↑ ↑ ↑
62 61 60
= (4x 62 +3x 61 + 5x 60)
5
= (165) 10
Now convert 165 to base 4.
Output Remainder
165 / 4 = 41 1
41 / 4 = 10 1
10 / 4 = 4 2
2 / 4 = 0 2
Answer is:- (435)6 = (2211)4

Computer – The term computer is derived from the word compute. A computer is an electronic
device that takes data and instructions as an input from the user, processes the data according to set of
instructions (called program) and provides useful information known as output.

The electronic device is known as hardware and the set of instructions is known as software.

Analog Computer: Analog Computer may process the real world data like current , voltage
speed in the real time frame i.e. analog computer process the analog data (continuous data).

Basic Functions of Computer: A computer system comprises of software and hardware


components. Hard ware refers to the Physical parts of the computer system and software is
the set of instruction or programs that are necessary for the functioning of a computer to
perform certain task.

H/W includes:
Input Devices: They are used for accepting the data on which the operation are to be
performed the most commonly used input devices among other are;
a) Keyboards b) mouse c) scanner

Processor: It is also known as CPU it is used to perform the calculation and information
processing on data that is entered through the input device.

Output devices: They are used for providing the output of a program that is obtained after
performing the operation specified in a program the e.g. Of O/P devices are:
a) Monitor b) printer c) speaker

Applications of computer:
1. Data processing
2. Numerical computing
3. Text processing
4. Message communication

6
5. Image processing
6. Voice recognition

History: in 1834, an English mathematician Charles Babbage designed an analytical engine. This was
considered as the first programmable digital mechanical computer. This machine contained all the major
parts of the modern computer- system. Charles Babbage is therefore known as the father of modern
computer.

Generation of computers- the different computing devices developed over the years can be
categories into several generations. Each generation of computer is the result of a technological
development , which changes the way to operate computers

Computer can be categories into five generation:-

1. First generation (1940 -1956)


2. Second generation (1956- 1963)
3. Third generation (1963- 1971)
4. Fourth generation (1971 - 1980)
5. Second generation (1980 – till date )

1. First Generation Computer :


• Vacuum tubes were used to build the circuitry for the computer. A vacuum tube was a
device made up of glass and used filaments to generate electrons. It is used amplify the
electronic signals.
• Magnetic drum is used for the memory of computer.
• Size of these computers was very large, single computer was used to cover the space of
an entire room.
• Consume high electricity and generated a large amount of heat.
• Perform calculation in milliseconds.
• They used machine language to perform operation
• Takes Input from punch cards & paper tapes and display the results on paper as
printouts.
• EX. ENIAC(Electronic numerical integrator and Calculator)
EDVAC (Electronic discrete variable automatic computer)
UNIVAC (Universal Automatic Computer)

2. Second Generation Computer :


• Transistor was used instead of vacuum tubes. Transistor was smaller than vacuum
tubes.
• They consume less power and generate less amount of heat than vacuum tube.

7
• Transistors were faster and more reliable than vacuum tubes.
• Used assembly language instead of machine language.
• Since transistors replaced vacuum tubes the size and cost associated with computer is
decreased.
• Takes Input from punch cards & paper tapes and display the results on paper as
printouts.
• EX. IBM 1620, PDP8, CDC1604

3. Third Generation Computer:


• Integrated Circuit (IC) were used in this generation .An IC is a silicon- chip that embeds
on electronic circuit, which comprises several components such as transistor, diode and
registers.
• The use of IC’s had increased the speed and efficiency of computer to a significant
extent.
• Keyboard and monitor is used as I/O and O/P device respectively.
• Cheaper than the previous generation computer
• Ex. IBM 370, PDP11.

4. Fourth generation computer:


• Large scale Integration (LSI) and very large scale integration (VLSI) technology were
used.
• Use semiconductor memories instead of magnetic core memories.
• Use graphical user interface (GUI)
• Smaller and cheaper than the previous generation computer.
• Use high level programming language.
• EX. personal computer (PC)

5. Fifth Generation Computer:


• Ultra large scale integration (ULSI) technology was used.
• Portable in size
• Does not require manual assembly of individual components.
• EX. Intel Pentium microprocessor chip.

Classification of Computer:
Computer can be classified in to several categories depending on their computing ability and
processing speed these are:

8
1. Micro-computer: A microcomputer is defined as a computer that has a microcomputer
as its CPU. The microcomputer system can perform the following basic operations:
Inputting, storage, Processing, Outputting & Controlling.
2. Mini-computer: A minicomputer is a medium sized computer that is more powerful
than a microcomputer .A important distinction between microcomputer and
minicomputer is that unlike microcomputer minicomputer is designed to serve multiple
users simultaneously.
3. Mainframe-Computer: This computer helps in handling the information like banks,
insurance companies, & railways. Mainframe computer are placed on a central location
and are connected to several user terminals, which can act as access station & may be
located in the same building.
4. Super- Computer: super computer are the most powerful and expensive computer
available at present they are also the fastest computer available. It is mainly used for
complex scientific application.

Types of Software: Software is designed as a computer program which include logical


instruction used for performing a particular task on a computer system using hardware
components it is categorized as -

1) System Software: System software refers to a computer program that manages and
controls hardware of computer system .The system software includes general programs
which are written to provide an environment for developing new application software
using programming languages.

For ex. operating system and utility programs are system software. The following are the
various function of system software.

• Process management
• memory management
• secondary storage management
• File and i/o system management

2) Application Software: Application software are those software which are made to run a
particular application. For example if want to listen music we made a music player which
is a application software. Application software is a computer program that is executed
on system software. Application software is unable to run without the system software
such as operating system for ex. MS Excel, MS Office which is the application software.

9
Operating System: The operating system may be considered as a collection of software
program which allows a user to interact with the hardware .The operating system provides
several routines which control the hardware and provide an environment for any user to
execute their application program without knowing the details of the hardware.

“The operating system is system software which is loaded in the memory of computer at the
time of booting process. It remains there all the time and provides a platform on top of which
application program may run.”

User User
Application program

Operating system

Hardware
User
User

Management function of an OS -
The OS are in two modes, single user mode and multi user mode . In single user mode, it is
assumed that only one are user will have to access to all the resources of a computer system .
In the multi user mode, The OS is designed to allow several user at a time .

Based on the resources, OS perform following four management function :

• Memory Management
• Process Management
• Device Management
• File Management

1. Memory Management: The memory management function finds all the available free
space in the memory and allocates it to the processes. The process is a program/ task
under execution stage. The OS manages whole memory by dividing it into several blocks

10
and partition. Every job under execution stage requires memory. If there exist two or
more than two processes then the OS allocates the memory segment as per the
requirement o f the job. When process is executed completely it finally free the
allocated memory space.

2. Process Management: The process management function of OS is related with


allocation of process or job to the processor. The speed of processor or CPU is much
faster than peripheral devices. So the scheduling is done in such a way that CPU
remains idle for minimum amount of time. When a process waits for I/O to be
completed, during that wait time, the CPU may be allocated to other process waiting for
processor.

3. Device management: The function of OS deals with allocation of devices to process. OS


Schedules the I/O devices, I/O channel to process, whenever it requires In I/O
scheduling, after finding the status of device, channels, and a schedule is prepared
which states which device is allocated to the process.

4. File Management: The file management of OS is related with management of files


stored in to secondary storage. The file is considered as collection of logically related
data item which are organized in records. These files may contain a set of commands,
executable code or reports. File managements of OS keeps track of all information on
files. It finds and records the following for all files:
Location, size, usage, status, etc. It also finds as to which process, which file is required,
checks through the protection routine, opens the file if allowed, & allocates it to the
process.

Types of Operating systems: depending on the characteristics of operating systems, they


can be categorized into the following types:

➢ Batch operating system: this is the earliest operating system, where only one program
is allowed to run at one time. We cannot modify any data used by the program while it
is being run .if an error is encountered, it means starting the program from scratch all
over again. a popular batch operating system is MS DOS.
➢ Interactive operating system: this operating system comes after the batch operating
system, where also only one program can run at one time. However, here modification
and entry of data are allowed while the program is running .An example of an

11
Interactive operating system is Mastics (multiplexed information and computing
service).
➢ Multi user operating system: A Multi user operating system allows more than one user
to use a computer system either at the same time or at different times. Example of
Multi user operating system includes Linux and windows 2000.
➢ Multi tasking operating system: A Multi tasking operating system allows more than one
program to run at the same time. Example of Multi tasking operating system includes
UNIX and windows 2000.
➢ Multithreading operating system: A Multithreading operating system allows the
running of different parts of a program at the same time. Example of Multi threading
operating system includes UNIX and Linux.

MS-DOS - Tim Patterson originally developed MS-DOS in 1980. DOS is still 16 bit OS and does
not support multiple users or multitasking. MS-DOS stands for Microsoft Disk operating System.
This OS was originally written for the IBM pc by the Microsoft Corporation. The first release of
the DOS came in 1981 which is a single user operating system, which allows the user to enter
command using textual interface.

How to start dos in windows:


➢ Go to start
➢ Click program
➢ Then click Accessories
➢ & then MS-DOS Command prompt

1. In MS-DOS there are internal commands & external commands. Internal commands are
contained in the file command.com, which is loaded in to memory at the booting of the
computer system. Copies, delete, Direct are internal command.

2. External commands are contained in separate files, which usually have extension .com
or .exe or .bat. Sys, tree, xcopy, FORMAT etc are external commands.

Some commands which are used in MS DOS are:

➢ CD change the current directory


Syntax: c:\> cd xyz

➢ MKDIR create new subdirectory


Syntax: c:\> mkdir xyz

➢ RMDIR deletes any directory by specifying its path.


12
Syntax: c:\>Rmdir \xyz\yz

➢ Del to deletes the file in the directory


Syntax: c:\> Del file name

➢ Edit to write content on file


Syntax: c:\> Edit filename

➢ Type to show content of file


Syntax: c:\> Type filename

➢ Copy copy one or more file from source to destination


Syntax: c:\>Copy filename1 filename2

➢ Cls clear the screen


Syntax: c:\> Cls

➢ Date show the system date


Syntax: c:\> Date

➢ Time show the time


Syntax: c:\> Time

➢ Ver. Show the system OS version.

UNIX Architecture:
UNIX is multi user, multi tasking operating system. UNIX has a hierarchical architecture
consisting of several layers provides a unique function as well as maintains interaction with its
lower layers. Such hierarchal or modular architecture is advantageous for the operating system
as failure of one layer does not disrupt the functioning of the whole OS. The layers of the Unix
OS are:

➢ Kernel
➢ Service
➢ Shell
➢ User application

13
Kernel: Kernel is the core of the Unix OS and it gets loaded in to memory whenever switch on
the computer. The kernel contains three components which are:
Scheduler: it schedules the processing of various jobs
Device Driver: it helps in controlling the I/O devices attached to the computer.
I/O Buffer: it controls the I/O operations in the computer.

The kernel enables a user to access the hardware with the help of system calls, where a system
calls is a service request that is passes to the kernel for the executing a user program.

Functions perform by the kernel:

➢ Initiating & executing different program at the same time.


➢ Allocating memory to the various user and system processes.
➢ Monitoring the files that reside on the disk.
➢ Sending & receiving information to and from the network.

Service: In the service layer, request is received from the shell and they are then transformed
into command to the kernel.
Services include:
➢ Providing access to various input and output devices such as keyboard and monitor.
➢ Providing access to storage device, such as disk drives.
➢ Controlling different file manipulation activities such as reading from a file & writing to a
file.

Shell: The third layer in the UNIX architecture is the shell which acts as an interface between a
user and the computer for accepting the request and executing programs.
“Shell is the command line interpreter. User interacts with system through shell.”
UNIX has following most popular shell:

Shell command prompt

Bourne shell $

C shell %

Korn shell $

Bash shell #

User Application: The last layer in the UNIX architecture is the user application, which is
used to perform several tasks and communicating with other user of UNIX.

14
E.g.- text processing, software development, database management , & electronic
communication.
User Application
Shell
Service layer
Kernel
Hardware

(Fig. The Layer of Unix operating system)

General purpose commands of UNIX OS:

cal: display the calendar


Syntax: $cal [month][year]

date: display the system date and time.


Syntax: $date

who: display the list of users currently logged in


Syntax: $ who

ls: display the list of files/directories.


Syntax: $ ls [-option]
Some options are: -c (list entries by columns)
-r (list subdirectory too)

cp: copy one file to another


Syntax: $ cp filename1 filename2

mv: move one file to another


Syntax: $ mv filename1 filename2

cat: display the content of file.


Syntax: $ cat filename

mkdir: create a new directory/subdirectory.


Syntax: $mkdir dirname

rm: remove a file/directory.

15
Syntax: $rm filename

rmdir: remove or delete directories & subdirectories


Syntax: $rmdir dirname

who am i: give the login details.


Syntax: $who am i

LINUX Operating System: Linux is basically multiuser, multitasking operating system. It


provides character interface & graphical user interface. Both for interacting with computer.It
was originally designed and developed by ‘Linux Bendict Torvalds in the year 1991.

➢ The objective behind developing Linux was to bring out an operating system, which was
low in cost and had the power of UNIX operating system.
➢ Its Version is available free of cost to everyone.
➢ Many software developing companies have incorporated many functionalities into it
and are marketing it .Red Hats Linux is one such operating system and many more also
exist.
➢ Linux also has powerful networking features incorporated in to it and has built in
internet facilities.
➢ Linux has gained popularity these days and is emerging as parallel competitor, window
and UNIX operating system.
➢ Linux operating system provides both type of user interface. It supports CUI & GUI both.
graphical interface provides windows look alike working environment, features like drag
and drop, cut and paste, file sharing , multitasking etc. are also available in Linux.
Character user interface of Linux is really powerful and provides thousands of
commands for doing wide variety of tasks.

Some Linux Commands which are used in day to day function:

ls display the name of all files present in current directory

cat display the content of file

cp copy the content of a file to another file.

mv move a file from one directory to another

mkdir makes a new directory

rmdir removes a blank directory

16
cd user can move from one directory to another

pwd display the name of current directory(current working directory)

Syntax: $pwd

vi edit a file

passwd change the password

chmod change file permissions

who display the names of all current users

grep searching the occurrence of a given string in a file

Syntax: $grep filename(s)

sort sort the given content either in ascending order or descending order

find finds file, if the file of given name is present.

Linux is powerful operating system, which is getting more popular everyday. Large
population of personal computer (PC) and laptops comes with preloaded Linux, These days it is
likely to gain, more popularity in coming future.

Advantages of Linux:

➢ Low cost
➢ Stability - it has high stability with other OS .there is no need to reboot the Linux system
to maintain performance level.
➢ Performance - provides high performance on various networks
➢ Networking-Linux provides a strong support for network functioning.
➢ Flexibility- it can be used for high performance server applications, desktop applications.
➢ Compatibility-it can process all common file formats.
➢ Fast and easy installation
➢ Better use of hard disk
➢ Multitasking
➢ Security
➢ Open source

Uses of Linux:

17
➢ Desktop
➢ Server and supercomputer
➢ Embedded devices
➢ Market share

Microsoft Window Operating System: MS Window was introduced by Microsoft


Corporation in the year 1985. It was brought in as an odd on to MS-Dos due to growing interest
of users in GUI’s. The first version of MS Window is 1.0, released in 1985.It did not provide a
complete system, rather it provide an extended version of MS-DOS. After this window1.90,
window 3.0 was released. After success of window 3.0, Microsoft come up with several new
version of window OS. Some are given below:

Window 95: released in august 24, 1995


New features:
• plug and play
• 32-bit OS
• Registry
• Right mouse click

Window 98: released in June 1998


New features:

• improved protection through backup


• Improved data supports (supports new devices such as DVD, USB)
• Internet Explorer
• Customizable Taskbar

Window 2000: released in February 2000


New features:
• protect memory of individual application and processes to
• that failure of a single application cannot bring the system down
• Includes greater supports for high speed networking devices such
as cable modems & native ATM.
• Supports NTFS along with the supports for both FAT16 & FAT32.

Window XP: released in October 2001

It is mainly used on general purpose computer system. The letter ‘XP’ in Window XP stands for

18
Experience. Window XP is the first consumer oriented OS. That is built on the Window NT
Kernel & architecture by Microsoft. The most common edition of Window XP are the Window
XP Home EDITION AND Window XP Professional.

Window Vista: released in 2007. It was upgraded version of window XP and Window 2000

New features:
• New multimedia creation tools such as DVD Maker.
• Ability to automatically detect and correct problems that are
encountered on the computer
• A completely new GUI & Visual style known as Window Aero.
• Improved searching features that provides instant search
available through all explorers Window.
Programming Environment:
A programming Environment comprises all those components that facilitate the development
of a program. These components are largely divided in two categories:

➢ Programming tools
➢ Application programming interface
Programming tool:
The software application which used for the development maintenance and debugging of a
software program is known as programming tools some of programming tools
Some of programming tools are:

➢ Integrated Development Environment (IDE): It is the most commonly used tool that
offers on an integrated environment to the programmer for the software development.
It contains compiler, editor, and debugger. Etc
➢ Debugging tool: It is a special tool that helps the programmer to detect and removes
bugs or errors from a program.
➢ Memory usage tools: It helps the programmer to manage the memory resources in an
efficient manner

Application programming interface (API’s):

An API can be defined as a collection of data structures, classes, protocols, and predefined
function stored in the form of libraries these libraries are included in the software package of
the programming language like c, c++ etc. An API makes the development task easier for the
programmer as a in-built API components are used again and again ensuring reusability

19
Digital Computer (Von Neumann Architecture):
A digital computer is a programmable machine which reads binary instruction and process the
data which are presented in binary form.

The digital computer takes the binary data as an input processes according to the set of
instructions called programs and produces the digital output. The computer which we
commonly used today are digital.

A digital computer may be represented by the following schematic diagram:

CPU (central processing unit)


Accumulator

ALU General Purpose


Input unit
Register Output unit
The Control unit

Primary Memory

Auxiliary (secondary) Memory

Following are the main fictional units of the digital computer

Central processing Units (CPU):

20
The CPU is the brain of a computer where all kinds of processing is done. This unit’s takes the
input data from the input devices and processes it according to the set of instruction called
program. The output of the processing data is directed to the output devices for the use in the
outside world.
The major function of the CPU is to store the data temporarily in the register and perform
arithmetic &logical computation. This unit also controls the operation of all other functional
units of the computer such as input & output devices.
CPU has four major parts called:

➢ ALU (Arithmetic Logical Unit): The function of an ALU is to perform arithmetic and
logical operation such as addition, subtractions,, multiplication and division,
AND,OR,NOT,XOR operation. It also perform increment, decrement, left shift, clear and
any others operations.
➢ Accumulator: CPU also contains a set of register called accumulator. A register may be
thought of as a unit capable of storing eight or more bits. The one byte register is
capable of storing one byte (8 bits) at a time. Each bit is stored in a device called flip-
flop. Flip flop are the electronic circuit capable of storing a bit temporarily.
➢ General purpose Register: It is also called programmable register. These register are at
the disposal of the programmer and he may write a program to use them according his
needs in order to execute the program.
➢ Control Unit: The control unit is the most important part of the CPU as it control and co-
ordinates the activities of all other units such as ALU, memory unit & output unit. The
control unit (cu) acts as the nervous system. All the related function for program
execution such as memory read , I/O write, execution of instruction are synchronized
through the control signal generated by the CPU.

Memory: Memory is also known by term storage and its function is store coded form of
information from the human operator through input devices.

Similarly, the result produced by the computer after processing must be kept somewhere
before they are passed on to the output unit for display. Moreover, the intermediate results
produced by the computer must also be preserved.

Primary / Main Memory: The primary / main memory of the computer provides, supports for
these storage function. The main memory is a fast memory. it stores program along with data
the main memory is directly accessed by the CPU. The result produced by the computer after
processing must be kept somewhere before they are passed on to the output unit for display.
Moreover, the intermediate results produced by the computer must also be preserved.

21
The primary / main memory of the computer provides, supports for these storage function. The
main memory is a fast memory. It stores program along with data the main memory is directly
accessed by the CPU.

Cache Memory: In the system it has depend upon the main memory to supply the instruction
and data as and when it needs. Because the CPU runs as much faster than the main memory
system. It ends up waiting for information, which is inefficient to reduce this effect we have
cache memory cache temporarily stores instruction & data that the processor is likely to use
frequently. Thus cache speeds up processing.

CPU Primary or
Main Memory

Cache
Memory

RAM (Random Access Memory): RAM temporarily stores program instruction and data before
and after it is processed by the CPU. RAM is said to be “Volatile- “ - The contents are lost when
the power goes off or is turned off. RAM is also referenced to as Read write Memory

ROM (Read only Memory): ROM is also a part of memory and it is also called non-volatile. As
the name indicates, the ROM can be used only for reading or fetching of data from it . The data
or program is written into ROM only once it has been written it cannot be modified or altered.
The term “non- volatile” means that even if the power is switched off, the data or program
stored in ROM is not destroyed. When the power comes, the same data appears once again.
This is happen because of the permanent hardware pattern used to store the data in ROM.

22
One of the important usages of ROM is to store the Basic Input- Output Software (BIOS). This
program is very important as it is used by the OS at the time of starting-up or booting the
system. Since this program is used every time the computer is turned on, it must be stored in
the ROM.

Why ROM is non-volatile?

The data stored in the form of permanent nature. When the power o ROM is switched off, the
data is not deleted. When the power is switched on ROM retains the data stored in the
memory, ROM is based on the fact that there is a mesh of diodes or fuses placed in the matrix
form. The selected fuses are burnt as per the data stored in the memory.

Similarly, the presence or absence of the diode or fuse denotes whether bit ‘1’ or ‘0’ is stored.
Since the pattern of placing diodes or fuses is decided by the manufacturers of ROM, it
becomes a permanent pattern.

Four types of ROM:

MASKED-ROM (MROM): It is manufactured by the masking and metallization process. The


pattern or matrix once created is permanent and no change or alteration is permissible
afterwards.

Programmable RPM (PROM): It is programmed by the programmer. PROM is manufactured by


placing a fuse at all position. A special device called PROM programmer is used to store the
desired pattern by selectively burning the fuses. Those fuses are burnt whenever a bit ‘0’ has to
be stored. The presence of a fuse represents the presence of bit 1. The pattern stored through
this process is permanent in nature.

Erasable PROM (EPROM): EPROM are programmable ROM which may be programmed again
and again. This is so happen because the pattern stored on EPROM is a semi-permanent. It can
be erased by exposing it to Ultra-Violets light.

Electrically- Erasable PROM (EEPROM):It is same as EPROM the only difference being that
electrical signal are used to program PROM . It can be erased by exposing electrical signal.

Secondary Memory or Auxiliary Memory: Secondary memory is used to store the OS, compiler,
assembler, application, program, data files etc. These are not directly read by CPU if any

23
information is needed to be processed from the secondary memory; it must be first transferred
to the primary memory. The secondary memory is used for mass storage. Hard disk is used for
this purpose. Examples: - Magnetic Media: - Hard disk, magnetic tape, Floppy Disk

Optical Media: - Compact Disk (CD), Digital Versatile ssDisk (DVD)

Input-unit: Input unit in the functional diagram of digital computer represents the various input
device which are used to input the real world data in to the computer. The function of the
Input-Unit is to accepts coded information from the human operator or from the
electromechanically device or from other computer connected to it through an internet or by
any other media. Input device converts the human data into the form which is acceptable by
the digital computer.

E.g.: keyboard, mouse, scanner are the input devices

Output Unit: The output unit is used to represents the information processed by the digital
computer. The function of the output unit is to store the processed information and display it
as and when needed by the user. Cathode Ray Tube (CRT) terminals, printers and speakers are
the example of the output devices.

Algorithm:-An algorithm is a complete, detailed, and precise step by step method for solving
a problem independently of the software and hardware of the computer.

Efficiency of an algorithm (termination and correctness): Efficiency of an algorithm


means how fast it can produce the correct result for the given problem. The efficiency of an
algorithm depends upon its time complexity and space complexity.

➢ Space complexity: space complexity of an algorithm refers to the amount of memory


required by algorithm for its execution and generation of the final output.
➢ Time complexity: time complexity of an algorithm refers to the amount of computer
time required by an algorithm for its execution. This time include both compile time and
run time.

Analysis of an algorithm: The Analysis of an algorithm determines the amount of resources


such as time and space required by it, for its execution. Algorithm analysis provides theoretical
estimates for its complexity and this complexity can be denoted in asymptotic notations. The
basic notation used to represent the complexity of an algorithm is:

Characteristic of an algorithm: there are five important characteristic of an algorithm

24
➢ Input- it may accept zero or more input
➢ Output- it should produce at least one output.
➢ Definiteness- each instruction must be clear, well defined and precise. there should not
be any ambiguity.
➢ Finiteness -it should be a sequence of finite instructions.
➢ Effectiveness- operation must be simple and carried out in a finite time at one or more
levels of complexity.

Question: write an algorithm for finding greatest among three numbers.


Algorithm:
Step 1: START
Step 2: Read three number x, y, z.
Step 3: If x>y
a) If x>z then x is greatest number
b) Else z is greatest number
Step 4: else
a) If y>z then y is greatest number
b) Else z is greatest number
Step 5: Stop

Flowchart- when step by step solution of a given problem is illustrated in the form of
graphical chart that chart is called flowchart.
Symbols of flow chart:
Terminal box- this symbol is used to represent starting and stopping of a program.

start Stop

Processing box- All arithmetic process such as addition, multiplication, division, subtraction are depict in
processing box. It is denoted by rectangle.

Processing box

Read / write box- A parallelogram is used to depict the reading /writing process.

25
Read /write box
(Input/output box)

Decision box- A diamond symbol is used for depicting comparison of two values or condition checking or
decision making in flowchart.

Decision
box

Flow line- a flow line is a simple line with an arrow at its front end. The head of arrow depicts the
direction of flow.

Connecter – there are two type of connecter are used in the flowchart.
➢ Same page connecter
➢ Off-page connecter.

Same page connecter off page connecter

Question: Give a flow chart for finding the given number is odd or even.

Flowchart:

Start

Input x

Divide x/2

Is Print x is 26
remainder odd
=1?
AA

Print x is
even

Stop
Programming Language:
A computer program is basically a set of instruction which when executed by the computer do a specific
task. The CPU processes the data as per the instruction given to it. The instruction is written using
various syntax and rules. Programming language provides the set of rules / syntax/ instruction format in
which the various instructions are written. There are three types of programming languages:

➢ High level languages


➢ Assembly languages
➢ Machine languages(low level language)

Low level language: a language in which each statement or an instruction is directly translated in to a
single machine code.
E.g. Machine language.

Machine code: it contains the string of binary numbers (0’s and 1’s) and is machine dependent. It means
that the machine language for every processor is different. It is referred as 1’st generation language.

The machine language is divided in to two pats


➢ Operation code (op code)
➢ Operands (binary data)

Ex. consider the following m/c language instruction of the microprocessor 8085
This program adds two hexadecimal number 20H and 30H stored in register A& B. the result is stored in
register C.

Hexadecimal code Binary Code Remark

3E 00111110 move the data 20 to register A

27
20 00100000

06 00000110 move the data 30 to register B

30 00110000

80 10000000 add the content of A & B

4F 01001111 moves the result from accumulator to register C

The main advantage of machine language is that the processor can create it without any translation

The disadvantage of machine language is as follow:


➢ It is very difficult to remember
➢ Machine dependent, so same code can not be used for different machine.
Assembly language:
In assembly language the 0’s and 1’s of machine are replaced by abbreviation or mnemonics code. It is
referred as second generation language .An assembly language instruction consist of a mnemonics code
followed by zero or more operands. During execution, assembly language program is converted in to
machine code with the help of assembler.

For e.g. MVI A, 20H 3E 00111110


20 00100000
ADD A, B 60 0110111

Advantages:
➢ Reduced programming complexity.
➢ It is easy to find error and also easy to debug.
➢ I t is easy to develop program than machine language.

Disadvantage:
➢ The coding of assembly language is time consuming
➢ It is also machine oriented as the code for one machine is not used by the other one.

High level language:


To overcome the problem of the low level language, the high level languages were developed. High level
languages are machine independent.
➢ It is easier to learn
➢ It is easier to maintain
➢ They provide better documentation

For e.g. COBOL, BASIC, PASCAL, C are all high level languages.

28
Each high level languages provides its own construct/ syntax and setoff statements.

Differences among High level languages, Assembly languages and Machine languages.

High level languages Assembly languages Machine languages

1. Easy to understand 1. Less under stable 1. Very difficult to understand

2. Program are portable


2. Not portable-
Portable only to processor 2. Not portable-
having same interpreter Portable only to processor of
same architecture

3. Complex
3. Debugging is easier 3. Very complex

4. Not suited for software


4. Most suited software Development. 4. No translation is required.
development Uses assembler to
Uses compiler and
generate object code
interpreter to generate
object code

Compiler: A program that translate source code in to object code. The compiler derives its names
from the way it works, it looking at the entire piece of source code, collecting and rearranging the
instruction. It also checks that t he program is grammatically correct.

29
Source file Source file Source file

Object code Object code Object code

Library Linker Executable program

Interpreter:
It also a program that translates a high level language in to low level one. But it does it at the moment
the program is run. it takes the program , one line at a time and translate each line before running it.
The interpreter has no memory for the translated lines, so if it comes across lines of the program within
a loop, it must translate them every time that particular line runs.

Assembler:
The assembly codes are easier to write but the processor still executes the machine codes. Therefore a
translator is required to translate the assembly language program in to machine language program.

“The assembler is a program which converts the assembly language program in to machine code which
may be executed by processor.”

Assembly language Assembler Machine language


program Object code

Introduction to the design and Implantation of correct, Efficient and


maintainable program (program development life cycle)
The design and development of a correct efficient and maintainable program depends on the approach
followed by the programmer. a programmer should follow standard methodologies throughout the

30
lifecycle of the of program development. The entire program development process is divided in to a
number of phases:

Analysis phase: The first phase of program development involves analyzing the problem in order to
ascertain the objective that the program is supposed to meet. This phase also emphasizes on
determining the input and output values of the program.

Designing phase: This phase involves making the plan of action before actual starting the development
work. The plan is made on the basis of program specification identified in the previous phase. Different
programs requires different designing pattern depending on the program specification. It basically helps
to break the program in to small modules or chunks .This breaking of the large program in to smaller
chunks results in the development of well organized program.

Development Phase: this phase involves writing the instruction or code for the program, in any
language, on the basis of design document created in the previous phase.

Implementation and Testing: In this phase the developed program is implemented in its target
environment and its key parameters are closely observed in order to ensure that the program runs
correctly. We also test the program for hidden bugs. To identify such bugs programs needs to be tested
using large number of varied input values.

Analysis phase

Designing phase

Development Phase

Implementation and Testing

Top down Design (stepwise refinement)

Program development includes designing coding testing and verification of a program in any computer
language. For writing a good program, the top down design approach can be used . It is also called
systematic programming or stepwise refinement.

A complex problem is broken in to smaller sub problem, further each sub problem is broken in to a
number of smaller sub problem and so on till the sub problem at the lowest level are easy to solve.

31
Similarly, a large program is broken in to a number of subprogram and in turn each subprogram is
further decomposed in to subprogram and so on.

The operation of coding a subprogram in terms of lower level subprogram is known as the process of
stepwise refinement.

Fig shows the hierarchical decomposition of P in to its subprograms and sub- subprograms.

P1 P2 P3

P21 P22

(Fig. Illustration of stepwise refinement)

Advantage of top down design approach:

➢ A large problem is divided in to a number of smaller problems using this approach. The
decomposition is continued till the sub problem at the lowest level become easy to solve.
➢ The programs become user friendly (that is easy to read and understand) and easy to maintain
and modify.
➢ Different programmers can write the modules for different levels.

Structured Programming:
A method of planning programs that avoid the branching category of control structure.”

32
➢ Structured programming can be seen as a subset or sub discipline of procedural programming.
One of the major programming paradigms .procedural programming can be used for specifying
the steps the program must take to reach the desired state.
➢ It is most famous for removing or reducing re- occurrence of the go to statement.
➢ Structured programs avoid unstructured control flows by restricting the use of GOTO statements

The main objectives of structured programming are


• Efficiency
• Readability
• Clarity of programs
• Easy modification
• Reduced testing problems

The Three basic building blocks for writing structured programming are:

Sequence control structure: It consists of a single statement or a sequence of statements with a


single entry and single exit.

Selection control structure: It consist of a condition and two branches out of which one is to be
followed depending on the condition being true or false.

33
Example:

if (age > 17)

{
printf(“you can vote”);
}
else
{
printf(“you can’t vote”);
}

Loop control structure: Also known as repetition, it allows some code to be executed several times
.The code might not be executed at all, executes a fixed number of times or executed indefinitely until;
some condition is met.

e.g. counter=0;
while (counter<5)
{
printf(“i am best”);
counter++;
}

Advantage of structured programming-


➢ Research experience have shown that programmers commit less no. of errors, while using
unstructured, if-then else and do-while statements then when using test and braces code
constructs.

➢ Structured programs are normally more readable, easier to maintain, and require less- effort to
develop the program, compared to unstructured programs.

34
UNIT-2
Basics of programming , data types and operators

C Tokens
Tokens are individual words and punctuation marks in passage of text. In C, program the
smallest individual units are known as C Tokens. C has Six types of Tokens. The Tokens are
shown in figure.

Keywords: All keywords have fixed meaning and these meanings cannot be changed.
Keywords serve as basic building blocks for program statements. All keywords must write in
lower case .there are 32 keywords are in C. They are:

auto double int struct

break else long switch

35
case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

Identifiers: Identifiers are the names that are given to various program elements such as
variables, symbolic constants and functions and array. Basically identifiers are the sequences of
alphabets or digits.

Rules for forming identifier name

1. Identifier name must be a sequence of letter and digits, and must begin with a letter.
2. The underscore character (‘_’) is considered as letter.
3. Names shouldn't be a keyword (such as int , float, if ,break, for etc)
4. Both upper-case letter and lower-case letter characters are allowed. However,
they're not interchangeable.
5. No special characters, such as semicolon, period, blank space, slash or comma are
permitted.
6. Must not contain whitespace.

Constant: A constant is an entity that doesn't change during the execution of a program.
Followings are the different types of constants:

1. REAL CONSTANT:
• It must have at least one digit.
• It must have a decimal point which may be positive or negative.
• Use of blank space and comma is not allowed between real constants.
• Example:
+194.143, -416.41

2. INTEGER CONSTANT:

• It must have at least one digit.


• It should not contain a decimal place.
• It can be positive or negative.
• Use of blank space and comma is not allowed between real constants.

36
• Example:
1990, 194, -394

3. CHARACTER CONSTANT:

• It is a single alphabet or a digit or a special symbol enclosed in a single quote.


• Maximum length of a character constant is 1.
• Example:
'T', '9', '$'

4. STRING CONSTANT:
• It is collection of characters enclosed in double quotes.
• It may contain letters, digits, special characters and blank space.
• Example:

"Technowell Web Solutions, Sangli"

Special Symbols: Some special symbols are also used to develop the program.
For eg- [ ] ( ) { } , : = ; ... #

Operators: An operator is a symbol that tells the computer to perform certain


mathematical or logical manipulations. For eg- +, - , * , /, || , & , ^, ! , etc.

Escape Sequence Characters (Backslash Character Constants) in C:


C supports some special escape sequence characters that are used to do special tasks.
Some of the escape sequence characters are as follow:

Character Constant Meaning

\n New line (Line break)

\b Backspace

\t Horizontal Tab

\f Form feed

\a Alert (alerts a bell)

\r Carriage Return

37
\v Vertical Tab

\? Question Mark

\' Single Quote

\'' Double Quote

\\ Backslash

\0 Null

Variable: A variable is a meaningful name of data storage location in computer memory.


When using a variable you refer to memory address of computer.

The Programming language C has two main variable types


• Local Variables
• Global Variables

1. Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
2. When a local variable is defined - it is not initialized by the system, you must initialize it
yourself.

DATA TYPE
C language is rich in its data types. C supports following classes of data types.
1. Primary/Fundamental data types
2. Derived data types/composite data types

38
All c compiler support five fundamental data types, namely integer (int), character (char),
floating point (float), double-precision floating point (double) and void.
1. Integer types: integers are whole numbers with a range of values supported by a
particular machine. The size of an integer that can be stored depends on the computer.
if we use a 16 bit word length , the size of an integer value is limited to the range -32768
to +32767 (-215 to 215-1).

2. Floating point types: Floating point numbers are stored in 32 bits, with 6 digits of
precision. Floating point numbers are defined in c by the keyword float .when the
accuracy provided by a float number is not sufficient; the type double can be used to
define the number.

3. Double – precision floating point: A double data type number uses 64 bits giving a
precision of 14 digits. These are known as double precision numbers. Remember that
double type represents the same data type that float represents, but with greater
precision. To extend the precision further, we may use long double which which uses 80
bits.

4. Character types: A single character can be defined as character (char) type data.
Characters are usually stored in 8 bits (one byte) of internal storage. The qualifier signed
or unsigned may be explicitly applied to char. While unsigned chars have values
between 0 to 255, signed chars have values from -128 to 127.

5. Void types: the void type has no values. This is usually used to specify the type of
functions. The type of a function is said to be void when it does not return any value to
the calling function.

Size and range of data types


Data types Range Bytes format
Signed char -128 to 127 1 %c

Unsigned char 0 to 255 1 %c

Short signed int -32768 to32767 2 %hd

Short unsigned int 0 to 65535 2 %hu

39
signed int -32768 to32767 2 %d

unsigned int 0 to 65535 2 %u

long signed int -2147483648 to 4 %ld


+2147483648

long unsigned int 0 to 4294967295 4 %lu

float -3.4E38 to +3.4E38 4 %f

double -1.7E308 to +1.7E308 8 %lf

long double -1.7E4932 to +1.7E4932 10 %Lf

Standard input and output in C:


Standard input (stdin): Standard input is data going into a program. The program requests data
transfers by use of the read operation.

Standard output (stdout): Standard output is the stream where a program writes its output
data. The program requests data transfer with the write operation.

Console I/O requires the declaration:

#include <stdio.h>

Useful functions include:

printf() Print a formatted string to stdout.


scanf() Read formatted data from stdin.
putchar() Print a single character to stdout.
getchar() Read a single character from stdin.
puts() Print a string to stdout.
gets() Read a line from stdin.

PC-based compilers also have an alternative library of console I/O functions. These functions
require the declaration:
#include <conio.h>

The two most useful PC console I/O functions are:

getch() Get a character from the keyboard (no need to press Enter).
getche() Get a character from the keyboard and echo it.

40
Formatted input : function scanf accepts all types of data in the program. General format for
scanf function is :
Scanf(format specifier,variable1,variable2,…);

Format specifier is a string of characters which contain information of the format in which data
will be accepted from the keyboard.

Formatted output : function printf display all the type of data on screen. general format for
printf function is :
printf(format specifier,variable1,variable2,…);

Reading a character : using getchar function one can accept single character from the keyboard
into the program, general format is :
char var=getchar();

Writing a character: the put char function display single character on the screen .a single
argument is passed in this function .for example:
putchar(var();

Operators and expression:


An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in program to manipulate data and variable.
C operators can be categories as:

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Compound assignment operators
5. Increment and decrement operator
6. Bitwise operators
7. Ternary conditional
8. Special operators

1. Arithmetic operators: The arithmetic operator is a binary operator, which requires


two operands to perform its operation of arithmetic. Following are the arithmetic
operators that are available in C:
Assume variable A holds 10 and variable B holds 20 then:

41
operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from A - B will give -10
the first
* Multiply both operands A * B will give 200
/ Divide numerator by de numerator B / A will give 2
% Modulus Operator and remainder B % A will give 0
of after an integer division

2. Relational operators: Relational operators compare between two operands and


return in terms of true or false i.e. 1 or 0. In C and many other languages a true value is
denoted by the integer 1 and a false value is denoted by the integer 0. Relational
operators are used in conjunction with logical operators and conditional & looping
statements. Following are the various relational operators:

Assume variable A holds 10 and variable B holds 20 then:

Operator meaning Description Example

== Is equal to Checks if the value of two (A == B) is not true.


operands is equal or not,
if yes then condition
becomes true.

!= Is not equal Checks if the value of two (A != B) is true.


to operands is equal or not,
if values are not equal
then condition becomes
true.

> Greater than Checks if the value of left (A > B) is not true.
operand is greater than
the value of right
operand, if yes then
condition becomes true.

< Less than Checks if the value of left (A < B) is true.


operand is less than the
value of right operand, if
yes then condition
becomes true.

>= Greater than Checks if the value of left (A >= B) is not true.
or equal to operand is greater than
or equal to the value of
right operand, if yes then

42
condition becomes true.

<= Less than or Checks if the value of left (A <= B) is true.


equal to operand is less than or
equal to the value of
right operand, if yes then
condition becomes true.

3. Logical Operators: A logical operator is used to compare or evaluate logical and


relational expressions. There are three logical operators available in the C language.
Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is true.


operands are non zero then then
condition becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non zero then then
condition becomes true.

! Called Logical NOT Operator. Use to !(A && B) is false.


reverses the logical state of its operand.
If a condition is true then Logical NOT
operator will make false.

These operators are used when we want to test mor than on condition and make
decision. An example is : (a>b )&& (x==10)

4. Assignment Operators: An assignment operator (=) is used to assign a constant or a


value of one variable to another. In addition , C has a set of ‘shorthand ‘assignment
operator of the form :

variable op= expression


Where op is C binary arithmetic operator. The operator op= is known as shorthand
assignment operator.

operator Description Example

= Simple assignment operator, Assigns values C = A + B will assign value of A + B into


from right side operands to left side C
operand

43
+= Add AND assignment operator, It adds right C += A is equivalent to C = C + A
operand to the left operand and assign the
result to left operand

-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A


subtracts right operand from the left
operand and assign the result to left
operand

*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A


multiplies right operand with the left
operand and assign the result to left
operand

/= Divide AND assignment operator, It divides C /= A is equivalent to C = C / A


left operand with the right operand and
assign the result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent to C = C % A


modulus using two operands and assign the
result to left operand

<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2


operator

|= bitwise inclusive OR and assignment C |= 2 is same as C = C | 2


operator

5. Increment and Decrement Operators: the increment and decrement operators are
very useful in C language. They are unary operators as they are applied on only one operand.
They are extensively used in for and while loops. The syntax of these operators is given below.

operators Syntax Meaning

increment Prefix ++a The value of a will be increment by 1

Suffix a++ The value of a will be increment by 1

decrement Prefix --a The value of a will be decrement by 1

Suffix a-- The value of a will be decrement by 1

44
a++ and a++ both are have same meaning when they form statement independently. they
behave differently when they are used in expressions.

For e.g. M=5


Y=++M (here the value of y is 6 and value of m is 6)
and

M=5
Y=M ++ (here the value of y is 5 and value of m is 6)

6. Conditional Operator: A conditional operator checks for an expression, which


returns either a true or a false value. If the condition evaluated is true, it returns the
value of the true section of the operator, otherwise it returns the value of the false
section of the operator.
Its general structure is as follows:

Expression1? Expression 2 (True Section): expression3 (False Section)

a=3, b=5, c;

c = (a>b) ? (a+ b) : (b-a); ( here c = b-a=2)

7. Bitwise Operators: Bitwise operator works on bits and performs bit by bit operation.
Bitwise operators may not be applied to float or on double.

Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
Now A & B = 0011 1100
& 0000 1101

0000 1100

A>>2 = 0000 1111

There are following Bitwise operators supported by C language

Operator Description Example

& Binary AND Operator copies a (A & B) will give 12 which


bit to the result if it exists in is 0000 1100
both operands.

45
| Binary OR Operator copies a (A | B) will give 61 which is
bit if it exists in eather 0011 1101
operand.

^ Binary XOR Operator copies (A ^ B) will give 49 which


the bit if it is set in one is 0011 0001
operand but not both.

~ Binary Ones Complement (~A ) will give -60 which is


Operator is unary and has the 1100 0011
efect of 'flipping' bits.

<< Binary Left Shift Operator. A << 2 will give 240 which
The left operands value is is 1111 0000
moved left by the number of
bits specified by the right
operand.

>> Binary Right Shift Operator. A >> 2 will give 15 which


The left operands value is is 0000 1111
moved right by the number of
bits specified by the right
operand.

8. Special operators: C supports some special operators such as comma operator, sizeof
operator, pointer operator and member operator.

Comma operator: A comma expression contains two operands of any type separated by a
comma and has left-to-right associatively. If there is more operand separated by comma in any
expression then the value of right most is the value of the combined expression.

For e.g. value=(x=12,y=10,x+y)


Then value=22.

Operator Description Example


sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return
4.
& Returns the address of an &a; will give actual address of the
variable. variable.

. Member operator

* Pointer to a variable. *a; will pointer to a variable.

Type conversion in expressions

46
1. Implicit type conversion : C automatically converts any intermediate values to the
proper type so that the expression can be evaluated without losing any significance.
This automatic conversion is known as Implicit type conversion.

2. Explicit type conversion : there are instances when we want to force a type
conversion in a way that is different from the automatic conversion. the process of
such conversion is known as Explicit type conversion.
The general form of cast is :
(type name) expression
For e.g. x=(int) 5.56
A=(int) 2.4c / (int) 4.6 = (2/4)
Operator precedence and associatively:
This list shows the C operators in order of precedence (highest to lowest). Their
associatively indicates in what order operators of equal precedence in an expression
are applied.

Operator Description Associativity


() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment

47
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

storage class in C
A variable name identifies some physical location within the computer where the string of bits
representing the variable’s value is stored. There are basically two kinds of locations in a
computer where such a value may be kept— Memory and CPU registers. Moreover, a variable’s
storage class tells us:

(a) Where the variable would be stored.

(b) What will be the initial value of the variable, if initial value is not specifically assigned.(i.e.
the default initial value).

(c) What is the scope of the variable; i.e. in which functions the value of the variable would be
available.

(d) What is the life of the variable; i.e. how long would the variable exist.

1. Automatic Storage Class-it is local variable known only to the function in which it is
declared. (default is auto).

Storage − Memory.

D default initial value − An unpredictable value, which is


often called a garbage value.

S Scope − Local to the block in which the


variable is defined.

Li life − Till the control remains within the


block in which the variable is
defined.

Void main( )
{
auto int i = 1 ;
{
{
auto int i = 2;
48
{
auto int i = 3 ;
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
}
The output of the above program is:
321

2. Register Storage Class- local variable which is stored in the register.

Storage - CPU registers.

D default initial value - Garbage value.

S Scope - Local to the block in which the


variable is defined.

Lilife - Till the control remains within the


block in which the variable is
defined.

If a variable is used at many places in a program it is better to declare its storage class as
register. A good example of frequently used variables is loop counters. We can name their
storage class as register.
Void main( )
{
register int i ;
for ( i = 1 ; i <= 10 ; i++ )
printf ( "\n%d", i ) ;
}

3. Static Storage Class- local variable which exists and retains its value even after the control is
transferred to calling function.

St
storage − Memory.

D default initial value − Zero.

49
S Scope − Local to the block in which the
variable is defined.

Lilife − Value of the variable persists


between different function calls.

Compare the two programs and their output given in program to understand the difference
between the automatic and static storage classes.

Void main( )
{
increment( ) ;
increment( ) ;
increment( ) ;
}

increment( )

auto int i = 1 ;

printf ( "%d\n", i ) ;

i=i+1;

Output: 111

Void main( )
{
increment( ) ;
increment( ) ;
increment( ) ;
}

increment( )

static int i = 1 ;

printf ( "%d\n", i ) ;

50
i=i+1;

Output:123

4. External Storage Class- global variable known to all function in the file.

Ststorage − Memory.

Ddefault initial value − Zero.

S scope − Global.

Li life − As long as the program’s execution


doesn’t come to an end.

int i ;
void main( )
{
printf ( "\ni = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
}
increment( )
{
i=i+1;
printf ( "\non incrementing i = %d", i ) ;
}
decrement( )
{
i=i-1;
printf ( "\non decrementing i = %d", i ) ;
}
The output would be:
i=0
on incrementing i = 1
on incrementing i = 2
on decrementing i = 1
on decrementing i = 0

51
Solve the following:
a) main()
{
int x=10,y,z;
z=y=x;
y -= x--;
z -= --x;
x= --x – x--;
printf(“y=%d\nz=%d\nx=%d”, y,z,x);
} Output: y=0,z=2,x=1

b) int a=10,b;
b=a++ + ++a;
printf(“%d%d%d%d”,b,a++,a,++a);
Output: 22,13,13,13
c) int z,x=5,y=-10,a=4,b=2;
z= x++ - --y*b/a;
printf(“%d”,z); Output: 10

d) If a=10, b=12,c=0,find the values of the expressions in the following :

a) a!=6 && b>5


b) a==9 II b<3
c) ! (a<10)
d) ! (a>5 && c)
e) 5 && c!=8 II !c

Output: (a) 1 (b) 0 (c) 1 (d) 1 (e) 1

e) find the value:


a) d=(5+5>=10);
b) e=5+5==10||1+3==5;
c) f=5>10||10<20&&3<5;
d) g=10!=15&&!(10<20)||15>30;

Output: (a) 1 (b) 1 (c) 1 (d) 0


f) int x=100;
printf("%d\n",10+x++);
printf("%d\n",10+ ++x);
Output: 110
112

52
UNIT-3
Conditional program execution and function

Decision making and branching


C language possesses such decision making capabilities by supporting the following statements

➢ If statements
➢ Switch statements
➢ Conditional operator statement
➢ goto statement

These statements are popularly known as decision – making statements. Since these statements control
the flow of execution, they are also known as control statements.

Decision making with if statements: the if statement is a powerful decision –making


statement and is used to control the flow of execution of statements. It is basically a two-way decision
statement .it takes the following forms:
entry

if(test expression) Test false


expression

true
the different forms of if statement are:
➢ simple if statement
➢ if……else statement
➢ nested if …….else statement
➢ else if ladder

1. Simple if statement: the general form of a simple if statement is


entry
if ( test expression )
{
statement block
} Test true
statement-x; expression

Statement block
False

Statement-x

53
If the test expression is true, the statement - block will be executed, otherwise the statement- block will
be skipped and the execution will jump to the statement-x.
void main ()
{
inta,b,c,d;
float ratio ;
printf(“enter the value of a,b,c,d”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
if((c-d)!=0)
{ ratio= (float) (a+b)/(c-d);
printf(“ratio=%f”,ratio);
}
getch();
}

2. The if……else statement: the if …else statement is an extension of the simple if


statement. the general form is:
entry
if ( test expression )
{
true block statement
} true Test false
else expression
{
false block statement True block False block
} statement statement
Statement-x;

Statement-x

If the test expression is true, then the true block statements are executed otherwise, the false block
statements are executed.

➢ Write a program which read two values .if the value are same then print “ I am fine “
otherwise it print “ try again “.

void main()
{
inta,b;
printf(“enter the value of a,b”);
scanf(“%d%d”,&a,&b);
if(a==b)
printf(“i am fine”);
54
else
printf(“i am fine”);
getch();
}

➢ Write a program to find greatest between given two numbers.

void main()
{
inta,b;
printf(“enter the value of a,b”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“a is greater”);
else
printf(“b is greater”);
getch();
}

3. Nesting of if….else statements: when a series of decisions are involved, we may


have to use more than one if….else statement in nested form.

if (test condition-1) entry


{
if(test condition-2)
{ false true
Test
statement-1
condition-1
}
else
{
statement-2 false true
Statement-3 Test
}
condition-2
}
else
{
statemenmt-3 Statement-2 Statement-1
}
statement –x

Statement-x

55
➢ Write a program to find greatest among given three numbers.

void main ()
{
int a,b,c;
printf(“enter the value of a,b,c”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
printf(“a is greater”);
else
printf(“c is greater”);
}
else
{
if(b>c)
printf(“b is greater”);
else
printf(“c is greater”);
}
getch();
}

4. The else if ladder: there is another way of putting if’s together when multipath
decisions are involved. A multipath decision is a chain of if’s in which the statement
associated with each else is if. It takes the following form:

if(condition-1)
Statement-1;
else if(condition-2)
Statement-2;
.
.
.
.
.
else if(condition-n)
Statement-n;
else
Default statement;
Statement-x;

56
True false
Condition-1

True false
Statement-1 Condition-2
.

Statement-2

True false
Condition-n

Statement-n

Statement-x Default Statement

➢ Write a program to find greatest among given four numbers.


void main()
{
Int a,b,c,d;
printf(“enter the numbers”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
if(a>b&&a>c&&a>d)
printf(“a is greater”);
else if(b>a&&b>c&&b>d)
printf(“b is greater”);
else if(c>a&&c>b&&c>d)
printf(“c is greater”);
else if(d>a&&d>b&&d>c)
printf(“d is greater”);
getch();
}

➢ Write a C program to enter marks of 3 subjects of a student and then calculate the total
marks and % marks. Find out the grade of the student as per following conditions.

Per>95 Grade –A
Per<=95 & Per>85 Grade –B
Per<=85 & Per>75 Grade –C
Per<=75 & Per>65 Grade –D

57
Per<=65 Fail
void main()
{
Int a,b,c,sum;
float per;
printf("enter the three numbers");
scanf("%d%d%d",&a,&b,&c);
sum=a+b+c;
per=(sum*100)/300;
printf("%d%f",sum,per);
if(per>95)
printf("grade-a");
else if(per<=95&&per>85)
printf("grade-b");
else if(per<=85&&per>75)
printf("grade-c");
else if(per<=75&&per>65)
printf("grade-d");
else if(per<=65)
printf("fail");
else
printf("try again");
getch();
}

➢ Write a program which accepts the category code and print as follows:
If code is ‘s’ then print “SC/ST”
If code is ‘b’ then print “BACKWARD”
If code is ‘h’ then print “HANDICAPPED”
If code is ‘a’ then print “ARMY”
If code is ‘g’ then print “GENRAL”

void main()
{
char code;
printf(“enter the code”);
scanf(“%c”,&code);
if(code==’s’)
printf(“sc/st”);

58
else if(code==’b’)
printf(“backward”);
else if(code==’h’)
printf(“handicapped”);
else if(code==’a’)
printf(“army”);
else if(code==’g’)
printf(“general”);
else
printf(“your code is wrong”);
getch();
}
➢ Write a program to print month name using else if. for example if code is 1 print January.
void main()
{
int code;
printf(“enter the code”);
scanf(“%d”, &code);
if(code==1)
printf(“january”);
else if(code==2)
printf(“february”);
else if(code==3)
printf(“march”);
else if(code==4)
printf(“april”);
else if(code==5)
printf(“may”);
else if(code==6)
printf(“june”);
else if(code==7)
printf(“july”);
else if(code==8)
printf(“august”);
else if(code==9)
printf(“september”);
else if(code==10)
printf(“october”);
else if(code==11)
printf(“november”);
else if(code==12)

59
printf(“december”);
else
printf(“your code is wrong”);
getch();
}
➢ Write a program to print week days using else if. For example if code is 1 print Monday.
➢ Write a program which accepts the color code and print as follows:
If code is ‘r’ then print “RED”
If code is ‘b’ then print “BLUE”
If code is ‘p’ then print “pink”
If code is ‘w’ then print “white”
If code is ‘g’ then print “GREEN”

Decision making with switch statements:the switch statement tests the value of a given
variable (or expression) against a list of case value and when a match is found, a block of statements
associated with that case is executed. the general form of switch statement is as shown as:

switch(expression)
{
case value1 : Expression
block -1;
break; expression=value1
case value2 :
Block -1
block -2;
break; expression=value2
case value3 : Block -2
block -3;
break; expression=value3 Block -3
------- -
------ -
------ -
default: -
default block ; default Default
break; block
}

Rules for switch statement: Statement -x


• The switch expression must be an integral type.
• Case labels must be constants.
• Case label must be unique. no two labels can have same value.
• There can be at most one default label.

60
• The break statement transfers the control out of the switch statements.
➢ Write a program to print week days using switch statement. For example if code is 1 print
Monday.
void main()
{
int code;
printf(“enter the code”);
scanf(“%d”, &code);

switch(code)
{
case 1:
printf(“Monday”);
break;
case 2 :
printf(“Tuesday”);
break;
case 3 :
printf(“Wednesday”);
break;
case 4 :
printf(“Thursday”);
break;
case 5:
printf(“Friday”);
break;
case 6 :
printf(“Saturday”);
break;
case 7 :
printf(“Sunday”);
break;
default:
printf(“your code is wrong”);

}
getch();
}

➢ Write a program using switch statement ,which accepts the color code and print as follows:
If code is ‘r’ then print “RED”
If code is ‘b’ then print “BLUE”
If code is ‘p’ then print “pink”
If code is ‘w’ then print “white”
If code is ‘g’ then print “GREEN”

61
void main()
{
char code;
printf(“enter the code”);
scanf(“%c”, &code);
switch(code)
{

case ‘r’:
printf(“RED”);
break;
case ‘b’ :
printf(“BLUE”);
break;
case ‘p’ :
printf(“PINK”);
break;
case ‘w’ :
printf(“White”);
break;
case ‘g’:
printf(“GREEN”);
break;
default:

printf(“your code is wrong”);


}
getch();
}

➢ Write a program using switch statement ,which accepts the category code and print as
follows:
If code is ‘s’ then print “SC/ST”
If code is ‘b’ then print “BACKWARD”
If code is ‘h’ then print “HANDICAPPED”
If code is ‘a’ then print “ARMY”
If code is ‘g’ then print “GENRAL”
➢ Write a program to print month name using switch statement. For example if code is 1 print
January.
➢ Write a program to print any one number in the word from 0,1,2,3,4,5,6,7,8,9 using switch
statement.

62
The goto statement: C supports the goto statements to branch unconditionally from one point
to another in the program. The goto requires a label in order to identify the place where the branch is to
be made. A label is any valid variable name, and must be followed by a colon. The label is placed
immediately before the statement where the control is to be transferred. The general forms of goto and
label statements are shown below:

goto label; label:


------------ statement;
------------ ---------------
------------ ---------------
label: ---------------
statement; goto label;

(Forwarded jump) (Backward jump)

#include<math.h>
void main()
{
float x,y;
read:
scanf(“%f”,&x);
if(x<0)
goto read;
y=sqrt(x);
printf(“%f: %f”,x,y);
getch();
}

The repetition control statement (looping) - in looping, a sequence of statements


are executed until some conditions for termination of the loop are satisfied.

A program loop consists of two segments, one known as the body of loop and the other known as the
control statement. The control statement tests certain conditions and then directs the repeated
execution of the statements contained in the body of the loop.

Depending upon the position of the control statement in the loop, a control structure may be classified
either as the entry –controlled loop or as the exit-controlled loop.

63
Entry controlled loop (pretest loop) - this loop evaluates the control condition first before the
execution of body of loop. C-provides two type of the entry controlled loop.
➢ while loop
➢ for loop

Exit controlled loop (post test loop) - this loop first of all executes the statements of loop-body.
Then the control condition is evaluated .if the condition is evaluated as true, then the repetition
continues otherwise the program – control exits the loop body. C-provides one type of the exit
controlled loop.
➢ do—while loop

A looping process would include following four steps:


➢ Setting and initialization of a condition variable.
➢ Execution of the statements in the loop.
➢ Incrementing or updating the conditional variable.
➢ Test for a specified value of the condition variable for execution of the loop.

The while statement (while loop) - the basic format of the while statement is:
While(test condition)
Loop control
{

Body of loop false


Test
} condition

Body of loop
True

Exit

The while is an entry-controlled loop statement. The test condition is evaluated first and if the condition
is true, then the body of loop is executed. After execution of the body the test condition is once again
evaluated and if it is true the body of loop is execute once again. This process of loop, repeated
execution of the body till the test condition becomes falseand then control is transferred out of the
loop.

➢ Write a program to print the numbers from 1 to 100.


void main()
{
int i=1;
while(i<=100)
{
64
printf(“%d\t”);
i++;
}
getch();
}
➢ Write a program to print the even numbers from 1 to 100.
void main()
{
int i=1;
while(i<=100)
{
If(i%2==0)
printf(“%d\t”);
i++;
}
getch();
}
➢ Write a program to print the odd numbers from 1 to 100.
void main()
{
int i=1;
while(i<=100)
{
If(i%2!=0)
printf(“%d\t”);
i++;
}
getch();
}
➢ Write a program to print the sum of n integer numbers.
void main()
{
int i=1,sum=0,n;
printf(“enter the value of n”);
scanf(“%d”,&n);
while(i<=n)
{
sum=sum+i;
i++;

65
}
printf(“sum of numbers=%d”,sum);
getch();
}
➢ Write a program to find the sum of even and sum of odd from 100 to 500.
void main()
{
int i=100,sumeven=0,sumodd=0;
while(i<=500)
{
if(i%2==0)
sumeven=sumeven+i;
else
sumodd=sumodd+i;
i++;
}
printf(“sum of even=%d\n sum of odd=%d”,sumeven, sumodd);
getch();
}
➢ Write a program to find the sum of digits of a given number.
void main()
{
intr,sum=0,n;
printf(“enter the value of n”);
scanf(“%d”,&n);
while(n!=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf(“sum of digits=%d”,sum);
getch();
}

➢ Write a program to find the reverse of a given number.


void main()
{
intr,rev=0,n;

66
printf(“enter the value of n”);
scanf(“%d”,&n);
while(n!=0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
printf(“revers of number=%d”,rev);
getch();
}
➢ Write a program to find the sum of the given series.( 11+22+33+44+55+…………….nn)
#include<math.h>
void main()
{
int i=1,sum=0,n;
printf(“enter the value of n”);
scanf(“%d”,&n);
while(i<=n)
{
sum=sum+pow(i,i);
i++;
}
printf(“sum of number of series=%d”,sum);
getch();
}

➢ Write a program to check the given number is palindrome or not.


void main()
{
intr,rev=0,n,num;
printf(“enter the value of n”);
scanf(“%d”,&n);
num=n;
while(n!=0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
67
}
if(rev==num)
printf(no is palindrome”);
else
printf(no is not a palindrome”);
getch();
}

The do…while statement (do ..while loop) - the basic format of the while statement is:
do
Loop control
{

body of loop Body of loop

}while(test condition);
True false
Test
condition

exit from the loop

On reaching the do statement, the program proceeds to evaluate the body of loop first .at the end of
the loop, the test-condition in the while statement is evaluated. If the condition is true, the program
continues to evaluate the body of the loop once again. This process continues as long as the condition is
true. When the condition becomes false, the loop will be terminated and the control goes to statement
that appears immediately after the while statement.

➢ Write a program to find theGCD (greatest common divisor) of two positive numbers.
void main()
{
intr,a,b;
printf(“enter the value of a and b”);
scanf(“%d%d”,&a,&b);
do
{
r=a%b;
a=b;
b=r;

68
}while(r!=0);
printf(“GCD=%d”,a);
getch();
}

Differentiate between while and do while loop.


While loop do ……. While loop

1. In while loop the condition is 1. In do –while loop the condition evaluated


evaluated before the execution of after one execution of the loop-body.
loop body.
2. The body of the loop executes at least once
always, whether the control- condition
2. It is not necessary that the body of evaluates true or false.
loop will be executed.
3. The first execution of the loop body is not
3. The first execution as well as dependent on control-condition.
repetition of the loop body is
always depends on control-
condition

For statement (for loop) -the for loop is another entry – controlled loop that provides a more
concise loop control structure. The general form of the for loop is-

Syntax of for loop:-


for (initialization; test condition; increment/decrement)
{

Body of loop

69
Initialization of
control variable

False
Test
condition

True

Body of the loop

Increment /
decrement

Exit from loop

The execution of for statement is as follows:-

1. Initialization of the control variable is done first.


2. The value of the control variable is tested using the test condition. The test condition is
relational expression. Itdetermines when the loop will exit. if the condition is true the body of
loop is executed .otherwise the loop is terminated
3. When the body of loop is executed ,the control is transferred back to the for statement after
evaluating the last statement in the loop .now the control variable is updated and it is again
tested to see whether it satisfied the loop condition .if condition is again true the body of loop is
again executed otherwise the loop will exit.

➢ Write a program to find the factorial of a given number.


void main()
{
inti,fact=1,n;
printf(“enter the value of n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf(“factorial=%d”,fact);

70
getch();
}

➢ Write a program to print the Fibonacci series up to n terms.


void main()
{
int i,f0=0,f1=1,f2,n;
printf(“enter the value of n”);
scanf(“%d”,&n);
printf(fibonacci series are:\n”);
printf(“%d\t%d\t”,f0,f1);
for(i=1;i<=n-2;i++)
{
f2=f0+f1;
printf(“%d\t”,f2);
f0=f1;
f1=f2;
}
getch();
}

➢ Write a program to print the even numbers from 1 to 100 using for loop.
void main()
{
int i;
for(i=1;i<=100;i++)
{
if(i%2==0)
printf(“%d\t”,i);
}
getch();
}

➢ Write a program to find the given number is prime or not.


void main()
{
int i ,c=0,n;
printf(“enter the number”);
scanf(“%d”,&n);
for(i=2;i<=n-1;i++)
{
if(n%i==0)
c++;
}

71
if(c==0)
printf(“given number is prime”);
else
printf(“given number is not prime”);
getch();
}

➢ Write a program to find the sum of even and sum of odd from 100 to 500 using for loop.
void main()
{
inti,sumeve=0,sumodd=0;
for(i=100 ; i<=500 ;i++)
{
if(i%2==0)
{
sumeve=(sumeve+i);
}
else
{
sumodd=(sumodd+i);
}
}
printf("sum of even no. are %d",sumeve);
printf("sum of odd no. are %d",sumodd);
getch();
}

➢ Write a program to find the Armstrong number between 100 and 1000.
void main()
{
ints,n,i,p,num;
clrscr();
for(i=100;i<=1000;i++)
{
p=0;
num=i;
while(num>0)
{
s=num%10;
p=p+(s*s*s);
72
num=num/10;
}
if(p==i)
printf("\t%d",p);
}
getch();
}
➢ Write a program to find the sum of the given series.
(1/1! +2/2! +3/3! +4/4! +5/5! +…………….n/n!)

void main()
{
int i,fact=1,n;
float sum=0;
int fact(int x);
printf(“enter the value of n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+ (float)i/ fact(i);
}
printf(“factorial=%d”,fact);
getch();
}
int fact (int x)
{
if (x==1)
return(1);
else
return(x*fact(x-1));
}

Nested for loop-when one for loop is completely placed within the other for loop then they
are called to be nested for loop.Nested loop must have following rules:
1. One loop must be completely placed inside the other loop.
2. Each loop must have different index variables.
The general syntax of nested for loop is:

73
for (initialization1; test condition1; increment1/decrement1)
{

for (initialization2; test condition2; increment2/decrement2)


{
Body of
Outer loop body of inner loop

}
}

Initialization1

Test
Exit from outer loop false Increment1/decrement1
condition1
True

Initialization2

False
Test
condition2
True
Increment2/decrement2

Body of inner loop

➢ Write a program to generate the following series:


a) b)
1 *
12 **
123 ***
1234 ****
12345 *****

74
void main() void main()
{ {
int i , j; int i , j;
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
{ {
printf(“%d”,j); printf(“*”);
} }
printf(“\n”);
printf(“\n”);
}
} getch();
getch(); }
}

➢ Write a program to generate the following series:


a)b)
12345 54321
1234 4321
123 321
12 21
1 1
void main() void main()
{ {
int i , j; int i , j;
for(i=5;i>=1;i--) for(i=5;i>=1;i--)
{ {
for(j=1;j<=i;j++) for(j=i;j>=1;j--)
{ {
printf(“%d”,j); printf(“%d”,j);
} }
printf(“\n”);
printf(“\n”);
}
} getch();
getch(); }
}

75
➢ Write a program to generate the following series:
1
121
12321
1234321
123454321

void main()
{
int i , j;
for(i=1;i<=5;i++)
{
for(j=4;j>=i; j--)
{
printf(“ ”);
}
for(j=1;j<=i;j++)
{
printf(“%d”,j);
}
for(j=i-1;j>=1;j--)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch();
}

➢ Write a program to generate the following series:

a) ***** b) 1
**** 22
*** 333
** 4444
* 55555
void main() void main()
{ {
int i , j; int i , j;

76
for(i=5;i>=1;i--) for(i=1;i<=5;i++)
{ {
for(j=1;j<=i;j++) for(j=1;j<=i;j++)
{ {
printf(“*”); printf(“%d”,i);
} }

printf(“\n”); printf(“\n”);

} }
getch(); getch();
} }

➢ Write a program to generate the following series:


A
AB
ABC
ABCD
ABCDE

void main()
{
int i , j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
Switch(j)
{
case 1: printf(“A”);
break;
case 2: printf(“B”);
break;
case 3: printf(“C”);
break;
case 4: printf(“D”);
break;
case 5: printf(“E”);
break;
}
}
printf(“\n”);

77
}
getch();
}

➢ Write a program to generate the following series:

1 b) *
2 3 4
**
5 6 7 8 9
***
10 11 12 13 14 15 16
****
17 18 19 20 21 22 23 24 25 *****

void main()
{
inti,j,m=1; void main()
clrscr();
{
for(i=1;i<=5;i++)
introw, c, n, temp;
{
for(j=5;j>=i;j--) printf("enter the number of rows in pyramid ");
printf(" \t ");
scanf("%d",&n);
for(j=1;j<=i;j++)
{ temp=n;
printf("%d\t",m);
m++; for(row=1;row<=n;row++)
} {
for(j=1;j<=i-1;j++) for(c=1;c<temp;c++)
{ {
printf("%d\t",m); printf(" ");
m++; }
} temp--;
printf("\n");
} for(c=1;c<=2*row-1;c++)
getch();
{
}
printf("*");

78
}

printf("\n");

}
getch();
}

➢ Write a C program that generates the prime numbers between10 to 500.


void main()
{
int i,j,c,n;
for(i=10;i<=500;i++)
{
n=i;
c=0;
for(j=2;j<=n-1;j++)
{
if(n%j==0)
c++;
}
if(c==0)
printf(“%d\t”,i);
}
getch();
}

➢ Write a program to generate the following series:


1
123
12345
1234567

void main()
{
inti,j,m=1,k;
clrscr();
for(i=1;i<=5;i++)
{

79
for(j=5;j>=i;j--)
printf(" \t ");
for(j=1;j<=i;j++)
{
printf("%d\t",j);
}
for(k=1;k<=i-1;k++)
{
printf("%d\t",j);
j++;
}
printf("\n");
}
getch();
}

The break statement: the break statement allows to terminate the execution of the loop
and to jump out of the loop. When we want to jump out of a loop instantly, without waiting to
get back to the conditional test, the keyword break allows us to do this. Thus when the break
statement is encountered inside a loop, the loop is immediately terminated and the control of
execution is transferred to the next statement immediately following the loop.For example:

void main()
{
int i;
for (i=0;i<100;i++)
{
printf(“%d”,i);
if(i==10)
break;
}takes control here
printf(“out of loop”);
}

The continue statement: like the break statement ,C supports another statement
‘continue’ .the continue as the name implies , causes the loop to be continue , with the next
iteration after skipping any statements in between. The continue statements tells the compiler
‘skip ‘the following statements and continue with the next iteration. For example:

void main()

80
{
int i;
for(i=1;i<=100;i++)
{
if(i%2==0) takes control here
continue;
else
printf(“%d”,i);
}
getch();
}

Functions (modular programming): A function in C can perform a particular task and


support the concepts of modular programming design technics.

Functions are two types:


1. Library functions: these are pre-defined functions and available in library of C. for example
scanf(), printf(),clrscr() etc.
2. User defined function: these functions are written by the programmer according to their
need.

Need for user defined function:


1. It facilitate top-down modular programming as shown in fig:

Main program

Function
1
2. The length of a source program can be reduced by using functions at appropriate places.
3. It is easy to locate and isolate a fault function for further investigation.
4. A function may be used by many other programs.

Elements of user –defined function: in order to make use of a user defined function, we
need to establish three elements that are related to function.
1. Function definition
2. Function call
3. Function declaration

➢ The function definition is an independent program module that is specially written to


implement the requirements of the function.
➢ In order to use this function we need to invoke it at a required place in the program.
This is known as the function call
➢ A function that calls the function is referred as the calling function.

81
➢ The calling program should declare. (Any function that is used to be later in the
program.)

1. Definition of the function:” A function is a self-contained block of statements, which


are kept together to perform a specific task in related manner”. A function shall include
the following statement:
Function type
Function header Function name
List of parameters

Local variable declaration


Function body Function statements
A return statement

A general syntax of function is:


Function-type function-name (parameter- list)
{
Local variable declaration
Function statement
Return statement
}

Function header: the function header consists of three parts: function name, function type, and
parameter list.

Function name and function type: the function type specifies the type of value (like float,int, or
double etc.) that the function is expected to return to the calling function. If return type is no
explicitly specified, c assumes it integer. If function does not return anything its type is void.and
The function name is any valid C identifier.

Parameter list: the parameter list declares the variables that will receive the data sent by the
calling function.

Function body: the function body contains three parts for performing the required task:
1. Local variable declarations that specifies the variable needed by function.
2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.
For examples:
float add(int a, int b)
{
return ( a + b);
}

82
2. Function call: A function can be called by simply using the function name followed by a
list of actual parameters. For e.g.

void main()
{ Here a and b are actual parameters
inty,a,b;
printf(“enter the value”);
scanf(“%d%d”,&a,&b);
y=add(a,b); function call
printf(“result=%d”,y);
getch(); here x and y are formal parameters
}

int add(int x , int y)


{
return(x+y);
}

3. Function declaration (function prototype): like variables, all the functions in a C


program must be declared, before they are invoked. A function declaration consist of four
parts:
• Function type
• Function name
• List of parameters
• Terminating semicolon
They are all coded in the following form-

function-type function-name (parameter list);


Note:
1. The parameter list must be separated by commas.
2. The parameter names do not need to be the same in the prototype declaration and the
function definition.
3. The type must match the type of parameters in the function definition, in number and
order.
4. If the function has no formal parameters, the list is written as (void).
5. The return type must be void if no value is returned.

Category of functions: A function, depending on whether arguments are present or not


and whether a value is returned or not, may belong to one of the following categories:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
83
3. Functions with arguments and one return values.
4. Functions with no arguments and return values.
5. Functions that return multiple values.

1. Functions with no arguments and no return value.-A function without any arguments means
you cannot pass data (values like int, char etc) to the called function. Similarly, function with no
return type does not pass back data to the calling function.

Example:

void main()
{
clrscr();
printf("Welcome to function in C");
printline();
printf("Function easy to learn.");
printline();
getch();
}
void printline()
{
int i;
printf("\n");
for(i=0;i<30;i++)
{
printf("-");
}
printf("\n");
}

84
2. Functions with arguments and no return value-This type of function can accept data from
calling function. In other words, you send data to the called function from calling function but
you cannot send result data back to the calling function.
Example:

void main()
{
clrscr();
add(30,15);
add(63,49);
add(952,321);
getch();
}
void add(int x, int y)
{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}

3. Functions with arguments and one return value-This type of function can send arguments
(data) from the calling function to the called function and wait for the result to be returned
back from the called function back to the calling function.

Example:
void main()
{
int z;
clrscr();

z = add(952,321);

85
printf("Result %d.\n\n",add(30,55));
printf("Result %d.\n\n",z);
getch();
}
int add(int x, int y)
{
int result;
result = x+y;
return(result);
}

4.Functions with no arguments but returns value-We may need a function which does not take
any argument but only returns values to the calling function then this type of function is useful.

Example:
void main()
{
int z;
clrscr();
z = send();
printf("\nYou entered : %d.", z);
getch();
}
int send()
{
int no1;
printf("Enter a no : ");
scanf("%d",&no1);
return(no1);
}

86
Parameter passing techniques:-
There are two techniques to pass the parameter as arguments:-
a. Call by value
b. Call by reference

Call by value: when the values of arguments are passed from the calling functions to the
called function, the values are copied into the called function. If any changes are made to the
values in the called function, there is no change in the original values within the calling
function. For example-

void swap(int a, int b);


void main()
{
int x,y;
printf(“enter the value of x and y”);
scanf(“%d%d”,&x,&y);
printf(“before swapping=a=%d\nb=%d”,x,y);
swap(x,y);
printf(“after swapping=a=%d\nb=%d”,x,y);
getch();
}

void swap(int x, int y)


{
int temp;
temp = x;
x = y;
y = temp;
}

87
➢ Write a program to find the sum of three number using functions.
int sum(int a,int b,int c);
void main()
{
int x,y,z,sum1;
printf(“enter the value of x and y”);
scanf(“%d%d%d”,&x,&y,&z);
sum1=sum(x,y,z);
printf(“sum=%d”,sum1);
getch();
}

int sum(int a,int b,int c)


{
return(a+b+c);
}

Recursion: When a function calls itself then it is called as 'recursive function’ or recursion.

Example:
recursion()
{
printf("Recursion !");
recursion();
}

Features:

• There should be at least one if statement used to terminate recursion.


• It does not contain any looping statements.

Advantages:

• It is easy to use.
• It represents compact programming structures.

Disadvantages:

• It is slower than that of looping statements because each time function is called

➢ Write a program to find Factorial of a number using recursion.

88
long factorial(int );
void main()
{
long int num ,f;
printf("Enter a number to find factorial\n");
scanf("%d", &num);
f = factorial (num);
printf("factorial = %ld\n", f);
}
getch();
}

long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

➢ write a program for Fibonacci series using recursion.

int Fibonacci(int);
void main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
getch();
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else

89
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

➢ Write a program to find greatest common divisor using function.


int gcd(int p, int q);
void main()
{
int x,y,z;
printf("Please Enter two integers:\n");
scanf ("%d%d",&x,&y);
z=gcd(x,y);
printf("Greatest Common Divisor of %d and %d is:%d\n",x,y,z);
getch();
}

int gcd(int p, int q)


{
Int r, greater,smaller;
if (p>q)
greater=p,smaller=q;
else
greater=q,smaller=p;
if(smaller==0)
return greater;
else
r=gcd(smaller,greater);
return r;
}

➢ Write a program to find the sum of n integers (1,2,……n) using recursion.

int sum(int n);


void main()
{
int n;
printf(“enter the terms”);
scanf(“%d”,&n);
printf(“sum of integers is =%d”,sum(n));
getch();
}
90
int sum(int n)
{
if(n==0)
return(0);
else
return( n+sum(n-1));
}

UNIT-4
Array and structure

Array –An array is a fixed – size sequenced collection of elements of the same data type. The
elements in an array are called as 'elements of an array’. These elements are accessed by
numbers called as 'subscripts or index numbers.' Arrays may be of any variable type.

Based on the dimensions for data storing, arrays are following types-
➢ One dimensional array

91
➢ Two dimensional arrays
➢ Multi-dimensional array

1. One dimensional array- A list of items can be given in one variable name using
only one subscripts and such a variable is called a single – subscripted variable or one-
dimensional array.

➢ Declaration of One dimensional array- the general form of declaration is:

Syntax: Data-type array-name [size] ;


• Size should be either numeric constants or symbolic constants.

For example- subscript


int a[3];
char ch[20];
float stax[3];

• Subscripts of an array can be integer constants.

➢ Initialization of One dimensional array:


1. At compile time initialization:

data-type array-name [size] ={ list of value};

For e.g. int a[3] = {2, 3, 5};


char ch[20] = "technoexam" ;
float stax[3] = {5003.23, 1940.32, 123.20} ;

2. At run-time initialization: this approach is usually applied for initializing large array.
For e.g. for(i=0;i<100;i++)
{
a[i]=2;
}
➢ Write a C program to use one dimensional array to read and compute the sum of their
squares.
void main()
{
int i, a[100],b[100],sum=0,n;
clrscr();
printf("\n enter the number of element \n ");
scanf(“%d”,&n);
92
printf("\n enter the numbers :\n ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]); // read array
}
for(i=0; i<n; i++)
{
b[i]=a[i]*a[i];
}
for(i=0; i<n; i++)
{
sum= sum + b[i];
}
printf(“sum of square=%d”,sum);
getch();
}

➢ Write a C program to find the smallest and largest element in an array.


void main()
{
inti,largest,smallest,a[100],n;
clrscr();
printf("enter the number of element in array");
scanf("%d",&n);
print("\nenter the element in array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
largest=a[0];
smallest=a[0];
for(i=1;i<n;i++)
{
if(largest<a[i])
largest=a[i];
if(smallest>a[i])
smallest=a[i];
}
printf("smallest=%d \n largest=%d",smallest,largest);
getch();
}

93
➢ Write a program in C to find the sum of odd and even number in an array.
void main()
{
inti,sumeven=0,sumodd=0,a[100],n;
clrscr();
printf("enter the number of element in array");
scanf("%d",&n);
printf("enter the element in array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
sumeven=sumeven+a[i];
else
sumodd=sumodd+a[i];
}
printf("som of even numbers=%d \n sum of odd numbers=%d",sumeven ,
sumodd);
getch();
}

➢ Write a program to copy one array into another array in reverse order.
void main()
{
int a[100],b[100],i,n;
printf("enter the no. of elements");
scanf("%d",&n);
printf("enter the elements in a");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
b[n-1-i]=a[i];
}

94
printf("array b is");
printf("\n");
for(i=0;i<n;i++)
{
printf("\t%d",b[i]);
}
getch();
}
➢ Write a program which read two array elements and find the sum of corresponding
element.
void main()
{
int i, a[100],b[100],sum[100],n;
clrscr();
printf("\n enter the number of element \n ");
scanf(“%d”,&n);
printf("\n enter the numbers in array a :\n ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("\n enter the numbers in array b :\n ");
for(i=0; i<n; i++)
{
scanf("%d", &b[i]);
}
for(i=0; i<n; i++)
{
sum[i]=a[i] + b[i];
printf(“%d\t”,sum[i]);
}
getch();
}
➢ Write a program that read an array and print them in reverse order.
void main()
{
int i, a[100],n;
clrscr();
printf("\n enter the number of element \n ");
scanf(“%d”,&n);

95
printf("\n enter the numbers :\n ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
for(i=n-1; i>=0; i--)
{
printf("%d\t", a[i]);
}
getch();
}

➢ Write a program to enter the number of n digits and print them in word.
void main()
{
long int i, a[100],n,num;
clrscr();
printf("\n enter the length of digits \n ");
scanf(“%ld”,&n);
printf("\n enter the numbers :\n ");
scanf(“%ld”,&num);
for(i=0; i<n; i++)
{
a[i]-num%10;
num=num/10;
}
for(i=n-1; i>=0; i--)
{
switch(a[i])
{
case 1: printf(“one”);
break;
case 2: printf(“two”);
break;
case 3: printf(“three”);
break;
case 4: printf(“four”);
break;
case 5: printf(“five”);
break;
case 6: printf(“six”);
break;

96
case 7: printf(“seven”);
break;
case 8: printf(“eight”);
break;
case 9: printf(“nine”);
break;
case 0: printf(“zero”);
break;
}
}
getch();
}

➢ Write a program that read elements of an integer array and count even and odd
numbers in it.
void main()
{
inti,even=0,odd=0,a[100],n;
clrscr();
printf("enter the number of element in array");
scanf("%d",&n);
printf("enter the element in array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]%2==0)
even++;
else
odd++;
}
printf("total even numbers=%d \n total odd numbers=%d",even , odd);
getch();
}

➢ Write a program to find the largest and second largest number in array.
void main()
{
int i ,j,a[100],n,x;

97
clrscr();
printf("enter the number of element in array");
scanf("%d",&n);
printf("\nenter the element in array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(a[i]<a[j])
{
x=a[i];
a[i]=a[j];
a[j]=x;
}
}
}
printf(“largest element is:%d\n second largest element is :%d”,a[0],a[1]);
getch();
}
Two dimensional array-The array which is used to represent and store data in a tabular
form is called as 'two dimensional array.' Such type of array specially used to represent data in a
matrix form.It is declared as :

Data-type array-name [row-size][column -size] ;


Example:
int a[3][3];

Operations on two dimensional array are-


I. Reading and printing elements of matrix
II. Adding and subtracting the corresponding elements of two matrices.
III. Multiplication of two matrices
IV. Symmetry and transpose

➢ Write a program to read a matrix and print them in matrix form.


void main()
{

98
int a[10][10], i, j,row col;
clrscr();
printf(“enter the order of matrix\n”);
scanf(“%d%d”,&row,&col);
printf("\n\t Enter matrix :\n ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
printf("\n\t Matrix is : \n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("\t %d",a[i][j]); //print 3*3 array
}
printf("\n");
}
getch();
}

➢ Write a C program for Addition of two matrices.


void main()
{
int a[10][10],b[10][10],c[10][10],i,j,row1,col1,row2,col2;
clrscr();
printf(“enter the order of matrix a\n”);
scanf(“%d%d”,&row1,&col1);
printf(“\n enter the order of matrix b\n”);
scanf(“%d%d”,&row2,&col2);
if( (row1==row2) &&(col1==col2))
{
printf("enter the values in matrix a");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter values in matrix b");

99
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("addition of two matrix is \n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf("\t%d",c[i][j]) ;
}
printf("\n");
}
}
else
printf(“ addition is not possible ”);
getch();
}

➢ Write a C program for Subtraction of two matrices


void main()
{
int a[10][10],b[10][10],c[10][10],i,j,row1,col1,row2,col2;
clrscr();
printf(“enter the order of matrix a\n”);
scanf(“%d%d”,&row1,&col1);
printf(“\n enter the order of matrix b\n”);
scanf(“%d%d”,&row2,&col2);
if( (row1==row2) &&(col1==col2))
{
printf("enter the values in matrix a");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)

100
{
scanf("%d",&a[i][j]);
}
}
printf("enter values in matrix b");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("subtraction of two matrix is \n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
c[i][j]=a[i][j] - b[i][j];
}
}
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf("\t%d",c[i][j]) ;
}
printf("\n");
}
}
else
printf(“ subtraction is not possible ”);
getch();
}

➢ Write a C program for multiplication of two matrices.


void main()
{
int a[10][10],i,j,k, b[10][10], p[10][10],row1,col1,row2,col2;
clrscr();
printf("Enter number of rows and columns of first matrix (less than 10)\n");
scanf("%d%d",&row1,&col1);
printf("\nEnter number of rows and columns of second matrix (less than 10)\n");
scanf("%d%d",&row2,&col2);

101
if(col1==row2)
{
printf("Enter elements of First matrix \n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter elements of second matrix \n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
p[i][j]=0;
for(k=0;k<col1;k++)
{
p[i][j]= p[i][j] + a[i][k] * b[k][j];
}
}
}
printf("Multiplication of the Matrices:\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
Printf(“%d\t ”,p[i][j]);
}
Printf(“\n”);
}

102
}
else
printf("Matrix multiplication cannot be done");
getch();
}

➢ Write a program to find the sum of diagonal elements in the given square matrix.
void main()
{
int a[10][10], i, j,row , col,sum=0;
clrscr();
printf(“enter the order of matrix\n”);
scanf(“%d%d”,&row,&col);
printf("\n\t enter matrix :\n ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
if(i==j)
sum=sum + a[i][j];
}
}
printf(“sum of diagonal elements is : %d”, sum);
getch();
}

➢ Write a program to find the transpose of a given matrix.


void main()
{
int a[10][10], i , j , row , col ,b[10][10];
clrscr();
printf(“enter the order of matrix\n”);
scanf(“%d%d”,&row,&col);
printf("\n\t enter matrix :\n ");
for(i=0; i<row; i++)

103
{
for(j=0; j<col; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
for(i=0; i<col; i++)
{
for(j=0; j<row; j++)
{
b[i][j]=a[j][i];
}
}
printf(“\n transpose matrix is:\n”);
for(i=0; i<col; i++)
{
for(j=0; j<row; j++)
{
printf(“%d\t ”,b[i][j]);
}
printf(“\n”);
}
getch();
}

➢ Write a program to find the given square matrix is symmetry or not.


void main()
{
int a[10][10], i , j,row , col , flag=0,b[10][10];
clrscr();
printf(“enter the order of matrix\n”);
scanf(“%d%d”,&row,&col);
printf("\n\t enter matrix :\n ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&a[i][j]); //read 3*3 array
}
}
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
104
b[i][j]=a[j][i];
}
}
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
if( a[i][j] != b[i][j] )
flag++;
}
}
if(flag==0)
printf(“ matrix is symmetry”);
else
printf(“ matrix is not symmetry”);
getch();
}

Structure-structure is a user defined data type .it is used to pack the data of different types in
a group to make logically related group. General format for defining the structure is:

Structstructure name
{
Data-type of member1 member1-name ;

Data-type of member2 member2-name ;


.
.
.
Data-type of member-n member-n-name ;
};

Struct is a keyword .declares a structure to hold the details of member data.


Declaring a structure variable: after define a structure format we can declare variable of
that type .it is declared as:

Struct structure-name variabl1, variable2 ……;

The complete declaration of structure looks like the following example:

struct book
{
char title[20];

105
int page;
float price;
};
struct book book1,book2 ;

Or//

struct book
{
char title[20];
int page;
float price;
} book1 ,book2;

Accessing structure members:we can access the structure member using a dot operator
(.), between variable and member of structure.

For example – Book1.price , Book1.page

➢ Define a structure named employee. The structure should have the following
element in it.
Employee Id(int type) , Name ( characterarray) , Age ( int ) , Salary ( float )

Program:
Struct employee
{
int id;
char name[20];
int age;
float salary;
} emp1;

void main()
{
printf(“enter the id \n”);
scanf(“%d”,&emp1.id);
printf(“enter the name \n”);
scanf(“%s”,emp1.name);
printf(“enter the age \n”);
scanf(“%d”,&emp1.age);
printf(“enter the salary \n”);
scanf(“%f”,&emp1.salary);
106
getch();
}

Array of structures: we may declare an array of structure as follows:

Struct structure-name array-name[size];

For example:
Struct employee people[50];

➢ Declare a structure which contains the following members (roll no, name, father’s
name, age, marks) and write a program in C to list all students name which contain
more than 75 marks.

struct student
{
int rollno , age;
char name[50], fname[50];
float marks;
} s[100];

void main()
{
int i , n;
printf(“enter the no of students :”);
scanf(“%d”,&n);
printf("enter the records of studentrollno , age ,name ,fname ,marks :");
for(i=0 ; i<n ; i++)
{
scanf("%d%d%s%s%f",&s[i].rollno,&s[i].age,s[i].name,s[i].fname,&s[i].marks);
}
printf(“record of the student are :”);
for(i=0;i<n;i++)
{
printf("%d%d%s%s%f",&s[i].rollno,&s[i].age,s[i].name,s[i].fname,&s[i].marks);
}
printf(“name of those student who scored more than 75 marks:”);
for(i=0;i<n;i++)
{
if(s[i].marks>75)
printf("%s",s[i].name);
}
getch();
107
}

Nesting of structures: Nested structure means “structure within a structure”. Nesting is done
in two ways.

1. Nested substructure

struct employee
{
char name[20];
int basic-pay;

struct day-join
{
int day;
int month;
int year;
} doj;

} emp;

2. Nested separate substructure

struct day-join
{
int day;
int month;
int year;
};

struct employee
{
char name [20];
int basic-pay;
struct day-join doj;
} emp;

Accessing nested structure members-since the nested structure is treated as the


member variable of another structure. so it is also access with the help of dot operator.For
example emp.doj.day;

108
➢ Program:
structstud_res
{
int rno;
char std[10];
struct stud_marks
{
char subj_nm[30];
int subj_mark;
} marks;
} result;

void main()
{
clrscr();
printf("\n\t Enter Roll Number : ");
scanf("%d",&result.rno);
printf("\n\t Enter Standard : ");
scanf("%s",result.std);
printf("\n\t Enter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",result.rno);
printf("\n\n\t Standard : %s",result.std);
printf("\nSubject Code : %s",result.marks.subj_nm);
printf("\n\n\t Marks : %d",result.marks.subj_mark);
getch();
}

Union- union is concepts borrowed from structures and therefore follow the same syntax as
structure. There is a major difference in terms of storage of items.
➢ In structure, each member has its own storage location, whereas all member of a union
use the same location.
➢ This implies that although a union may contain many members of different types, it can
handle only one member at a time.
For e.g.
union item
{
int m;
float x;
char s;
} a;

109
➢ The compiler allocates a piece of storage that is large enough to hold the largest
variable type value in the union.

Storage of 4 bytes

1000 1002 1004 1006 1008

x
( sharing of a storage location by union member)

POINTER – pointer is a variable that can hold the address of other variables, structures,
functions and array that are used in the program.

Operators used with pointers-

&- tells the address of the associated variable. For e.g. (&variable)
*tells the value of variable to which the associated variable is pointing ( *ptr)
Declaration of pointer variables-it is declared as –

Data-type * pointer – variable;


For e.g. int *p ; Char *s;
Pointer declaration style:
1. int* p;
2. int *p;
3. int * p;

Initializing of pointer variable- the process of assigning the address of a variable to a pointer
variable is known as initialization.
For e.g.
int q;
int *p;
p=&q;

or/ int q;
int *p=&q;

110
Arithmetic operations on pointer: the following arithmetic operations are performed on
pointer variable.

➢ Addition of a number to a pointer variable-


For e.g.
int x=10;
int*p;
p=&x;
*p=*p+1; [increase value at address by one]
p=p+1; [increase address by one]

---------X-- -------------

6401 6402 6403 6404 6405

P 6401 p+1

i.e. The increment in the address of variable x leads to increment of two members because
increment in address means pointing to next memory variable of its type.

➢ Subtracting of a number from a pointer variable-


For e.g.
int x=10;
int*p;
p=&x;
*p= *p-1; [decrease value at address by one]
p= p-1; [decrease address by one]

------------x --------------------

6401 6402 6403 6404 6405

P-1
6403 P

➢ Subtracting of a pointer variable from another pointer variable: it is possible only and
only if the two pointers pain to the elements of same array.
For e.g.
int a[]={10,8,9,7,6,4};
int *p ,*q ,d;
p=&a[2];
q=&a[0];

111
d=p-q;

10 8 9 7 6 4

6000 6002 6004 6006 6008 6010 6012

6000 6004

q p d=p-q=4

The following operation should be avoided-


• Addition of two pointers
• Subtraction of two pointers
• Division of two pointers

Call by reference method-when the addresses of actual arguments are given to a function,
it is known as “call by reference “method. The addresses of actual arguments are copied into
the formal arguments. So that formal argument should be pointer being able to store the
address .so it is possible to make changes in the value of actual arguments within the body of
called function by means of value at address operator.

Advantage-
• Using call by reference method we can make a function to return more then on value.

➢ Write a program to swap two integer variable values through call by reference.
void swap( int *p,int *q);
void main()
{
int x , y;
printf("enter the two number\n”);
scanf(“%d%d”,&x,&y);
printf(“\nbefore swapping\n x=%d\ny=%d”,x,y);
swap(&x ,&y);
printf(“\nafter swapping\n x=%d\ny=%d”,x,y);
getch();
}

void swap( int *p,int *q)


{

112
int t;
t=*p;
*p=*q;
*q=t;
}

➢ Write a program to calculate area and circumference by call by reference.


void calculate( int r, float *cir , float *area);
void main()
{
int r;
float circum ,area;
printf(“enter the value of radius”);
scanf(“%d”,&r);
calculate( r ,&circum ,&area);
printf(“\n circumference =%f\n area=%f”,circum,area);
getch();
}
void calculate( int r, float *cir , float *area)
{
*cir=2*3.14*r;
*area=3.14*r*r;
}

➢ Write a program to calculate area and perimeter of rectangle using call by


reference.

void calculate( int l, int b, float *peri , float *area);


void main()
{
int l ,b ;
float perimeter ,area;
printf(“enter the value of length and breadth ”);
scanf(“%d%d”,&l,&b);
calculate(l,b ,&perimeter ,&area);
printf(“\n perimeter =%f\n area=%f”, perimeter ,area);
getch();
}
void calculate( intl,int b, float *peri , float *area)
{

113
*peri=2*(l+b);
*area= l * b;
}

Pointer and array- when an array is declared, the compiler allocates a base address and
sufficient amount of storage to contain all the elements of the array in continuous location.
Base address is the location of the first element of the array.
For e.g.
int x[ ]={ 9,8,5,4,3,2};

9 8 5 4 3 2

1000 1002 1004 1006 1008 1010 1012

Base address

Now if p is a pointer variable we have,


P=&x[0]; /* value at p is 1000
Then ,
P+1=&x[1] =1002
P+2=&x[2] =1004
P+3=&x[3] =1008
P+4=&x[4] =1010
P+5=&x[5] =1012

➢ Write a program to display an array element using pointers.

void main()
{
int i, a[100],n,*p;
clrscr();
printf("\n enter the number of element \n ");
scanf(“%d”,&n);
printf("\n enter the numbers :\n ");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
p=&a[0];
for(i=0; i<n; i++)

114
{
printf("%d\t", *p);
p++;
}
getch();
}

Two dimensional array and pointer- two dimensional array is known as ‘array of array’.so the
rows of a two dimensional array treated as one dimensional array.
Pointer representation of array is :
A[i] is written as *(a + i)
A[i][j] is written as *( *(a+i) +j) or *( a[i] + j)

Dynamic memory allocations-the process of allocating memory at run time is known as


dynamic memory allocation.
There are two types of memory allocation possible in c:
➢ Compile time or static allocation
➢ Run time or dynamic allocation

Local variable Stack


Heap
Free memory Permanent storage

Global variables

C program instructions

(Storage of c program)

The free memory is available for dynamic allocation during execution of the program.
C provides following memory allocation function-
➢ Malloc()
➢ Calloc()
➢ Free()
➢ Realloc()

All these functions are declared in the following header files-


• Stdlib.h
• Alloc.h

115
1. Malloc function (allocating a block of memory ) -the malloc function reserves
a block of memory of specified size and returns a pointer of type void. This means that
we can assign it to any type of pointer. It returns the address of first byte of allocated
space.it takes the following form-

Ptr=(cast-type*) malloc( no.of element * size of element);

For e.g.
X = ( int*) malloc( 100 *sizeof(int));
Or
Cptr = (char*) malloc(10*sizeof(char));

Address
of first
byte Space for 10 bytes

Cptr

2. Calloc(allocating multiple blocks of memory)-calloc is another memory


allocation function it allocates multiple blocks of storage. each of the same size. it
allocates space for an array of elements & structures. initialize them to zero and return
a pointer to the memory. its general syntax is:

ptr = (cast-type * ) calloc ( n,element-size); where n is number of blocks.

for e.g. int *a;


a=(int *)calloc(10,2);

or//
struct student
{
char name [25];
float age;
};
typdefstruct student record;
record *str;

116
int n=30;
str=(record*) calloc( n . sizeof (record) );

3. Free (releasing the used space)-the free function is used to de-allocate the
previously allocated memory using malloc() or calloc()function. The syntax is –

free(ptr);

4. realloc ( altering the size of a bloc) – the realloc function is used to increase or
decrease the size of the block of heap memory to the size specified by the new size
while preserving the address and contents of the beginning of the block. For e.g.

ptr=realloc(ptr,newsize);

➢ Write a program to enter the element and print them in reverse order using dynamic
memory allocation.
void main()
{
inti,n,*ptr;
clrscr();
printf("How many element do you wish to enter in array? :");
scanf("%d",&n);
ptr=(int *)malloc(n*sizeof(int));
if(ptr==0)
printf("no space");
else
{
printf("\nEnter the Elements:\n");
for(i=0;i<n;i++)
{
scanf("%d\n",(ptr+i));
}
for(i=n-1;i>=0;i--)
{
printf("%d",*(ptr+i));
}

117
}
getch();
}

Stack-a stack is a non-primitive linear data structure.it is an order list in which addition of new
item and deletion of already existing data item is done from only one end ,known as top of
stack.as all deletion and insertion in a stack is done from top of the stack, the last added
element will be the first to be removed from the stack .that is the reason that stack is also
called LIFO( last in first out).

PUSH POP

(STACK)
Operation on stack-
1. Push operation
2. Pop operation

PUSH- the process of adding a new element to the top of stack is called push operation. After
every push operation the top is incremented by one.
void push()
{
int item;
if(top==maxsize-1)
{
printf(\n the stack is full”);
getch();
exit(0);
}
else
{
printf(“enter the element \n”);
scanf(“%d”,&item);
top=top+1;

118
stack[top]=item;
}
}

POP- the process of deleting an element from the top of stack is called pop operation. After
every pop operation the top is decremented by one.

int pop()
{
int item;
if( top == -1)
{
printf(\n the stack is empty”);
getch();
exit(0);
}
else
{
item=stack[top];
top=top-1;
}
return(item);
}
Uses of stack:
• Expression evaluation
• Backtracking (game playing, finding paths, exhaustive searching)
• Memory management, run-time environment for nested language features.

Linked list-A completely different way to represent a list, which make each item in the list is a
part of a structure that also contain a link to the structure containing next item.as shown in fig.

Structure (node1) Structure (node2) Structure (node3)

(A linked list)

Each structure of list is called a node and consists of two fields, one containing item, and other
containing the address of the next item, in the list. A linked list is therefore a collection of

119
structures ordered not by their physical placement in memory but by logical links that are
stored as part of the data in the structure itself. such a structure is represented as follows-

struct node
{
int item;
struct node *next;
};

Advantages-
➢ Linked list are dynamic data structure
➢ Efficient memory utilization
➢ Insertion and deletion are easier and efficient

Disadvantages
➢ More memory
➢ Access to any arbitrary data item is little bit cumbersome and also time – consuming.
Types of linked lists----

A B C

( Linear linked list)

A B C

(Circular linked list)

0 A B C 0

(Two way linked list)

A A A

120
(Two way circular linked list)

Operation on linked list-

➢ Creating a list
➢ Traversing a list
➢ Counting the items in the list
➢ Printing the list
➢ Inserting an item
➢ Deleting an item

UNIT-5
Pointer, searching and File handling

121
Searching: Searching is the process of finding an element within the list of elements stored in
any order or randomly. Searching is divided into two categories:
1. Linear search (Sequential search)
2. Binary search

a) Linear Searching: In linear search we compare the given element with the elements of an
array one by one sequentially and see whether it is desired element or not. A Search will be
unsuccessful if all the elements are accessed and the desired element is not found.

Efficiency of Sequential search: The time taken or the number of comparison made to search
an element from a list of elements determines the efficiency of the technique. If the desired
element is present in the first then one- one comparison is made. If it is the last element then
n-comparison has to be made. If the element is present somewhere in the search table on an
average then the number of comparison will be (n+1)/2.

Program:
void main()
{
int a[100],n,i,item,loc=-1;
clrscr();
printf("enter the number of elements");
scanf("%d",&n);
printf("enter the numbers:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the item to be searched");
scanf("%d",&item);
for(i=0;i<n;i++)
{
if(item==a[i])
{
loc=i;
break;
}
}
if(loc>=0)
printf("element is found in position%d %d",i+1,item);
else
printf("element is not found");

122
getch();
}

b) Binary Search: To do the binary search first we had to sort the array elements. The logic
behind this technique is given below:
1) First find the middle element of the array.
2) Compare the mid element with an item.
3) There are three cases:
a) if it is a desired element then search is successful.
b) if it is less than desired element then search only the first half of the array.
c) if it is greater than the desired element then search in the second half of the array.

Program:
void main()
{
int a[100],n, i ,item, beg, end, mid;
clrscr();
printf("enter the number of elements");
scanf("%d",&n);
printf("enter the elements in sorted order");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the item to be searched");
scanf("%d",&item);

beg=0;
end=n-1;
mid=(beg+end)/2;
while(beg<=end&&item!=a[mid])
{
if(item>a[mid])
beg=mid+1;
else
end=mid-1;
mid=(beg+end)/2;
}
if(a[mid]==item)
printf(“item is present in the list”);

123
else
printf(“item does not exist in the list”);
getch();
}

Sorting: Sorting refers to the operation of arranging data (character, number, string) in
ascending order or descending order.

a) Bubble sorting: In bubble sort each element is compared with its adjacent element, if
the first element is larger than the second one then the position of the elements is
interchanged, otherwise it is not changed. In this way during the first pass the largest
element occupies the last position of the list. After that we repeat the above process for
n-1 elements.

Algorithm of bubble sort: This algorithm sorts the array A with N elements
Step1: Initialization
Set i=0
Step 2: Repeat step 3 to 5 until i<N
Step 3: Set j=0
Step 4: Repeat step 5 until j<N-i-1
Step 5: if (A[j]>A[j+1])
Set temp= A[j]
Set A[j]=A[j+1]
Set A[j+1]= temp
Step 6: End

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,j,temp;
clrscr();
printf("enter the number of elements");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

124
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("sorted elements are");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}

b) Selection Sort: The selection sort is based upon the extension of the minimum/maximum
technique. It means a pass through the array is made to locate the minimum value. Once this is
found, it is placed in the first position of the array (position 0).Another, the remaining element
are made to find the next smallest element, which is placed in the second position (position 1)
and so on. Once the next to last element is compared with the element, all the elements have
been sorted into ascending order.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],n,i,j,temp, loc, min;
clrscr();
printf("enter the number of elements");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;i++)
{

125
scanf("%d",&a[i]);
}
min=a[0];

for(i=0;i<=n-1;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<=n-1;j++)
{
if (a[j]<min)
{
min=a[j];
loc=j;
}
}
if(loc!=i)
{
temp =a[i];
a[i]=a[loc];
a[loc]=temp;
}
}

printf("sorted elements are");


for(i=0;i<n;i++)
{
printf("%d",a[i]);
}
getch();
}

String – a string is a sequence of characters that is treated as a single data item.


Strings are also defined as array of characters. Strings are always enclosed in double quotes as
"string constant".

Declaration:
The string can be declared as follow:

126
Syntax:
Char stringname[size];

Example: The following defines a string of 50 characters.

char name[50];

String Structure:
When compiler assigns string to character array then it automatically supplies null character
('\0') at the end of string. Thus, size of string = original length of string + 1.

char name[7];
name = "TECHNO”

Read Strings:
To read a string, we can use scanf() function with format specifier %s.
char name[50];
scanf("%s",name);

Write Strings:
To write a string, we can use printf() function with format specifier %s.
char name[50];
scanf("%s",name);
printf("%s",name);

String handling functions:


C library supports a large number of string handling functions that can be used to carry out
many of the string manipulations such as:
1. Length (number of characters in the string).
2. Concatenations (adding two are more strings)
3. Comparing two strings.
4. Copy (copies one string over another)

127
1) strlen() function:

This function counts and returns the number of characters in a string. The length does not include a null
character.

Syntax: n=strlen(string);

Where n is integer variable. This receives the value of length of the string.

Example
/*write a c program to find the length of the string using strlen() function*/
#include < stdio.h >
include < string.h >
void main()
{
char name[100];
int length;
printf("Enter the string");
gets(name);
length=strlen(name);
printf("\nNumber of characters in the string is=%d",length);
}

2) strcat() function:

When you combine two strings, you add the characters of one string to the end of other string.
This process is called concatenation. The strcat() function joins two strings together. It takes
the following form

Syntax: strcat(string1,string2)

string1 & string2 are character arrays. When the function strcat is executed string2 is appended
to string1. the string at string2 remains unchanged.

Example

strcpy(string1,"sri");
strcpy(string2,"Bhagavan");
Printf("%s",strcat(string1,string2);

From the above program segment the value of string1 becomes sribhagavan. The string at str2

128
remains unchanged as bhagawan.

3) strcmp function:

In c you cannot directly compare the value of two strings in a condition like if(string1==string2)
.for this purpose we use the strcmp() function, which returns a zero if two strings are equal, or
a non zero number if the strings are not the same. The syntax of strcmp() is given below:

Syntax: Strcmp(string1,string2)

String1, & string2 may be string variables or string constants some computers return a negative
if the string1 is alphabetically less than the second and a positive number if the string1 is
greater than the second.

Example:

strcmp("Newyork","Newyork") will return zero because two strings are equal.


strcmp("their","there") will return a 9 which is the numeric difference between ASCII 'i' and
ASCII 'r'.
strcmp("The", "the") will return 32 which is the numeric difference between ASCII "T" & ASCII
"t".

4) strcpy() function:

C does not allow to assign the characters to a string directly as in the statement name=”rob” .
Instead this, use the strcpy() function for copy of two string. The syntax of the function is
illustrated below.

Syntax: strcpy(string1,string2);

Strcpy function assigns the contents of string2 to string1. string2 may be a character array
variable or a string constant.

strcpy(Name,"Robert");

In the above example Robert is assigned to the string called name.

129
➢ Write a program that would sort a list of names in alphabetical order
(lexicographical order).
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[10][20],temp[20];
int i,j ,n;
printf("\nenter the no of strings\n");
scanf(“%d”,&n);
printf("enter the strings\n");
for(i=0;i<n;i++)
{
scanf("%s",str[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(strcmp(str[j],str[j+1])>0)
{
strcpy(temp,str[j]);
strcpy(str[j],str[j+1]);
strcpy(str[j+1],temp);
}
}
}
printf("\nsorted strings are\n");
for(i=0;i<n;i++)
printf("%s\n",str[i]);
getch();
}

➢ Write a program in C to find the number of VOWELS and CONSONANTS in


given string.

Program:

130
#include<stdio.h>
#include<conio.h>
void main()
{
char str[50];
int i,count,countc,whitespace;
count=0;countc=0;
printf("Enter a string : ");
gets(str);
count=0; i=0;
while(str[i]!='\0')
{
if(str[i]=='A' || str[i]=='a')
count++;
else if(str[i]=='E' || str[i]=='e')
count++;
else if(str[i]=='I' || str[i]=='i')
count++;
else if(str[i]=='o' || str[i]=='O')
count++;
else
countc++;
i++;
}
printf("The total nos of vowels %d consonants %d ",count, countc);
getch();
}

➢ Write a program in C to reverse the string using library function */

Program:
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();

131
printf("enter the string");
gets(str);
strrev(str);
puts(str);
getch();
}

➢ Writ a program to enter the name as “Radha Krishna sarvapalli” and print the name
as “R.K. sarvapalli “.
#include<string.h>
void main()
{
char f[20][10],m[20][10],s[20][10],n[20][20],temp[20];
int i,j;
clrscr();
printf("enter the name of customer");
for(i=0;i<2;i++)
{
scanf("%s%s%s",f[i],m[i],s[i]);
temp[0]=f[i][0];
temp[1]='\0';
strcpy(n[i],temp);
strcat(n[i],".");
temp[0]=m[i][0];
temp[1]='\0';
strcat(n[i],temp);
strcat(n[i],".");
strcat(n[i],s[i]);

}
for(i=0;i<2;i++)
{
printf("%s\n",n[i]);
}
getch();
}

File –A file is a place on the disk where a group of related data is stored.
The basic operation which can be performed on file is-
➢ Naming a file
➢ opening a file

132
➢ Reading data from file
➢ Writing data to file
➢ Closing a file

Types of file- depending upon the format in which data is stored, file are categories in two
ways:

Text files: As the name suggested, text files stored textual information likes alphabets,
number, special symbols etc. in actuality, the ASCII code of textual characters is stored in the
text files. But, since data is stored in a storage device in the binary format, the text file contents
are first converted in the binary format before actually being stored in the storage device.

Binary file: As the name suggested, a binary files stored the information in binary form. Thus,
the use of binary file eliminates the need of data conversion from text to binary format for
storage purpose. However the data stored in a binary file is not in human understandable form.
every executable file generated by C compiler is a binary file.

Defining and opening a file- if we want to store data in a file in the secondary memory, we
must specify certain things about the file, to the operating system. They include:
➢ Filename
➢ Data structure
➢ Purpose

Data structure of a file is defined as FILE in the library of standard I/O function definitions.
Therefore, all files should be declared as type FILE before they are used.

Opening a file:
The general format of the function used for opening a file is
FILE *fp;
fp = fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the data type FILE. The second
statement opens the file named filename and assigns an identifier to the FILE type pointer fp.
fopen() contain the file name and mode (the purpose of opening the file).mode can be one of
the following:

r is used to open the file for reading only.


w is used to open the file for writing only.
a is used to open the file for appending data to it.

When trying to open a file, one of the following things may happen:

133
➢ When the mode is writing, a file with specified name is created if the file does not exist.
The contents are deleted, if the file already exists.
➢ When the purpose is appending the file is opened with the current contents safe. A file
with specified name is created if the file does not exist.
➢ If the purpose is reading and if it exists, then the file is opened with the current contents
safe otherwise an error occurs.

Closing a File

A file must be closed as soon as all operations on it have been completed. This ensures that all
outstanding information associated with the file is flushed out from the buffers and all links to
the file are broken. it also prevents any accidental misuse of the file. This would close the file
associated with the file pointer. The input output library supports the function to close a file. it
takes the following form:

fclose (filepointer) ;

INPUT /OUTPUT OPERATIONS ON FILES:

The getc and putc function: these are the simplest input/output functions and analogous
to getchar and putchar functions and handle one character at a time. the general syntax is:

putc(c,fp1);
c = getc(fp2);
Where fp1 is a file type pointer and c is a character variable.

➢ Write a program in C to copy the content of one file into another file.

include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1,*f2;
char c;
printf(“Data is enter in the file named INPUT”);
f1=fopen("INPUT","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("INPUT","r");
f2=fopen("OUTPUT","w");

134
while((c=getc(f1))!=EOF)
putc(c,f2);
fclose(f1);
fclose(f2);
printf(“Data is copied into the file named OUTPUT”);
f2=fopen("OUTPUT","r");
while((c=getc(f2))!=EOF)
printf("%c",c);
fclose(f2);
getch();
}
The getw and putw function: these are the integer – oriented functions. They are
similar to getc and putc and they are used to read and write integer values.the
general syntax is:
putw(integer value,fp);
getw(fp);

➢ Create a file DATA and store list of 30 integers in it. Using the file DATA ,write a C
program which creates two more file name EVEN and ODD to store even integers and
odd integers.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp,*f1,*f2;
int n,i;
printf(“Contents of INPUT file”);
fp=fopen("INPUT","w");
printf("enter the number");
for(i=0;i<30;i++)
{
scanf("%d",&n);
if(n==-1)
break;
else
putw(n,fp);
}

135
fclose(fp);
fp=fopen("INPUT","r");
f1=fopen("EVEN","w");
f2=fopen("ODD","w");
while((n=getw(fp))!=EOF)
{
if(n%2==0)
putw(n,f1);
else
putw(n,f2);
}
fclose(fp);
fclose(f1);
fclose(f2);
f1=fopen("EVEN","r");
f2=fopen("ODD","r");
printf(“Contents of EVEN file”)
while((n=getw(f1))!=EOF)
printf("%d",n);
printf(“Contents of ODD file”);
while((n=getw(f2))!=EOF)
printf("%d",n);
fclose(f1);
fclose(f2);
getch();
}

The fprintf and fscanf function: these are used for handle a group of mixed data
simultaneously. The general syntax is :
fprintf( fp,”control string”,variable-list);
fscanf(fp,”control string”,variable-list);

Error handling during input output operation: it is possible that an error may occur
during input/output operations on a file. The common error is:
➢ Trying to read beyond the end – of – file marker.
➢ device overflow
➢ trying to use a file that has not been opened
➢ Trying to perform an operation on a file , when a file is opened for another type of
operation.

136
➢ opening a file with invalid filename
we have two status- inquiry library functions : feof and ferror that can help us detect
input / output errors in file.

1. feof- this is used to test for an end of file condition. it takes a FILE pointer as its
only argument and returns a nonzero integer value if all of the data from the
specified file has been read and otherwise return s zero .for e.g.
if(feof(fp))
printf(“end of data”);

2. ferror- it takes a file pointer as its argument and return a nonzero integer if an
error has been detected and otherwise return zero. for e.g.
if(ferror(fp)!=0)
printf(“an error has occured”);

Random Access to files: when we are interesting in accessing only a particular part of a file
not in reading the other parts .this can be achieved with the help of the functions fseek , ftell
,and rewind.

1. ftell- it takes file pointer and return a number of type long, that corresponds to the
current position. This function is useful in saving the current position of a file. it takes the
following form:
n = ftell(fp);

Where n would give the relative offset(in bytes) of the current position. This means that n
bytes have been already read(or write).

2. rewind- it takes a file pointer and resets the position to the start of file. For e.g.
rewind(fp);

3. fseek- it is used to move the file position to a desired location within the file.it takes the
form:
fseek( filepointer, offset,position);

the offset specifies the number of position to be moved from the location specified by
position. the position can take one of the following three values:

value meaning
0 beginning of the file
1 current position

137
2 end of file

Operation of fseek function:

Statement meaning

Fseek(fp ,0L,0); Go to the beginning


Fseek(fp ,0L,1); Stay at the current position
Fseek(fp ,0L,2); Go to the end of file
Fseek(fp ,m,0); Move to (m+1)th bytes in the file

Fseek(fp ,m,1); Go forward by m bytes

Fseek(fp ,-m,1); Go backward by m bytes from current position


Fseek(fp ,-m,2); Go backward by m bytes from the end

C preprocessor (directives): The preprocessor provides the ability for the inclusion of
header files, macro expansions, conditional compilation, and line control.

“The preprocessors as its name implies, is a separate program invoked by the compiler as
the first part of translation. All preprocessor commands begin with a symbol (#).”

Following section lists down all important preprocessor directives:

Directive Description
#define Substitutes a preprocessor macro
#include Inserts a particular header from another file
#undef Undefined a preprocessor macro
#ifdef Returns true if this macro is defined
#ifndef Returns true if this macro is not defined
#if Tests if a compile time condition is true
#else The alternative for #if
#elif #else an #if in one statement
#endif Ends preprocessor conditional
#error Prints error message on stderr
#pragma Issues special commands to the compiler, using a standardized method

138
These directives can be divided in three categories:
➢ Macro substitution
➢ File inclusion directives
➢ Complier control directives
1. Macro substitution: it is a process where an identifier in a program is replaced by a
predefined string composed of one or more tokens. The preprocessors accomplishes this
task under the direction of #define statement. its general form is:

#define identifier string

There are different common forms of macro substitution such as:


➢ Simple Macro substitution
➢ Argumented Macro substitution
➢ Nested Macro substitution

a) Simple Macro substitution – it is used to define constants. for e.g.


#define COUNT 100
#define PI 3.14

b) Argumented Macro substitution-This permits us to define more complex and more


useful form of replacements. it takes the form:
#define identifier( f1 ,f2 ,……..fn) string
For e. g.
#define CUBE (x*x*x)

c) Nested Macro substitution-we can use one macro in the definition of another macro.
for e.g.
#define SQUARE(x) (x*x)
#define SIXTH(x) (SQUARE(x) * SQUARE(x) * SQUARE(x) )

2. File Inclusion- an external file containing functions or macro definitions can be included
as a part of a [program so that need not rewrite those functions or macro definitions. this
is done as:
#include ”filename”
Or //
#include <filename>

When the file name is included within double quotation marks, the search for the file is
made first in the current directory and then in the standard directories. While in other
case ( <>) the file is searched only in standard directories.

139
3. Compiler control directives- These directives allow to include or discard part of the code
of a program if a certain condition is met.

#ifdef allows a section of a program to be compiled only if the macro that is specified as
the parameter has been defined, no matter which its value is. For example:

#ifdef TABLE_SIZE
int table[TABLE_SIZE];
#endif

In this case, the line of code int table[TABLE_SIZE]; is only compiled if TABLE_SIZE was
previously defined with #define, independently of its value. If it was not defined, that line will
not be included in the program compilation.

140

You might also like