Professional Documents
Culture Documents
(GCS101/201)
Notes
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
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
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
= (1 1 0 1. 1 0 1)2
↑ ↑ ↑ ↑ ↑ ↑ ↑
23 22 21 20 2-1 2-2 2-3
= (8+4+0+1).(0.50+0.25+0.125)
= (13 .875) 10
= (1 2 1. 1 2 )8
↑ ↑ ↑ ↑ ↑
82 81 80 8-1 8-2
= (64+16+8).(0.125+0.03125)
= (88 .15625) 10
= (1 A. B 1 )2
↑ ↑ ↑ ↑
16 16 16-1 16-2
1 0
= (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
(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).
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
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
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.
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 .
• 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.
➢ 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.
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.
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.
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:
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
15
Syntax: $rm filename
➢ 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.
16
cd user can move from one directory to another
Syntax: $pwd
vi edit a file
sort sort the given content either in ascending order or descending order
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
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
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.
Primary Memory
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.
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.
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
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.
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.
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.
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.
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:
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.
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.
27
20 00100000
30 00110000
The main advantage of machine language is that the processor can create it without any translation
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.
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.
3. Complex
3. Debugging is easier 3. Very complex
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
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.”
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
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
➢ 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 Three basic building blocks for writing structured programming are:
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:
{
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++;
}
➢ 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:
35
case enum register typedef
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.
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:
36
• Example:
1990, 194, -394
3. CHARACTER CONSTANT:
4. STRING CONSTANT:
• It is collection of characters enclosed in double quotes.
• It may contain letters, digits, special characters and blank space.
• Example:
Special Symbols: Some special symbols are also used to develop the program.
For eg- [ ] ( ) { } , : = ; ... #
\b Backspace
\t Horizontal Tab
\f Form feed
\r Carriage Return
37
\v Vertical Tab
\? Question Mark
\\ Backslash
\0 Null
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.
39
signed int -32768 to32767 2 %d
Standard output (stdout): Standard output is the stream where a program writes its output
data. The program requests data transfer with the write operation.
#include <stdio.h>
PC-based compilers also have an alternative library of console I/O functions. These functions
require the declaration:
#include <conio.h>
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();
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
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
> 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.
>= 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.
These operators are used when we want to test mor than on condition and make
decision. An example is : (a>b )&& (x==10)
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
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.
44
a++ and a++ both are have same meaning when they form statement independently. they
behave differently when they are used in expressions.
M=5
Y=M ++ (here the value of y is 5 and value of m is 6)
a=3, b=5, c;
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
45
| Binary OR Operator copies a (A | B) will give 61 which is
bit if it exists in eather 0011 1101
operand.
<< 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.
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.
. Member operator
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.
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:
(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.
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
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.
49
S Scope − Local to the block in which the
variable is defined.
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.
S scope − Global.
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
52
UNIT-3
Conditional program execution and function
➢ 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.
true
the different forms of if statement are:
➢ simple if statement
➢ if……else statement
➢ nested if …….else statement
➢ else if ladder
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();
}
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();
}
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();
}
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
➢ 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
}
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:
➢ 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:
#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();
}
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
The while statement (while loop) - the basic format of the while statement is:
While(test condition)
Loop control
{
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.
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();
}
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();
}
The do…while statement (do ..while loop) - the basic format of the while statement is:
do
Loop control
{
}while(test condition);
True false
Test
condition
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();
}
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-
Body of loop
69
Initialization of
control variable
False
Test
condition
True
Increment /
decrement
70
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();
}
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)
{
}
}
Initialization1
Test
Exit from outer loop false Increment1/decrement1
condition1
True
Initialization2
False
Test
condition2
True
Increment2/decrement2
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(); }
}
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();
}
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();
} }
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();
}
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();
}
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();
}
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
81
➢ The calling program should declare. (Any function that is used to be later in the
program.)
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
}
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-
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();
}
Recursion: When a function calls itself then it is called as 'recursive function’ or recursion.
Example:
recursion()
{
printf("Recursion !");
recursion();
}
Features:
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
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));
}
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) );
}
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.
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();
}
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 :
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();
}
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();
}
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();
}
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();
}
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();
}
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 ;
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.
➢ 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();
}
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;
struct day-join
{
int day;
int month;
int year;
};
struct employee
{
char name [20];
int basic-pay;
struct day-join doj;
} emp;
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
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.
&- 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 –
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.
---------X-- -------------
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.
------------x --------------------
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 6004
q p d=p-q=4
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();
}
112
int t;
t=*p;
*p=*q;
*q=t;
}
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
Base address
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)
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()
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-
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
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.
(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
A B C
0 A B C 0
A A A
120
(Two way circular 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;
}
}
Declaration:
The string can be declared as follow:
126
Syntax:
Char stringname[size];
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);
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:
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");
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();
}
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();
}
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:
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) ;
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
Statement meaning
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 (#).”
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:
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