Вы находитесь на странице: 1из 160

GE6151 COMPUTER PROGRAMMING

UNIT I INTRODUCTION
Generation and Classification of Computers- Basic Organization of a Computer Number
System Binary Decimal Conversion Problems. Need for logical analysis and thinking
Algorithm Pseudo code Flow Chart.
UNIT II C PROGRAMMING BASICS
Problem formulation Problem Solving - Introduction to C programming fundamentals
structure of a C program compilation and linking processes Constants, Variables Data
Types Expressions using operators in C Managing Input and Output operations Decision
Making and Branching Looping statements solving simple scientific and statistical problems.
UNIT III ARRAYS AND STRINGS
Arrays Initialization Declaration One dimensional and Two dimensional arrays. StringString operations String Arrays. Simple programs- sorting- searching matrix operations.
UNIT IV FUNCTIONS AND POINTERS
Function definition of function Declaration of function Pass by value Pass by reference
Recursion Pointers - Definition Initialization Pointers arithmetic Pointers and arraysExample Problems.
UNIT V STRUCTURES AND UNIONS
Introduction need for structure data type structure definition Structure declaration
Structure within a structure - Union - Programs using structures and Unions Storage classes,
Pre-processor directives.
TOTAL: 45 PERIODS
TEXTBOOKS:
1. Anita Goel and Ajay Mittal, Computer Fundamentals and Programming in C, Dorling
Kindersley
(India) Pvt. Ltd., Pearson Education in South Asia, 2011.
2. Pradip Dey, Manas Ghosh, Fundamentals of Computing and Programming in C, First
Edition,
Oxford University Press, 2009
3. Yashavant P. Kanetkar. Let Us C, BPB Publications, 2011.

UNIT I INTRODUCTION
Generation and Classification of Computers- Basic Organization of a Computer Number
System Binary Decimal Conversion Problems. Need for logical analysis and thinking
Algorithm Pseudo code Flow Chart.
Introduction
Definition of computer:
The computer is an electronic device which converts raw data into valid (or) meaningful
information.
Data :
* facts about anything.
*Data is the raw material of information processing.
Information:
The processed data is called the information and the data or information comes in various shapes
(or) size depending upon the application.
Generations of computers:
1. First Generation [1940-1956]: Vacuum Tubes
2. Second Generation [1956-1963]: Transistors
3. Third Generation [1964-1971]: Integrated Circuits
4. Fourth Generation [1971-Present]: Microprocessors
5. Fifth Generation [Present and Beyond]: Artificial Intelligence
First Generation - 1940-1956: Vacuum Tube
The first generation computers used vacuum tubes for circuitry and magnetic drums for
memory.
A magnetic drum, also referred to as drum, is a metal cylinder coated with magnetic ironoxide material on which data and programs can be stored.
Input was based on punched card and paper tape.

Output was in the form of printouts.


Language used by first generation computer was binary-coded language(0 & 1).
This computer can solve only one program at a time.
Eg:ENIAC,EDVAC,UNIVAC
Characteristics of first generation computer:
Computation time was in milliseconds.
Computers were very large and it occupies more space.
Thousands of vacuum tubes were used, they generate a large amount of heat, so air
conditioning was essential.
Machine languages are the only languages understood by computers.
Advantages:
Electronic components at that time
Advent of electronic digital computer
Fastest calculating device
Computation in milliseconds.
Disadvantages:
Too bulky in size.
Unreliable.
Thousands of vacuum tubes that were used emitted large amount of heat and burnt out
frequently
Air conditioning required.
Prone to frequent hardware failures.
Constant maintenance required.
No portable.

Second Generation - 1956-1963: Transistor


Used transistor[superior to vacuum tubes]
Transistor[made up of semiconductor like germanium and silicon]

It have 3 leads

1st lead-voltage

2nd lead-current

3rd lead-power amplification

Magnetic cores used as primary memory and magnetic disks used as secondary
memory.
They still relied on punched cards for input and printout for output
Progress from machine language to assembly language.
Assembly language used mnemonics [abbreviations] for instructions rather than numbers.
High-level programming languages were also being developed at this time, such as early
versions of COBOL and FORTRAN.
Characteristics of second generation computer:
Based on transistor technology
Comparatively smaller
Computational time reduced from milliseconds to microsecond
Assembly language was used to program, become more efficient.
Advantages:
Smaller in size as compared to first generation computers.
More reliable.
Less heat generated.
These computers were able to reduce computational times from milliseconds to
microseconds.

Less prone to hardware failures.


Better portability.
Disadvantages:
Air-conditioning required.
Frequent maintenance required.
Manual assembly of individual components into a functioning unit was required.
Commercial production was difficult and costly.
Third Generation - 1964-1971: Integrated Circuits

The development of the integrated circuit was shown start of third generation computers.
Also called as IC, an integrated circuit consists of a single chip [silicon] with transistor
and resistors.
It replaces several individual wired transistors.
It replaces the punched cards and printouts, it uses keyboard and monitors interfaced with
operating system.
It allows different applications run at one time.
First time computers are used by many peoples.
Eg: NCR 395and B6500
Characteristics of third generation computer:
Based on IC technology
Computational time reduced from microsecond to nano seconds
Consume less power and generate less heat
Hardware is rarely failed.

Commercial production became easier and cheaper.


Advantages:
Smaller in size.
More reliable than second-generation computers.
Less heat generated.
Computational times from microseconds to nanoseconds.
Maintenance cost is low
Easily portable.
Less power required.
Disadvantages:
Air-conditioning required in many cases.
Highly sophisticated technology required for the manufacture of IC chips.
Fourth Generation [1971-Present]: Microprocessors
Extension of third generation.
Depends on integrated circuit but uses micro processor.
Microprocessor is built onto a single piece of silicon known as chip. It is 0.5cm long and
not more than 0.05cm thick.
Fourth generation led to LSI [large scale integration] and VLSI [very large scale
integration].
LSI technology allowed thousands of transistors to be constructed on one small slice of
silicon.
VLSI->thousands of components on to single chip.
ULSI [ultra large scale integration] increased that number into millions.
Magnetic core memories were substituted by semi conductor memories
Hard disk becomes economical, smaller and large capacity.
Fourth generation computers also saw the development of GUI's, the mouse and
handheld devices.

Eg:Apple-II,CRAY-1
Characteristics of fourth generation computer:
Microprocessor-base system.
GUI and pointing device lead to learn computer quickly.
They could be linked together to form networks leads to resource sharing
Very small.
Cheapest among all generations
Advantages:
Smallest in size.
Very reliable.
Heat generated is negligible.
No air conditioning required in most cases.
Hardware failure is negligible easily portable because of their small size.
Cheapest among all generations.
Disadvantage:
Highly sophisticated technology required for the manufacture of LSI chips.
Fifth Generation [Present and Beyond]: Artificial Intelligence
The dream of creating a human like computers would be capable of reasoning and
reaching a decision through a series of what-if-then.
Computers should learn from its mistakes and posses the skill of experts.
Three characteristics of 5th generation computer are
1. Mega chips
2. Parallel processing
3. Artificial Intelligence [AI]

1. Mega chips:
Fifth generation computer use SLSI (super large scale integrated circuit).
SLSI is production of micro
Mega chips may enable the computer to approximate memory capacity of the human
mind.
2.Parallel processing:
Access and execute only one instruction at a time, this is called serial processing
Access several instructions at once and also works on them at same time.
3.Artificial Intelligence
Artificial Intelligence is the branch of computer science concerned with making
computers behave like humans.
Series of related technologies tries to reproduce human behavior include thinking,
speaking and reasoning.
Comprises a group of related technologies: expert system[ES],natural language
processing[NLP],speech recognition, vision recognition and robotics.
Characteristics of fifth generation computer:
This generation computers are very fast, highly reliable, user friendly systems.
Having much faster and large primary storage capacity.
Support parallel programming
Support wide operating system.

S.no

Generation
computers

of Component used

speed

Language used

1.

First generation

Vaccum tube

Milliseconds

Machine language

2.

Second
generation

Transistor

Micro seconds

assembly language

3.

Third generation

Integrated circuits

Nanoseconds

High level language

4.

fourth generation Microprocessor

1 to 10 nanoseconds

4GL

5.

fifth generation

1 to 100 nanoseconds

Artificial
intelligence

Artificial
intelligence

Explain the classification of computers in detail.

TYPE

DESCRIPTION

Based on Hardware Design

a) Analog
b) Digital
c) Hybrid

Based on

a) General Purpose Computer

Utility

b) Special Purpose Computer.

Based on Size

a) Micro Computer

and Capacity

b) Mini Computer
c) Mainframe Computer
d) Super Computer

Based on

a) palmtop PC

Mode of Use

b) Laptop pc
c) PC
d) Workstation
e)mainframe system
f) Server

1. Based on hardware design


o Analog Computers
o Digital Computers
o Hybrid Computers

Analog Computers: These computers recognize data as a continuous measurement of a physical property
(voltage, pressure, speed and temperature).
An analog computer operates on inputs of continuously varying electrical Voltages.
Analog computers are used mainly in scientific design and production environments.
Characteristics:
Requires by measuring.
Function on continuously varying quantity.

Output in the form of graphs.


Calculations are first converted to equations and latter into electrical signals.
Accuracy of the output is poor .
Speed is low.
Example: Automobile speedometer
Digital Computers: These are high speed programmable electronic devices that perform mathematical
calculations, compare values and store results.
They recognize data by counting discrete signal representing either a high or low voltage
state of electricity.
In digital computers, mathematical expressions are represented as binary digits (0 and 1)
and all operations are done using these digits at a very high rate.
These computers are widely used in commercial and control systems.
Basic operation is performed by digital computer is addition.
Other operation such as multiplication, division, subtraction and exponential are done by
successive addition methodology.
Characteristics:
Operate by counting.
It functions on discrete numbers.
Calculations are converted into binary numbers.
Output in the form of discrete values and have large memory space.

Hybrid Computers:
This computer that processes both analog and digital data.
Desirable features of analog and digital machines can be combined to create a Hybrid
Computer.
This type of computer operates by counting as well as by measuring.
Measuring functions are performed by analog way.
Control and logic functions are digital in nature.

2. Based on utility
1. General purpose Computers
2. Special purpose Computers
General purpose Computers
It is designed to satisfy the needs of the society.
A General Purpose Computer is a machine that is capable of carrying out some general
data processing under program control.
Applications:
Business
Scientific problems

Special purpose Computers


This computer that is designed to operate on a restricted class of problems.
Use special purpose computer equipment to obtain patient diagnostic information.
Eg: Aircraft control system, electronic routing machine.
3. Based on size and capacity
a) Micro Computer
b) Mini Computer
c) Mainframe Computer
d) Super Computer
a)Microcomputers
It is the smallest, least expensive of all the computers. Micro computers have smallest memory
and less power, are physically smaller and permit fewer peripherals to be attached.

It consist of microprocessor whose components namely input, output and cpu are on a single
integrated circuit chip.
Advantages:
Small and portable.
Relatively inexpensive.
Dont occupy much space and power.
Disadvantages:
Relatively slow.
Storage capacity also slow.
Minicomputers:
They are smaller than mainframe, general purpose computers, and give computing power
without adding the prohibitive expenses associated with larger systems. It is generally easier to
use.
Word length -32 bits.
Processing speed is in the range of 10 to 30 MIPS.
Memory [RAM] capacity lies in the range 8 to 256 MB.
Minicomputers usually have multiple terminals.
Minicomputers may be used as network servers and Internet servers.
Eg: payroll preparation, accounting computation.
Advantages:
General purpose computer.
Storage capacity is about 2 mega words.
Use all high level languages
Mainframe Computers:
These computers are usually slower, less powerful and less expensive than supercomputers.
A technique that allows many people at terminals, to access the same computer at one time is
called time sharing. Mainframes are used by banks and many businesses to update inventory etc.

It handles huge volumes of data.


Word length -48 to 64 bit memory capacity,
Hard disk 1000 MB to 10 GB
Processing speed-30 to 100 MIPS
Multi-user ,multiprocessor system.
Advantages:
Mainframe computers can support hundreds or thousands of users, handling massive amounts of
input, output, and storage.
Mainframe computers are used in large organizations where many users need access to shared
data and programs.
Mainframes are also used as e-commerce servers, handling transactions over the Internet.
Supercomputers:
These computers are widely used in scientific applications such as aerodynamic design
simulation, processing of geological data.
Supercomputers are the most powerful computers. They are used for problems requiring
complex calculations.
Because of their size and expense, supercomputers are relatively rare.
Supercomputers are used by universities, government agencies, and large businesses.
Word length - 64 to 96 bit memory capacity,
Hard disk 1000 MB and more.
Processing speed-400 to10, 000 MIPS
Machine cycle time -4 to 6 ns.
Advantages:
Use several processors working simultaneously.
They process at rapid speed.
Done operation in parallel

4.Based on modes of use:


a) palmtop PC
b) Laptop pc
c) PC
d) Workstation
e) Server
a) Palmtop PC
It accepts the handwritten inputs using an electronic pen, which can be used to write on
palmtop screen
It have small disk storage.
It has facilities such as mobile phone, fax and e-mail machine
Windows-ce operating system can be used
b.Laptops:
Similar in operation to desktops, laptop computers are miniaturized and optimized for mobile
use. Laptops run on a single battery or an external adapter that charges the computer batteries.
They are enabled with an inbuilt keyboard, touch pad acting as a mouse and a liquid crystal
display. Their portability and capacity to operate on battery power have proven to be of great
help

to

mobile

users.

c) Personal computers
It is mainly designed to meet the personal computing requirements of users at working place or
at home
Non-portable
These computers have rapidly changed the work culture and habits of individuals
It is used by children, adults for education, entertainments and common everywhere.

Configuration varies from one pc to another pc


It has two models
a) Desktop model
b) Tower model
Workstations:
Workstations are powerful single-user computers.
Workstations are used for tasks that require a great deal of number-crunching power,
such as product design and computer animation.
Workstations are often used as network and Internet servers.
Servers and client:
Server:
They are computers designed to provide services to client machines in a computer network. They
have larger storage capacities and powerful processors. Running on them are programs that serve
client requests and allocate resources like memory and time to client machines. Usually they are
very large in size, as they have large processors and many hard drives. They are designed to be
fail-safe and resistant to crash.
Client:
It is a single user pc and supports user friendly with end user.
It send request to server and gain access with server.
With a suitable block diagram of basic organization of computer system describe the
operations performed by it.

The block diagram for computer system is as follows

Control Unit

Input unit

Memory Unit

Output Unit

ALU

Secondary Storage

Data Flow
Control Flow

It having
1) Input unit
2) CPU
3) Output unit
1. Input unit
Computer must need the data and instructions to solve any problem.
We put data and instructions into the computer.
Keyboard is one of the most commonly used input device.
The input device perform following functions
a. Accept data and instructions from the outside world.
b. Convert it to a form that computer can understand.
c. Supply the converted data to the computer system for further processing.
Eg for input devices are

Keyboard, mouse.lightpen, digitizer, trackball, joystick


OCR (Optical Character Recognizer)
MICR (Magnetic Ink Character Recognizer)
OMR(Optical Mark Recognizer)
2) Central Processing Unit (CPU)
It is the heart of computer system.i.e all operations are carried out in CPU only.
It performs following functions
i) It performs all calculations and all decisions.
ii) It controls and coordinates all units of computer.
iii) It interprets instructions of a program.
iv) It stores data temporarily.
The CPU is divided into following subsystem
i)control unit
ii)Arithmetic and logical unit[ALU]
iii)Memory unit
a) Primary storage
b) Secondary storage
i)control unit
It instructs the computer how to carry out program instructions.
It directs the flow of data between memory and ALU.
It controls and coordinates the entire computer system.
Eg: input unit does not know where to receive the data and where to put data in the storage unit.
Control unit only give instructions to input unit

o It controls the flow of data and instructions from storage unit to ALU.
o It controls the flow of data and instructions from ALU to storage unit.
ii) Arithmetic and logic unit
It performs all arithmetic and logical operations.
Arithmetic operations like addition, subtraction, multiplication and logical
operations such as comparison are performed in ALU.
All calculations are performed in ALU.
It performs comparison and takes decision.
E.g.: if the number A is less than, equal to or greater than the number B. Once the calculation is
over, then the result transferred to storage unit.

iii)Memory unit
Memory is a device which is used to store information temporarily or permanently.
Memory is the part of computer which holds data for processing and other information. It
is called main memory or primary memory.
Secondary storage also used for storage purpose but permanently.

memory

primary
memory

RAM

ROM

secondary
memory

Serial access
memory

Serial random
access memory

Eg:magnetic
tape

Eg:floppy disk

Primary memory
The primary memory is also called main memory. stores and access information very
fastly.
It is used to hold the program being currently in the computer, the data being received
from input unit, the intermediate and final results of the program.

It loses its content when we switch off the computer. primary memory is also known as
system memory, internal, temporary and RAM.
Primary memory is two types
i) ROM [read only memory]
ii) RAM [random access memory]
i) ROM [Read Only Memory]

It is permanent memory at the time of production.


ROM is also called firmware.
It stores a set of instructions permanently which instructs the computer how to work.
Trigonometric and logarithmic function is also performed.
Also called as programmable read only memory.
Types of ROM
i)PROM[programmable ROM]
ii)EPROM[erasable PROM]
iii)EEPROM[electrically EPROM]

ii) RAM [random access memory]


It is local local memory,where the computer stores all data and the instructions it receives
From input and the result as it work through its calculations.
RAM is short-term memory or volatile memory.i.e the computer is switched off, all
information disappears.
It is not permanent memory but it is fastest memory.
Secondary memory
It is called Auxiliary storage.
It stores several programs, documents, databases.
The program we want to run on the computer is first transferred to the primary memory
before it can run.
After running the program, we need to save the program, if we need secondary storage.
It is permanent storage, the data or information stored in this storage will not erase, when
power is lost.It is called non-volatile memory.
Secondary memory is also known as disk storage, external, long term.
Not directly accessible-data transferred throughan I/O system.
Non-volatile and long-term storage
Not fast as internal memory
Holds larger amount of data

It having
a) Floppy disk
b) Hard disk
c) CDROM
d) Magnetic tape
e) Cache memory
f) Virtual memory
a) Floppy disk
It is the piece of a plastic that we put into computer to store information.
b) Hard disk
It is permanent storage, where we store lots of information.
c) CDROM [Compact Disk-Read Only Memory]
It is used to store large amount of data.i.e 700MB to 1.4GB
d) Magnetic tape
It is used as a backup storage for data stored on online storage devices.
e) Cache memory
A small memory between CPU and main memory are called cache memory.
f) Virtual memory
It is just an imaginary memory.
3) Output unit
Devices used to get the response (or) result of a process from the computer.
Output unit is communication between user and computer.
It provides the information and results of a computation to outside world.
Computers does not work in the decimal system,they work in binary system.
Output unit converts the binary data into a form the users can understand.
Commonly used output devices are
a) Monitor
b) Printer

c) Plotter
c) Computer output microfilm
Write the uses of algorithm with suitable examples.
Algorithm
Algorithm is a finite sequence of instructions required for producing the desired result.
Characteristics:

The steps in the algorithm must be unambiguous .


It should be written in sequence.
Ensure that the algorithm will terminate.
It should conclude after a finite number of steps.

Factors used to judge the algorithm :

Time
Memory
Accuracy
Sequence etc,.

Representations:

Flowcharts
Normal English
Pseudo code etc,.

Example

Addition of two numbers

Step1: Start
Step2: Read a, b
Step3: Add the value of a with b and store the result in c.
Step4: Display the value of c.
Step5: Stop.

Draw and explain the various symbols of flowchart


Flowcharts
It is the pictorial representation of the algorithm.
Flowchart Symbols

Terminal symbol
It is used to represent the start, end of the program logic.

Input/Output
It is used for input or output.

Process Symbol
It is used to represent the calculations, data movements, initialization operations
etc,.

Decision Symbol

It is used to denote a decision to be made at that point

Flow lines
It is used to connect the symbols

Connectors
It is used to connect the flow lines.

Guidelines for preparing flowcharts

It should be simple.
Standard symbols should be used.
The flow lines should not intersect each others.
In case of complex flowcharts use the connectors symbols.
Only one flow line should enter the process symbol and only one flow line should come
out from a process symbol.

Only one flow line used with the terminal symbol.

START
STOP

Only one flow line should enter the decision symbol and two or three flowlines may
leave from the decision symbol.

Benefits of Flowcharts

Makes Logic Clear


Communication
Effective Analysis
Useful in coding
Useful in Testing etc,.

Limits of Flowcharts
It is difficult to use flowcharts for large program
Difficult to modify
Cost etc,.
Design Structures
1. Sequence structure
START

Read

Process

Output

STOP

A series of statements performed one after other. Because the flow always continuous
in same direction every time the structure is executed.
A sequence may include a number of instructions, but each would be done in turn in
the same order.
2. Selection structure

Is
A>B

False
B is big

True
A is big

It uses a decision to ask some question.


This structure includes the decisions and operations to be performed in response
to the decisions.
There will be two exits from the decision, but both of these branches are still a
part of the selection structure, then both branches must rejoin a single flow line to
exit the structure.
Using these selection structure different steps may be executed depending on the
result of the decision test.
If the selection only as an operation the true side, then it is called a one-sided
selection, with this one sided structure the null side still must have its exits from
the decision box.
3. Loop structure
It is used to execute a sequence of steps in a number of times or until a
particular condition is met.
There are two loops available.
o Top tested loop
o Bottom tested loop
(i)

Top tested loop


It is leading decision loops, means that the decision is evaluated always at the
first statements of the loop.
If it is true, the control follows the flow line that goes into the loop.
If it is false, control follows the flow line to the first statement after the loop.

Start

Count=0

If
count<10

No
Add 1 to count

Stop
Display Count

Yes

(ii) Bottom tested loop


It is a trailing decision loop, means that the decision is always at the last
statement of the loop.
The body of the loop is executed once before control even gets to the loop test.
In this loop if the condition is false, control follows the flow line back to the
loop.
If the test is true, control follows the branch from the decision box that exits the
loop structure.

START

Count=0

Add 1 to count

Display count

No

If count
> 10

Yes
STOP

What is pseudo code and explain its benefits and limitations.


Pseudocode

Pseudo means imitates and code means instruction.


It is formal design tool.
It is also called Program Design Language.

Keywords

READ,GET
PRINT,DISPLAY
COMPUTE,CALCULATE

Guideline for writing Pseudocode

Steps should be understandable


Capitalize the keyword.
Indent to show hierarchy.
End multiple line structure etc,.

Example
READ a,b
C=a+b
WRITE C
stop
Example
READ a,b
IF a>b
PRINT a is greater
ELSE
PRINT b is greater
ENDIF
Stop

Advantage & Disadvantage

It can be easily modified


It can be understood easily
Compare to flowchart it is difficult to understand the program logic.

Explain Pseudo code and how it can be designed


Design Structures
Sequence control structure

Flow chart

Process 1

Pseudocode

Process 1

Process 2

Process 2

Process n

Process n

The instructions are computed in sequence i.e. it performs instruction one after another.
It uses top-down approach

Example
START

Read a,b

C=a+b

Print c

STOP

SELECTION CONTROL STRUCTURE

It is used for making decisions.


It allows the program to make a choice from alternative paths.
IF THEN
IF THEN ELSE
CASE etc.,

Program planning method

Specification
Review
Informal Design
Formal Design
Coding

Test & Debug


Maintaining

Specification review
collect the requirements
understand the requirements
Informal Design
Identifies the major tasks
Identifies the subtasks
Formal Design
It converts the informal design to some format that can be understand by others.
Coding
It converts the Design into Programs.
It translate these programs to machine language.
Test & Debug
It use sample data to test whether it works properly.
It also eliminate the errors.
Maintaining
It Modifies the programs if necessary

Waterfall method

Feasibility
Analysis
Design
Impl
Testing
Maintenance

Feasibility
It determines whether it is possible to create the project or not.
It also produce the plans and the estimates.
Analysis

It get the requirements from the customer.


It analysis the requirements.

Design
It is the process of designing how the requirements to be implemented.

Implementation
It converts the designs into code.
After coding it use language translators to compile the code.

Testing
Here the modules are integrated together.
Then the project is tested and find whether it meets the customer/user
requirements.

Maintenance
It make modifications based on the customer feedbacks.

Introduction:

Computer software are classified into two types

1. Application Software: It is set of programs necessary to carry out for specific applications.
2. System Software: The general programs written for the system which provide the
environment to facilities the writing of application software.

High level Languages:

Some of high level languages are

(i)
(ii)

FORTAN
COBOL

(iii)
(iv)
(v)

BASIC
PASCAL
C Language

(i) FORTAN [Formula Translation]


Oldest high level language
Developed by John Backus and his team at 1956-57
Languages are developed for scientific and Business application.
Versions:

FORTAN II - Popular version in 1950


FORTAN IV - Developed in 1960, popular version
FORTAN 77- It was most powerful
FORTAN 90- It is recent version
(ii) COBOL[Common Business Oriented Language]
It begins in 1959 in USA department.
The first formal COBOL was published in 1960 & revised in 1965.
This programming language is used for business data processing.
(iii)BASIC [Beginners All Purpose Symbolic Instruction Code]
Developed in 1963 by Dr. John, G.Kemeny and Thomas E.Kurtz.
It is developed for the users who are starting their learning in computers.
It is simple to learn
(iv) PASCAL
Blaise Pascal is designed and developed by Nickolas in 1971
Objective of this language was to learn good problem solving and programming
methods for the beginners.

Introduction to C
'C' is one of the most popular programming language; it was developed by Dennis Ritchie
at AT & T's Bell Laboratories at USA in 1972.
It is an upgraded version of two earlier languages, called BCPL and B, which were also
developed at Bell laboratories.
History of C Language
ALGOL

-> 1960 ->International group

BCPL

-> 1967 ->Martin Richards

-> 1970 ->Ken Thompson

-> 1972 ->Dennis Ritchie

ANSI

-> 1989 -> ANSI Committee

ANSI/ISOC-> 1990 -> ISO Committee

All modern computer languages are started through the ALGOL language in 1960.
After the COBOL was being used for commercial applications.
FORTAN was developed for scientific applications.
A committee was formed to develop a new language called Combined Programming
Language (CPL) at Cambridge University.
Basic CPL was derived by BCPL.
BCPL was developed by Martin Richards at Cambridge University by 1967.
At the same time a language called B was developed by Ken Thomson at AT &
Ts Bell labs in 1970.
Then C language is developed by Dennis Retchie in 1972 with some additional
features of BCPL and B which is very simple.
ANSI C American National Standard Institute has began to work on a standardized
definition of the C language that makes it still powerful.

Types of Language:
Low level Language (or) Machine Language.
High Level Language normal English, human understandable language,
machine independent, C, C++, etc

Middle Level Language


C Language is also called as Middle level Language because C stands in
between Low level Language (nor) high level language (i.e) it performs task of
low level languages as well as high level language.
We can write program for operating, application programs, Assembly language
programs in C Languages.
UNIX operating system is written in C Language.
Features and Applications of C Languages:
1.
2.
3.
4.

C is a general purpose, structured programming language.


C is a powerful, efficient, compact & flexible.
C is highly portable. It can run in different operating systems environment.
C is robust language. It has built in functions and operators can be used to write any
complex program.
5. C is well suited for writing system software as well as application software.
6. C is middle level language. It supports low level & high level language.
7. C language allows reference to memory allocation with the help of the pointers.
8. C language allows dynamic memory allocation.
9. C programs are fast and efficient.
10. C can be applied in system programming as like.

Structure of C Program
A C program may contain one or more section.

Documentation section

Preprocessor section

Definition section

Global declaration section

main()

Declaration part;

Executable part;

1. Documentation Section :
of the program etc.
Comments:

It consists of set of comment lines used to specify the name


Subprogram Section

{ in identify the program features and logic of the


Comments are very helpful
program.
Body
the subprogram
The lines begins with /*
andofending
with */ are known as comments lines.
}
These lines are not executable.

There are two types of comment lines,


Single comment line eg., /* ABCD.
Nested comment line (or) multiple comment line
e.g, /*..
..*/
2. Preprocessor Section :
It is used to link system library files for defining the macros and for defining the
conditional inclusion.
C program depends upon some header file for function definition that are used in
program.
Header file is extended with .h. This file should be included using #.
Eg.,
#include<stdio.h>
<stdio.h> file is included. All definitions and prototypes of function defined in this file.
(i)
(ii)

3. Global Declaration Section: The section declares some variables that are used more
than one function. These variables are known as global variables. These variables must
be declared outside of the main function.
Function main:

Every C program must contain main function.


Without main function that is not a C program.
After main function empty parenthesis are necessary.
Main () is the starting point of every C program.
The execution always begin with the main function
The execution starts with opening brace { & closing brace }
In between these braces the programmer should write executable and declaration part.

Executable part: it contains a set of statements or a single statement. These statements


are enclosed between the braces.
Declaration part: It declares the entire variables that are used in executable part.
Variable initialization is done in declaration section.
4. Sub program section (or) User defined function
These section defined by user are called user defined functions.
These functions are defined after the main function (or) before the main function.
PROGRAMMING RULES:
While writing a program, a programmer should follow the following rules.
1. All statements should be written in lowercase letters.
2. Uppercase letters are only used for symbolic constants.

3. Blank space may be inserted between words. But blank space is not used while
declaring a variable, keyword, constant and function.
4. The programmers can write the statement anywhere between the two braces.
5. We can write one or more statements in a same line by separating each statement
in a same line by separating each statement with semicolon (:)
6. The opening and closing braces should be balanced.
*************************************************************
CONSTANTS, VARIABLES AND DATA TYPES

Character Set
Character set is a fundamental raw material of any language.

C Character Set

Source Character Set

Alphabets

Digits

Special
Character

Execution Character
Set

White
Spaces

Escape Sequence

Two types of Character Set:

Source Character Set.


Executable Character Set.
Source Character Set:
It is used to construct the statements in the source program.
Source character set is classified into,

Alphabet A to Z and a to z
Digit 0 to 9
Special Character +,-,?,/,(,),*,&,^,$,#,@,!,<,>,:,;,,,_,=
White space Blank Space, horizontal tabs, vertical Tab, newline, form feed.

Executable Character Set:


It is used at the time of execution.
Execution character set is also called as non-graphic character (or) Escape sequence.
Escape sequence are invisible and cannot be printed (or) displayed on the output screen.
Escape sequence are always represented by a back slash(1) followed by a character.
Escape sequence are invisible and cannot be printed (or) displayed on the output screen.
Escape sequence are always represented by back slash (\) followed by a character.

Character
Escape Sequence
Result

Bell

\a

Beep Sound

Back Space

\b

Moves Previous Position

Horizontal Tab

\t

Moves next horizontal tab

Vertical Tab

\v

Moves next vertical tab

Newline (line feed)

\n

Moves next line

Form feed

\f

Moves initial position next page

Carriage return

\r

Moves beginning of the next line

Question mark

\?

Present Question mark

Question mark

Present Quotation mark

Apostrophe

Present Apostrophe mark

Backslash

\\

Present Back slash mark

NULL

\0

NULL

C Tokens
Token is defined as collection of entity. They are identifiers, keywords, constants, strings,
operators, special symbols.
Tokens are usually referred as individual text & punctuation in a passage of text.
C Tokens

Identifiers

Keyword

Constants

Eg : main()

Eg., int

Eg., 39.77

String

Eg., XYZ

Operator

Eg., +,-,*

Special symbols

Eg., #,$,%

Identifiers:

Identifier is defined as name of the variable, function, arrays etc.


Eg., STDNAME, SUB invalid identifiers Return, STD NAME

Keywords

Keywords are reserved words by the compiler that have standard and fixed (or)
predefined meaning in C Language.

The meaning cannot be changed. There are 32 keywords in C language.


The keywords are,

auto
double
int
struct
break

else

long

case

enum

registertypedef

char

extern

return

union

const

float

short

unsigned

continue

for

signed void

default goto
do

sizeof
if

switch

volatile
static

while

All the keywords must be written in lower case.


Describe the different types of constants:

Constants:

C Constants

Numeric Constants

*Integer constant
*Real constant

Character Constants

*Single character
constants
*String Constant

Definition:
Constants do not change during the execution of a program.

Numerical Constant:

It is divided into two types,

1. Integer constant
2. Real constant
Integer constant
They are the sequence of numbers from 9 without decimal point (or) fractional part (or)
any symbols.
Eg., 10,20,+30,-5, etc
Real Constant
Real constant are often known as floating point constants
Eg: 2.4, 5.345, 4.123 etc

Character constant:

1. Single character constant:


A character constant is a single character. They are also represented with a single
digit (or) single special symbols (or) white spaces enclosed within a pair of single
quote marks. Eg., a, g
2. String constant:
String constants are sequence of characters enclosed within double quote marks.
Eg., Hello, India, a etc

Different Data types in C:

Data types:

Allows the programmers to select the appropriate data type as per the need of the
application.
Data types are used to specify the types of data.
They are in different types
1. char
(i) Signed Character
(ii) Unsigned Character
2. int
3. float
4. double
5. long double
ANSI C supports four class of data type:

1.
2.
3.
4.

Primary data type


User defined data type
Derived data type
Empty data type

Char- Signed, Unsigned:

Signed Char
Occupies 1 byte in memory range- 128 to
127 control string %c

Unsigned Char
Occupies 1 byte in memory range 0 to 255
control string %c

Differentiate Integer Signed and Unsigned:

Integer Signed, Unsigned:

Signed Integer
1.
2.
3.
4.

Occupies 2 bytes in memory


Range: -32768 to 32767
Control string: %d or %L
Long signed integer having from
2147483648 to 2147483647
5. Eg: int a=2
Long int b=2

Unsigned Integer
1.
2.
3.
4.

Occupies 2 bytes in memory


Range: 0 to 65535
Control string: %u
Long signed integer having from 0
to 4294967295
5. Eg: unsigned long b;
unsigned short int c;

Float:

It is a data type which accepts fractional part occupies 4 bytes in memory.


Range: (3.42-38) to (3.42+38)
Control String-%f
Eg: float a
Double:

Occupies 2 bytes in memory


Range: 1.72-308 to 1.72+308
Control String: %&f
Eg: double a;

Long double:

It is a data type in C language


Occupies to bytes in memory

Range: -1.7e4932 to 1.7e4932


Eg: long double k;
Primary data types:

Primary data
types

Integer

Signed

int

Short int

Character

Unsigned

Signed Char

Long int

Unsigned
int

Unsigned
short int

Unsigned
long int

Unsigned Char

Integer Types:

Type

Size (bits)

Range

int or signed int

16

-32, 768 to 32767

unsigned int

16

0 to 65535

short int

-128 to 127

unsigned short int

0 to 255

long int

32

unsigned long int

32

-2,147,483,648 to 2,147,
483, 647
0 to 4,294,967,295

Floating Point Types:

Type

Size (bits)

Range

Float

32

3.4E-38 to 3.4E+38

Double

64

1.7E-308 to 1.7E+308

long double

80

3.4E-4932to 1.1E+4932

Type

Size (bits)

Range

Char

-128 to 127

unsigned char

0 to 255

Character Types:

VARIABLE DECLARATION:

Declaration of variable can be done in the declaration part of the program.


The variables must be declared before they are used in the program.

Syntax:

Data type Variable Name

Eg: int a;
char m;
float s;
Initializing Variables:

Value can be initialized in the valuable name using an assignment operator =

Syntax:

Data type variable name= constant

Eg: int x=2;


x=2;
Rules for defining variables:

Variable name must begin with a character without spaces but underscore(_) is permitted.
The variable should not be a Cat keyword
The variable names may be a combination uppercase and lower case character.

Variable should not start with a digit.


Scope of the variable:

Scope of the variable implies the availability variables within the program.
Variables have 2 types of scope
(i)
Local variable
(ii)
Global variable
Local variable:

Local variables are defined inside a function block(or) inside a compound statement of a
function subprogram are called local variables.
Eg:
function()
{
int i,j;
}
function()
{
int i,j;
}

Global / External Variable:


The variables that are declared before the function main() are called the global/external
variables.
Eg: int a,b;
void main()

// here a,ball is a global variables.

{
}

Operator and Expression:

Operator:
An operator is a symbol that specifies an operation to be performed on the operands.

Operand:

It is an data item on which operators perform operation.

Eg: a+b

Here, a, b Operator
+ Operand
Explain various types of operators in C language with suitable example
Types of Operator:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

Arithmetic operators
Arithmetic operators are,
+ , - , * , / , %.
C allows basic arithmetic operations like addition, subtraction, multiplication and division.
+

Addition

2+9 = 11

Subtraction

9-2= 7

Multiplication

2*9= 18

Division

9/3= 3

Modulo division

9%2=1

Arithmetic operators are classified as


i)Unary arithmetic : It requires only one arithmetic.
Eg: +x, -y
ii)Binary arithmetic: It requires two operators
Eg: a+b, a%b
iii)Integer arithmetic: It requires both operands are integer value for arithmetic operators.
Eg: a+b :
a= 5, b=2
a+b= 5+2=7
iv)Floating point arithmetic: It requires both operands are float type for arithmetic operators
Eg: a+b
a=6.5

b=3.5

a+b 6.5+3.5 = 10
Sample program:

#include<stdio.h>
#include<conio.h>
void main()

{
int b,c,d;
int sum, mul, sub, rem;
float div;
clrscr();
printf(Enter values of b,c,d:);
scanf(%d%d%d\n\n\n, &b,&c,&d);
sum=b+c;
sub=b-c;
mul=b*c;
div=b/c;
rem=b%d;
printf(\n sum=%d,\n sub=%d,\n mul=%d,\n div=%f,sum,sub,mul,div);
printf(\n Remainder of division of b&d is %d,rem);
getch();
}
Output:

Enter the values of b,c,d:


2
3
4
Sum=5;
Sub=-1
Mul=6

Div=0.6666666
Reminder of division of b&d is 0
Relational operator

Relational operators are used to compare two or more operands. Operands may be variables,
constants or expression.
Operator

Meaning

<

is less than

<=

is less than or equal to

>

is greater than

>=

is greater than or equal to

==

is equal to

!=

is not equal to

Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(\n condition: Return value \n);
printf(\n 5!=5: %5d, 5!=5);
printf(\n 5==5:%d,5==5);
printf(\n 5>=50: %d,5>=50);
printf(\n 5<=50: %d,5<=50);

printf(\n 5!=3: %5d, 5!=3);


getch();
}
Output:
Condition

Return value

5!=5

5==5

5>=50

5<=50

5!=3

Logical operators:
Logical operators are used to combine the results of two or more conditions.
Operator

Meaning

Example

Return value

&&

Logical AND

(9>2)&&(17>2)

||

Logical OR

(9>2)||(17==7)

Logical NOT

29!=29

Sample coding for logical operator:

#include<stdio.h>
#include<conio.h>
void main()
{

int c1.c2,c3;
clrscr();
printf(Enter the values c1,c2,c3);
scanf(%d%d%d, &c1,&c2&c3);
if((c1<c2)&&(c1<c3))
printf(c1 is less than c2 and c3);
if(!(c1<c2))
printf(\n c1 is greater than c2);
if((c1<c2)||((c1<c3))
printf(c1 is less than c2 or c3 both);
getch();
}
Output:
Enter the values c1,c2,c3
9
6
3
C1 is greater than c2
Assignment Operator:

Assignment operators are used to assign a value or an expression or a value of a variable


to another variable.

Syntax: variable=expression (or)


value ;

Example : x=10;
x=a+b;
x=y;

Two types of assignment operator are,


(i) Compound assignment
(ii) Nested assignment (or) multiple assignment
Compound assignment
Assign a value to variable.

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

Nested assignment
Assign a value (or) Expression to variable.

Syntax:
var1 = var2 = var3
Ex: i=j=k=1
x=y=z=(i+j+k)
Sample Program for assignment operator

#include<stdio.h>
#include<conio.h>
void main()
{

int i,j,k;
clrscr();
k=(i=4,j=5);
printf(k=%d,k);
getch();
}
Output:
k=5
Increment & Decrement Operator:
'C' has two way useful operators not generally found in other languages, these are the
increment (++) and decrement (--) operators. + & - operators are called unary operators.
Because they acts upon only one variable.
++x Pre increment
--x Pre decrement
x++ Post increment
x-- Post decrement.

#include<stdio.h>
#include<conio.h>
Void main()
{
int a=10;
clrscr();
printf(a++=%d\n,a++);
printf(++a=%d\n,++a);

printf(-- a=%d\n,--a);
printf(a--=%d\n,a--);
getch();
}

Output:
a++=10
++a=12
--a=11
a--=11
Conditional Operator

Checks the condition and executes the statement.


Ternary Operator ( condition ? Exp1:Exp2)
Eg:
Sample program for conditional operator:

#include<stdio.h>
#include<conio.h>
void main()
{
int a=5,b=2,big;
clrscr();
big=(a>b)?a:b;
printf(Largest number is %d,big);

getch();
}
Output:
Largest number is 5
Bitwise Operator:

Bitwise operators are used to manipulate the data at bit level. It operates on integers only

Operator

Meaning

&

Bitwise AND

Bitwise OR

Bitwise XOR

<<

Shift left

>>

Shift right

One's complement

Sample Coding for Bitwise operator:

#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,c;
clrscr();
a=10;

b=20;
c=a&b;
printf(Bitwise AND=%d,c);
c=a/b;
printf(Bitwise OR=%d,c);
c=a+b;
printf(Bitwise XOR=%d,c);
c=~a;
printf(ones complement=%d,c);
getch();
}
Output:
AND=2
OR=10
XOR=8
Ones complement= 5

Special Operator:

Operators

Meaning

Comma Operator

Sizeof

size of operator

& and *

Pointer Operator

Member selection operators

Special Operator:

Sizeof() Operator:

The sizeof() operator : The sizeof() is a unary operator, that returns the length in bytes of
the specified variable, and it is very useful to find the bytes occupied by the specified variable in
the memory.

Expressions:
An expression represents data item such as variables, constants and are interconnected
with operators as per the syntax of the language.
Example:
y=(a/b)+c; z=(a*b)-d;

*************************************************************
Explain briefly formatted and unformatted in input/output functions in C
Or
Explain Managing Input and Output Operator:

Managing Input and Output Operator

In C Language two types of Input/output statements are available and all input and
output operations are carried out by through function calls.

(i)
(ii)

Formatted input / output statements.


Unformatted input / output statements.

Input and Output Functions

Formatted functions :

Definitions :

* Formatted input and output functions read and write all


types of data values.
*They require conversion symbol to identify the data.
*The formatted functions return the values after execution.
The formatted input functions are

1. scanf();
2. fscanf();
scanf();
This statements reads all the types of data values from the input device
(Keyboard)
It is used for runtime assignment of variables.
Scanf() requires conversion symbol(control string) to identify the data to be
read during execution of the program.
Syntax:

scanf(Control string,& var1,&var2,,&var n);

Eg:
scanf(%d %f %c&a,&b,&c);

Control string:
It is type of data that user going to accept via input statements.
Eg:
%c,%d,%f,%s
& var :
Each variable name must be proceeded by an ampersand(&).
A symbol gives the meaning address of the variable.
The address operator prints memory location of the variable.
Rules for writing scanf() function:

1.The control string must begin with (%)sign and must be within quotations.
2.If there is a number of input data items, items must be repeated by commas,and
must begin with(&)sign except for string input.
3.The control string and the variables going to input should match with each other.
4.It must have termination with semicolon.

Eg for scanf function

#include<stdio. h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf (Enter the values of a, b;);
scanf(%d %d, &a, &b);

c=a+ b;
printf (c=%d ,c);
getch();
}
Output:
Enter the values of a, b
2
4
6
Formatted output function:
printf()
printf() is formatted output function.
It is used to print the result message on the output screen.
It prints all types of data values.
Syntax:

printf(control string,var1,var2,var n);


Eg:
printf(The result is %d,var1);
printf(%d,a);
printf(Welcome to VRSCET);

Rules for writing printf() function:


1.
2.
3.
4.
5.

Place appropriate headings in the output.


The Variable must be separated by comma and need not be begin with &sign.
The control string and variables must match in their order.
The control string must be in quotation.
The printf statements is terminated by semicolon(;)

Eg:

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(Enter the value;);
scanf(%d ,&a);
printf(b=%d,a);
getch();
}
Output:
Enter the value
3
4
b=3

Un Formatted output function:


Definition:
The unformatted input/output functions only work with the character data
type.
They dont require conversion symbols for identification of datatype.
Unformatted functions also return values, but the return value of unformatted
function is always the same.
UNFormatted input functions are:

* getc(); *getch(); *getche(); *gets(); *getchar()


*getc();
Used to accept a single character from the standard input to a character variable.
Syntax: Char variable = getc();
Eg : char c
C=getc();
*getch()
Accepts the character but does not display the character.
*getche()
Accepts the character and displays the character.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
printf(Enter any two alphabetics);
getche();
getch();

}
*getchar();
This functions reads character type data from the standard input. It reads one
character at a time till the user processes the enter key.

Syntax: Char variable = getchar();


Eg:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
clrscr();
printf(enter any character/Digit..);
ch=getchar();
if(is alpha(ch)>0)
printf(It is alphabet);
else if(is digit(ch)>0)
printf(It is a digit);
else
printf(it is alphanumeric);
getch();
}
gets()
This functions is used to string from the standard input device (Keyboard)

Syntax: gets (variable);


Eg: gets(s);
Unformatted Output functions are

put();
put ch();
put char();
put s();

put c();
This functions is used to display single character in a character variable to standard output
device.

Syntax:
put c (char variable);
Eg: char c;
put(c);
putch();
This function prints any alphanumeric character taken by standard input device.
ch=get ch();
putch(ch);
putchar()
This function prints one character on the screen at a time which is read by the standard
input.

Eg: c=get char();


put ch();

Eg:
#include <stdio.h>
#include<ctype.h>
#include <conio.h>
main()
{
char ch;
clrscr();
printf(enter any alphabet either in lower or uppercase)
ch=getchar();
if(is lower(ch))
put char (to upper (ch));
else
put char (to lower (ch));
}

Output
enter any alphabet either in lower or uppercase
record
RECORD
puts()
This function print the string (or) character array to the standard output device.

Syntax: put s(variable);


Eg: put(s);

Eg:
#include<stdio.h>
main()
{
char scientist[40];
puts(Enter name);
gets(scientist);
puts(print the name);
puts(scientist);
}

Character test functions:

isalnum(ch)is ch an alpha numeric character


isalpha(ch) is ch an alphabetic character
isdigit(ch)is a digit
islower(ch)is a lower case letter
isupper(ch)is a upper case letter
isspace(ch)is a blank space character
tolower(ch)convert ch to lowercase
toupper(ch)convert ch to uppercase

Decision making:
C language provides four general categories of control structure.
a) Sequential structure
In which instructions are executed in sequence
Eg:
i=i+1;
j=j+1;
b) Selection structure
Sequence of the instructions is determined by using the result of the condition.
Eg:
if(x>y)
i=i+1;
else
j=j+1;
c) Iteration structure
In which statements are repeatedly executed. These form program loops.
Eg:
for(i=1;i<=5;i++)
{
i=i+1;
}
Encapsulation structure:

In which the other compound structures are included.


for(i=1;i<=5;i++)
{

if(a==b)
{
..
..
}
}

*********************************************************
Explain different types of conditional statement
Or
Explain in detail about Decision making

Decision making:
Conditions are placed in the program using decision making statements.
Decision making statements check the condition and then executes its sub blocks.
C language provides the following conditional statements.

if statements
if..else statements
nested if.else statements
if statements

ifelse ladder

if is a c keyword.
The if statement is a decision making statement
Used to control the flow of execution by executing statements when the logical condition
is true (or) false.

It has only one option.


The set of command lines are executed only when logical condition is true.
if (condition)
{
statement -1;
statement -2;
}

condition

True

Statement-1

/* Find out the given no is equal using if statement*/

Eg:

False

#include<stdio.h>
void main()
{
int a;
printf(enter the value);
scanf(%d,&a);
if(a==10)
{
printf(Both are equal);
}}
if ..else statement

It is two way decision making statement


if..else statement take care of true as well as false condition.
It has two block if & else
if block is executed when the condition is true, else block is executed when the condition
is false.

condition

Statement 1

Statement 3

Statement 2

Statement 4

Syntax:
if(condition is true)
{
statement 1;

statement 2;;
}
else
{
statement 3;
statement 4;
}

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf(enter the value);
scanf(%d,&a);
if(a==10)
{
printf(both are equal);
}
else
{
printf(both are not equal);
}
getch();

Output :

Enter the value 4


both are not equal
or
enter the value 10
both are equal
/* Given number is odd (or) even */

#include<stdio.h>
#include<conio.h>
void main()
{
int num,rem;
clrscr();
printf(Enter ur number);
scanf(%d,&num);
rem=num%2;
if(rem==0)
printf(the number is even);
else
printf(the number is odd);
getch();

Output:
Enter the number
2
The number is even

Nested ifelse statement

if..else statement is written in another if.else statement called nesting and the
statement is called nested if

Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2;
}
Else
{
false statement 2;
}
}
else

{
false statement 1;
}
/*For nested if..else to find out smallest of 3 number*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,small;
clrscr();
printf(Enter three numbers);
scanf(%d%d%d,&a,&b,&c);
if(a<b)
{
if(a<c)
small=a;
else
small=c;
}
else
{
if(b<c)
small=b;
else

small=c;
}
printf(the smallest value is %d,small);
getch();
}
Output:
Enter the three numbers
2
3
4
The smallest value is 2

if.else Ladder

Number of logical conditions is checked for executing various statements.


If three are more than three alternatives and indentation is not consistent, it may be different
for you to determine the logical structure of the if statement
Syntax:

if(condition 1)
{
Statement 1;
else
if(condition 2)
{
Statement 2;

}
else
if(condition 3)
{
Statement 3;
}
else
{
default-statement;
}

True

False

Condition 1

True
Statement 1

False

Condition
2

True

Statement 2

False
Cond
3

Statement 3

Default
Statement

Example program: for else..if ladder

#include<stdio.h>
main()
{
int a,b,c,d;
printf(enter the four numbers);
scanf(%d%d%d%d,&a,&b,&c,&d);
if((a<b)&&(a<c)&&(a<d))
printf(a is greater);
else
if((b>a)&&(b>c)&&(b>d))
printf(b is greater);
else
if((c>a)&&(c>b)&&(c>d))
printf(c is greater);
else
printf(d is greater);
return(0);
}

Output:
enter the four numbers
2
5

3
6
d is greater

Explain switch case with suitable example


Switch case statements:
Switch statement is a multi-way branch statements.
To make a choice from a number of options, this structured selection is useful.
Switch statement required only one argument of any data type which is checked with
number of case options.
If the value matches with case constant this particular case statement is executed if not
default is executed.
Here switch case default are reserved c keywords
Every case statements terminate with: -break statement is used to exit from the current
case structure.
Syntax:
Switch (variable (or) expression)
{
case constant 1:
statement 1;
break;

case constant 2:
statement 2;
break;

case constant 3:
statement 3;

break;

default:
statement;
}

Switch

Case 1
Statement

Case 2
Statement
Default
Statement

Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, option;
printf(\n 1.Addition);
printf(\n 2.subtraction);
printf(\n 3.multiplication);
printf(\n 4.Division);
printf(\n 5.Exit);
printf(\n Enter two number);
scanf(%d %d, &a, &b);
printf(\n Enter your option)
scanf(%d, &option);
switch(option)
{
Case 1:
c=a+b;
printf(\n Addition=%d ,c);
break;

case 2:
c=a-b;
printf(\n subtraction=%d,c);

break;

case 3:
c=a*b;
printf(\n multiplication=%d,c);
break;

case 4:
c=a/b;
printf(\n division=%d,c);
break;

case 5:
Exit(0);
break;

default:
printf(Invalid Choice);
}
getch();
}
Output:

Enter two numbers


2

Enter your option


1

*************************************************************
Describe the statements for looping

Branching and Looping:

Explain the various looping constructs.

Loop:
A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
They are three types of loop control statements
1. for
2. while
3. do-while
Give the syntax for loop statement and explain with suitable example
for loop
Syntax:

For(initialize counter; test condition; increment/decrement

counter)
{
statement 1;
statement 2;
}

Initialization

Increment/
Decrement

Body of loop
Condition

True

False

Increment/
Decrement

Condition
Body of loop

(i) Initialise counter:


It is used to initialize the counter variable

(ii) Test condition:

It is used to test the condition.

(iii) Increment / decrement counter:


It is used to Increment / decrement the counter variable

Ex:
#include<stdio.h>
#include<conio.h>
main()
{
int i, sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
printf(The addition of numbers upto 10 is %d,sum);
getch();
}

Output:

The addition of numbers upto 10 is 55

While loop:
It is repetitive control structure used to executed the statements within the body
until the condition becomes false.

Condition

false

Body of the loop

true

Syntax:

while(test condition)
{
body of the loop;
}
Test Condition:
It may be any expression.
The while loop is an entry controlled loop statement means the condition is evaluated
first and it is true, then the body of the loop is executed.
After executing the body of the loop, the condition is once again evaluated and if it is
true, the body is executed once again, the process of repeated execution of the body of the
loop continues until the condition becomes false and the control is transferred out of the
loop.
Eg: Sum of given number using while loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+1;
i++;
}
printf(the sum of numbers upto 10 is %d);

getch();
}
Output:

the sum of numbers upto 10 is 84

Program to reverse the given numbers using while loop

#include<stdio.h>
void main()
{
int number, digit, rev=0;
printf(Enter the number:);
while(number!=0)
{
digit=number%10;
rev=rev*10+digit;
number=number/10;
}
printf(%d,rev);
getch();
}

do.while

Here the condition is checked at the end of the loop.


The do while loop will executed at least one time even if the condition is false initially.
The do-while loop executes until the condition becomes false.
for-loop allows to executed a set of instructions until a certain condition is satisfied.

Syntax:
do
{
Statement;
}
while(condition);

Body of the loop

Condition

Addition of numbers upto 10 by using the dowhile loop.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=2,sum=0;
do
{
sum=sum+i;
i++;
}
while(i<=10)
printf(sum of the numbers upto 10 is=%d,sum);
getch();
}
Output:
sum of the numbers upto 10 is 54
Difference between while and do.while
While

do.while

1. This is the top tested loop.

1. This is the bottom tested

2.The condition is first tested, if the


condition is true, then the block is executed
until the condition becomes false.

2. It executes the body once after it checks


the condition, if it is true the body is
executed until the condition become false.

3. Loop will not be executed if the


condition is false

3.Loop is executed at least once even


through condition is false.

Continue statement:

The condition statement is used for continuing next iteration of loop statements.
It is useful when we want to continue the program without executing any part of the
program.
Eg:
#include<stdio.h>
void main()
{
int i,n,sum=0;
for(i=1;i<=5;i++)
{
printf(Enter any number);
scanf(%d,&n);
if(n<0)
continue;
else
sum=sum+n;
}
Printf(sum is.%d,sum;);
}
Output:

Enter any number.10


Enter any number.5

Enter any number.15


Enter any number.25
Enter any number.-10
Enter any number.50
Sum is105
goto statement:

This statement does not require any condition.


This statement passes control any where the program
ie., control is transferred to another part of program without testing the application.

Syntax:
goto label;

Eg:

#include<stdio.h>
#include<conio.h>
void main()
{
int x;
printf(Enter a number);
scanf(%d,&x);
{
if(x%2==0)
{

goto even;
}
else
{
goto odd;
even;
printf(number is even number);
return;
odd:
}
printf(number is odd);
}
}

Output:

Enter a number 5
number is odd

Difference between Break and Continuous statement:


Break
1. Break statement takes the control to
the outside of the loop.
2. It is also used in switch statement
3. Always associated with if condition
in loops

Continuous
1. Continue statement takes the
control to the beginning of the loop.
2. This can be used only in loop
statements.
3. This is also associated with if
condition.

Nested switch() case:

The inner switch() statement can be part outer switch() statement.


The inner and outer switch() case constants.
UNIT III ARRAYS AND STRINGS 9
Arrays Initialization Declaration One dimensional and Two dimensional arrays. StringString
operations String Arrays. Simple programs- sorting- searching matrix operations.

Explain String handling function in C


Handling of Character Strings:

The group of charcter,digits and symbols enclosed with in a quotation marks are called string.
Header file used is string.h Null charater(\0) is used to mark the end of the string.
Eg:
Char name[]={b,t,o,j,\0};

Declaring & Initializing string


String variable is always declared as an array.
Syntax:
char string_name[size];
Eg:
char city[10];

Example:
char city[9]=New York;
char city[ ]=New York;

compiler automatically supplies a null


character(\0) at the end of the string
Reading a string:
Scanf function can be used with %s format specification to read a string.
Eg:
char name[15];
scanf(%s,name);
& is not necessary for string variable.
Scanf terminates its input on the first white
space.
Writing a string
Prinf function with %s format to print
strings to the screen.
eg:
printf(%s,name);

Explain in detail about string handling functions


String standard functions:
Strlen (s)

Strlen returns the length of a string

.
Strcmp ()

compares two strings and returns an


integer indicating the difference
between the strings.
If the strings match, then the number
returned is 0.

Strcat()

Strcat combines two strings

Strcpy ()

Strcpy copies one string to another

strlwr()

Used to convert string to lower case

strupr()

Used to convert string to uppercase

strdup()

Used to duplicate a string.

strrev()

Used to reverse a string

strchr()

Determines the first occurrence of a


given character in a string

strrchr()

Determines the last occurrence of a


given character in a string

Strnset()

Sets n characters of string to a given


character

Strrchr()

Finds last occurrence of given character


in string

strcmpi

Compares two strings, non-case


sensitive

strlen() function:
This function is used to count and return the number of characters present in a string.

Syntax:
Var=strlen(string);

#include <stdio.h>
#include <string.h>
int main()
{
char name[]=INDIA;
int num;
printf(enter your name\n");
num = strlen(name);
printf(The length of the string is %d,num);
return 0;

}
Output
The length of the string is 5
Strcpy()
This function is used to copy the contents of one string to another string.

Syntax:

strcpy(string1,string2);

string1-destination string.
String2-source string.
#include <stdio.h>
#include <string.h>
int main ()
{
char source[10]=hello;
char target[10];
strcpy (target,source);
printf (The Target string is:%s,target);
return 0;
}
Output

The Target string is hello


strcat() function
This function is used to concatenate or combine two strings together and forms a new
concatenated string.
Syntax:

strcat(string1,string2);
string2 is combined with string1 and it removes the null character(\0) of string1 and
places string from there.
#include<stdio.h>
#include<string.h>
void main()
{
char name1[ ]=Computer;
char name2[10]=science;
strcat(name1,name2);
printf(The concatenated string is%s,name1);
printf(name2 is%s,name2);
}
Output:
The cancatenated string is Computerscience
name2 is science

strcmp()
This function is used to campares two string and find whether are same or not.
Syntax:

strcmp(string1,string2);

#include<stdio.h>
#include<string.h>
void main()
{
char name1[ ]=vino;
char name2[ ]=mano;
int a,b,c;
a=strcmp(name1,vino);
b=strcmp(name1,name2);
c=strcmp(name1,vino mano);
printf(/n %d %d %d,a,b,c);
}
output
If two string are identical strcmp() returns a value zero.If they are not identical it returns
the numeric difference between the first non-matching character.

strrev()
This function is used to reverse a string.
Syntax:

strrev(string);

#include<stdio.h>
#include<string.h>
void main()
{
char city[];
char rcity[];
printf(enter the city\n);
gets(city);
printf(\nThe reversed string is %s, strrev(city));
}
Output
enter the city
chennai
The reversed string is iannehc

ENUMERATED DATA TYPES


Enumerated data type variables can only assume values which have been previously
declared.
Syntax:
enum tagname
{
enum1;
enum2;

Eg:
enum n;

enum operator
};

{
plus;
minus;
multiplication;
division;
};
enum operator opr1,opr2;
opr1=plus;
opr2=division;

By default the values in the enum are assigned ffom 0.In the above mentioned
example,plus=0,minus=1 and so on.
#include<stdio.h>
#include<string.h>
void main()
{
enum week{sunday = 0,Monday,Tuesday,Wednesday,Thursday,friday}
clrscr();
printf(mon=%d\n,Monday);
printf(tue=%d\n,tuesday);
printf(fri=%d\n,friday);
getch();
}
Output:
Mon=1
Tue=2
Fri=5
************************************************************************
Explain in detail about Array
ARRAYS

Arrays are data structures which hold multiple variables of the same data type. Consider the
case where a programmer needs to keep track of a number of people within an organization. So
far, our initial attempt will be

to create a specific variable for each user. This might look like,

int name1 = 101;


int name2 = 232;
int name3 = 231;

Arrays, like other variables in C, must be declared before they can be used. The replacement
of the above example using arrays looks like,

int names[4];
names[0] = 101;
names[1] = 232;
names[2] = 231;
names[3] = 0;

We created an array called names, which has space for four integer variables. You may also
see that we stored 0 in the last space of the array. This is a common technique used by C
programmers to signify the end of an array.

Arrays have the following syntax, using square brackets to access each indexed value (called
an element).

x[i]
so that x[5] refers to the sixth element in an array called x. In C, array elements start with 0.
Assigning values to
array elements is done by,

x[10] = g;
and assigning array elements to a variable is done by,
g = x[10];
In the following example, a character based array named word is declared, and each element
is assigned a character. The last element is filled with a zero value, to signify the end of the
character string (in C, there is no
string type, so character based arrays are used to hold strings). A printf statement is then used to
print out all
elements of the array.

/* Introducing array's, 2 */
#include <stdio.h>
main()
{
char word[20];
word[0] = 'H';
word[1] = 'e';
word[2] = 'l';
word[3] = 'l';
word[4] = 'o';
word[5] = 0;
printf("The contents of word[] is -->%s\n", word );
}
DECLARING ARRAYS

Arrays may consist of any of the valid data types. Arrays are declared along with all other
variables in the declaration section of the program.

/* Introducing array's */
#include <stdio.h>
main()
{
int numbers[100];
float averages[20];
numbers[2] = 10;
--numbers[2];
printf("The 3rd element of array numbers is %d\n", numbers[2]);

}
The above program declares two arrays, assigns 10 to the value of the 3rd element of
array numbers, decrements this value ( --numbers[2] ), and finally prints the value. The number
of elements that each array is to have is
included inside the square brackets

ASSIGNING INITIAL VALUES TO ARRAYS

The declaration is preceded by the word static. The initial values are enclosed in braces, eg,
Example:

#include <stdio.h>
main()
{
int x;
static int values[] = { 1,2,3,4,5,6,7,8,9 };

static char word[] = { 'H','e','l','l','o' };


for( x = 0; x < 9; ++x )
printf("Values [%d] is %d\n", x, values[x]);
}
The previous program declares two arrays, values and word. Note that inside the square
brackets there is no variable to indicate how big the array is to be. In this case, C initializes the
array to the number of elements that appear within the initialize braces. So values consist of 9
elements (numbered 0 to 8) and the char array word has 5 elements.

MULTI DIMENSIONED ARRAYS


Multi-dimensioned arrays have two or more index values which specify the element in the
array.

multi[i][j]
In the above example, the first index value i specifies a row index, whilst j specifies a
column index.

DECLARATION

int
m1[10][10];
static int m2[2][2] = { {0,1}, {2,3} };

sum = m1[i][j] + m2[k][l];

{ 0, 1 },

{ 2, 3 }

Remember that arrays are split up into row and columns. The first is the row, the second
is the column. Looking at the initial values assigned to m2, they are,
m2[0][0] = 0
m2[0][1] = 1
m2[1][0] = 2
m2[1][1] = 3

Example:

#include <stdio.h>
#include<conio.h>
main()
{

static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} };


int row, column, sum;
clrscr();
sum = 0;
for( row = 0; row < 4; row++ )
for( column = 0; column < 3; column++ )
sum = sum + m[row][column];
printf("The total is %d\n", sum );
getch();

CHARACTER ARRAYS [STRINGS]


Consider the following program,

#include <stdio.h>
#include<conio.h>
main()
{
static char name1[] = {'H','e','l','l','o'};
static char name2[] = "Hello";
clrscr();
printf("%s\n", name1);
printf("%s\n", name2);
getch();
}

Output: Hello
The difference between the two arrays is that name2 has a null placed at the end of the
string, ie, in name2[5], whilst name1 has not. To insert a null at the end of the name1 array, the
initialization can be changed to,

static char name1[] = {'H','e','l','l','o','\0'};

Consider the following program, which initializes the contents of the character based array word
during the program, using the function strcpy, which necessitates using the include file string.h

Example:
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char word[20];
strcpy( word, "hi there." );
printf("%s\n", word );
getch();
}

Output:

hi there

UNIT IV FUNCTIONS AND POINTERS


Function definition of function Declaration of function Pass by value Pass by reference
Recursion Pointers - Definition Initialization Pointers arithmetic Pointers and arraysExample
Problems.

Explain different types of functions with suitable example


Functions
Function is a set of instruction that are used to perform specified tasks which repeatedly
occurs in the main program.
Functions are 2 types,
Pre defined functions.
User defined functions.

User defined functions

The function defined by the users according to their requirements.


Written by the programmer to perform a particular task, that is repeatedly used in main
program.
Helpful to breakdown a large program in to a number of smaller programs.
Debugging, testing and maintenance becomes easier.
Advantages of user defined function:
Length of the source program can be reduced.
Easy to locate and debug errors.
It can be used in many other source program whenever necessary.
Avoid coding of repeated programming.

Elements of user defined function:


Function definition.
Function declaration.
Function call.

Function definition:
Defining its element and characteristics.

Function Declaration:
Like the normal variables in a program,the function can also be declared before they
defined and invoked.

Syntax:
datatype func_name(parameter list)
{
Variable declaration;
Body of the function;
}.
Func_name-name of function.
Parameter list-list of parameters that the
function can convey.
Eg:
int add(int x,int y)
{
}

Function call:
The function can be called by simply specifying the name of the function,return value
and the parameters if presence.

func_name();
func_name(parameter);
return value=func_name(parameter);
Parameter:
Parameters provide the data communication between the calling function and called function.

There are 2 types of parameters:


Actual parameter:these are the parameters transferred from the calling function (main
program) to the called program(function).
Formal parameter: these are the parameters transferred from the called function (
program) to the calling program( mainfunction).

Example:
main()
{

fun(a,b);
}
fun(x,y)

{
}
a &b are actual parameter
x & y are formal parameter
Types of variable
LOCAL AND GLOBAL VARIABLES:
There are two kinds of varibles.
1. Local variable.
2. Global variables.

1. Local variable:
The local variable are defined within the body of the function.these variables are
defined local to that function only or block only,other function cannot access these variables.
Eg:
Value(int a,int b)
{
int c,d;
}
c and d local variables.
2. Global variables.
Global variables are defined outside the main() function.multiple function can use
these variables.

Eg:
int m=5,n=10;
main()
{
int a,b;
}
m and n are global variables.
Program to demonstrate local and global variables
#include<stdio.h>
#include<conio.h>
int i=0;
void f1();
i=o;
clrscr();
printf(value of i in main:%d\n,i);
f1();
printf(value of i after call:%d\n,i);
getch();
}
Void f1(void)
{

int k;
i=50;
}
Output:
Value of i in main:0
Value of i after call:50

RETURN statement
The return statement may or may not send back any values to main program.
The return statement can take the form:
Syntax:
return;
or
return(exp);
Eg:
if(x <= 0)
return(0);
else
return(1);
FUNCTION calling:
A function can be called by simply using the function name in the statement.

Eg:
main()
{
message();
printf(main message);
}
message()
{
printf(function message\n);
}
Explain different function prototypes:
Function prototypes:
The functions are classified into the following types depending on the arguments are
present or not and whether the value is returned or not. These are also called function prototypes.
A function prototype declaration consists of the function return type, name and
arguments list.
Prototype:
Function with no arguments & no return value.
Function with arguments & no return value.
Function no arguments & with return value.
Function with arguments & return value.

Function with No Arguments and No Return Values


In this prototype, no data transfer takes place between the calling function and the called
function. i.e.. the called program does not receive any data from the calling program and
does not send back any value to the calling program.

Main()

func1()

..

Func1();

..

..

..
}

/* Program to addition of two numbers */


#include<stdio.h>
main()
{
void add(void);
add() ;

/* add is a function with no arguments */


}
void add()
{
int a, b, c ;
/* Local definitions */
printf("Enter two numbers...");
scanf("%d %d",&a, &b) ;
c=a +b:
printf("Sum is...%d",c) ;
}
OUTPUT
Enter two numbers...10 20
Sum is...30

Function with Arguments and No Return Values


In this prototype, data is transferred from calling funtion to called function but dont have
return values.

Main()

func1(x,y)

..

Func1(a.b);
..
..
}

main()
{

void add(int,int);
int a,b;
printf(enter the values);
scanf(%d %d,&a,&b);
add(a,b) ;
}
void add(int x,int y)
{
int z;

..
}

z=x +y:
printf(the sum is%d:,z);
}

Function with no Arguments with return Values

In this prototype, one way data communication takes place. i.e the calling program cannot
pass any arguments to called program but, the called program may send return value to the
calling program.
Main()

data_type func1(x,y)

..

func1();

return(z);

..
..
}

void main()
{
int add();
int c;

c=add();
printf(the sum %d,c);
}
int add()
{
int x,y,z;
printf(enter the values);
scanf(%d %d,&x,&y);
z=x+y;
return(z);
}

Function with arguments and return


Value
In this prototype, the data is transferred between the calling function and called function.
Main()

data_type func1(x,y)

..

Func1(a.b);

return(z);

..

..
}
void main()
{
int add(int,int);
int a,b,c;
printf(enter the values);
scanf(%d %d,&a,&b);
c=add(a,b);
printf(the result %d,c);
}
/* a=5,b=3; */
int add(int x,int y)
{
int z=x+y;
return(z);
}
****************************************************************
Explain in detail about parameter passing methods
Or
Explain in detail about call by value and call by reference

Parameter passing methods

Call by value
Call by reference.

1. Call by value
It copies the value of actual parameter in to formal parameter.
Change of formal parameter cannot affect the actual parameter.
void main()
int square(int x);
main()
{
int n=3;
printf(the square %d,n,square(n));
}

int square(int)
{
x=x*x;
return(x);
}

Output:
the square 9

Call by reference
The address of arguments are copied into the parameter inside the function, address is
used to access the actual argument.
void change(int *a,int *b)
main()
{
int x=5,y=10;
printf(values of x,y %d%d,x,y);
change(&x,&y);
printf(after interchange %d%d,x,y);
}

void change(int *a,int*b)


{
int t;
t=*a;
*a=*b;
*b=t;

}
output:
values of x,y 5 10
after interchange 10 5

Recursion
Recursion is the process of calling the same function itself again and again until some
condition is satisfied.
#include<stdio.h>
#include<conio.h>
main()
{
int a;
printf(enter the value);
scanf(%d,&a);
printf(the factorial is %d,fac(a));
}

fac(int x)
int n;
{

if(x==1)
return(1);
else
n=x*fac(x-1);
return(n);
}

POINTERS
1. Definition
A pointer is a variable which contains the address in memory of another variable. We can
have a pointer to any variable type.
The unary or monadic operator & gives the ``address of a variable''.
The indirection or dereference operator * gives the ``contents of an object pointed to by a
pointer''.
Declaring a pointer
Declaring pointers can be very confusing and difficult at times. To declare pointer
variable we need to use * operator before the variable identifier and after data type . Pointer can
only point to variable of the same data type.
Datatype * pointer-name;
Ex:
int *pointer;
sample Example program:
#include<stdio.h>

main()
{
int sno=89;
printf(address of sno=%u,&sno);
printf(value of sno=%u,&sno);
}
Output:
address of sno=3932
value of sno=89
Accessing a Variable Through its Pointer

The indirection operator (*) is used to access the value of a variable by its ptr

* can be remembered as value at address

int n = *p // int *p = &quantity is done

int n = *&quantity // is = quantity

Syntax:
*pointer variable;
where

* - indirection operator
pointer variable - declared pointer variable

Program:
#include<stdio.h>
main()
{
int a;
int *b;

a=100;
b=&a;
printf("The content of the pointer b=%d\n", *b);
}

Output:
The content of the pointer b=100
Null pointer
A pointer is said to be null pointer when its right value is 0.
A null pointer can never point to valid data.
For checking a pointer, if it is assigned to 0,then it is null pointer and is not valid.
Example: int *a;
int *b;
b=a=0;
Hence a and b become null pointers after the integer value of 0 is assigned to them.
Pointer to pointer :
Pointer is a variable that contains the address of the another variable.
Similary another pointer variable can store the address of this pointer variable.so we can say this
is a pointer to pointer.
Ex:
#include<stdio.h>
main()

{
int a=22;
int *b;
int **c;
b=&a;
c=&b;
printf(\n value of a is %d,a);
printf (\n value of a is %d,*(&a));
printf (\n value of a is %d,*b);
printf (\n value of a is %d,**c);
printf (\n value of b and address of a = %u,b);
printf (\n value of c and address of b = %u,c);
printf (\n address of a = %u,&a);
printf (\n address of b = %u,&b);
printf (\n address of a = %u,*c);

printf (\n address of b = %u,&b);


printf (\n address of b = %u,c);
printf (\n address of c = %u,&c);
}
Output:

Value of a is 22
Value of a is 22
Value of a is 22
Value of a is 22
value of b and address of a =2000
value of c and address of b =4000
address of a =2000
address of b = 4000
address of a =2000
address of b =4000
address of b=4000
address of c =6000

******************************************************************
Explain in detail about Array and Pointer:
Array and pointer:
When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of array in contiguous memory location. The base addresses
the location of the first element (index 0) of the array. The compiler also defines the array name
as a constant pointer to the first element. Suppose we declare an array x as follows:
static int x[5] = {1,2,3,4,5};
Suppose the base address of x is 1000and assuming that each integer requires twobytes,

Elements

x[0]

x[1]

x[2]

x[3]

x[4]

value
1

Address
1004

1000 1002
1006

1008

The name x is defined as a constant pointer pointing to the first element x[0] and
therefore value of x is 1000, the location where x[0] is stored . That is ,
x = &x[0] =1000

Accessing array elements using the pointer


Pointers can be used to manipulate two-dimensional array as well. An element in a two
dimensional array can be represented by the pointer expression as follows:
*(*(a+i)+j) or *(*(p+i)+j).
The base address of the array a is &a[0][0] and starting at this address, the compiler
allocates contiguous space for all the elements, row-wise. That is, the first element of the
second row is placed immediately after the last element of the first row, and so on.
12345
A program using Pointers to compute the sum of all elements stored in an array is
presented below:
POINTERS IN ONE-DIMENSONAL ARRAY

main ( )

{
int *p, sum , i
static int x[5] = {5,9,6,3,7};
i = 0;
p = x;
sum = 0;
printf(Element Value Address \n\n);
while(i < 5)
{
printf( x[%d] %d %u\n, i, *p, p);
sum = sum + *p;
i++, p++;
}
printf(\n Sum = %d \n, sum);
printf(\n &x[0] = %u \n, &x[0]);
printf(\n p = %u \n, p);
}
Output
Element Value Address
X[0] 5 166
X[1] 9 168

X[2] 6 170
X[3] 3 172
X[4] 7 174
Sum = 55
&x[0] = 166
p = 176

UNIT V STRUCTURES AND UNIONS


Introduction need for structure data type structure definition Structure declaration
Structure
within a structure - Union - Programs using structures and Unions Storage classes, Preprocessor
directives.
Explain in detail about structure
STRUCTURES
1. Structure Definition
2. Rules for declaring a structure
3. Array Vs Structure:
4. Accessing structure elements
5. Structure Initialization
1. STRUCTURE DEFINITION
The structure can be declared with the keyword struct following the name and opening
brace with data elements of different type then closing brace with semicolon.
The general format of a structure definition is as follows:
struct structure _ name
{
structure_element 1;
structure_element 2;
structure_element 3;

--------- ------------- ----};


struct structure_name v1,v2vn;
v1,v2.vn are structure variable.
Example:
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
Struct book b1,b2,b3;

2. Rules for declaring a structure

The template is terminated with a semicolon.


While the entire definition is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
The tag name such as book _ bank can be used to declare structure variables of its type,
later in the program.
ARRAY VS STRUCTURE

Array

Structure

An array is a collection of related data

Structure can

elements of same type.

have elements of different types.

An array is derived data type

structure is a user-defined one

Any array behaves like a built-in data type

It must be declared and defined

An array can be increased or decreased

A structure element can be added if


necessary.

3. Accessing structure elements


After declaring the structure type, variables and members, the member of the structure can be
accessed by using the structure variable along with the dot(.) operator.
struct std
{
int no;
char name[10];
int marks;
};
struct std s;

for accessing the structure members from the above example.

s.no;

s.name;

s.marks;

where s is the structure variable

STRUCTURE INITIALIZATION

Like any other data type, a structure variable can be initialized at compile time.
main()
{
struct
{
int weight;
float height;
}
student ={60, 180.75};

}
This assigns the value 60 to student. weight and 180.75 to student. height. There is a oneto-one correspondence between the members and their initializing values.

struct st _ record
{

int weight;
float height;
};
main()
{

struct st_record student1 ={60, 180.75};


struct st_record student2 ={53, 170.60};

}
C language does not permit the initialization of individual structure member within the
template. The initialization must be done only in the declaration of the actual variables.

#include<stdio.h>
#include<conio.h>
struct student
{
int rno;

char name[20];
int m1;
int m2;
int m3;
int total;
float avg;
}struct std s;
void main()
{

printf("Enter the roll no,name,mark1,mark2,mark3);


scanf("%d%s%d%d%d",&s.rno,&sk.name,&s.m1,&s.m2,s.m3);
total=s.m1+s.m2+s.m3;
avg=total/3;
printf("%d\t%s\t%f\t%f\t",s.no,s.name,total,avg);
}

OUTPUT
Enter the roll no,name,mark1,mark2,mark3

1 raja 99 95 97
1 raja 291.00 97.00

******************************************************************************

Union:
Union is user defined data type used to stored data under unique variable name at single
me

memory location.
Union is similar to that of stucture. Syntax of union is similar to stucture. But the major
Difference between structure and union is 'storage.'
In structures, each member has its own storage location, whereas all the members of union
use the same location. Union contains many members of different types, it can handle only
one member at a time. To declare union data type, 'union' keyword is used. Union holds value
for one data type which requires larger storage among their members.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
Example:
union techno
{

int comp_id;
char nm;
float sal;
}tch;

In above example, it declares tch variable of type union. The union contains three members
as data type of int, char, float. We can use only one of them at a time.
Memory allocation:

Fig : Memory allocation for union


To access union members, we can use the following syntax.
tch.comp_id
tch.nm
tch.sal
Program :
#include <stdio.h>
#include <conio.h>
union techno
{
int a;
char b[2];
};
void main()

{
clrscr();
union name c;
c.a=99
printf("\n\t c.a value is :%d\n ",c.a);
printf("\n\t c.b[0] value is :%d\n ",c.b[0]);
printf("\n\t c.b[1] value is :%d\n ",c.b[1]);
getch();
}
Output :
c.a value is :99
c.b[0] value is :0
c.b[1] value is :1

*************************************************************************
Explain the different types of storage classes

Storage Class

A storage class defines the scope (visibility) and life time of variables and/or functions within a C Prog
There are following storage classes which can be used in a C Program

auto
register
static
extern

auto - Storage Class


auto is the default storage class for all local variables.

{
int Count;
auto int Month;
}

The example above defines two variables with the same storage class. auto can only be used within fun
local variables.

register - Storage Class

register is used to define local variables that should be stored in a register instead of RAM. This means
variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator
(as it does not have a memory location).
{
register int Miles;
}

Register should only be used for variables that require quick access - such as counters. It should also be
defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored
register - depending on hardware and implementation restrictions.

static - Storage Class

static is the default storage class for global variables. The two variables below (count and road) both ha
storage class.
static int Count;
int Road;

{
printf("%d\n", Road);
}

static variables can be 'seen' within all functions in this source file. At link time, the static variables defined her
be seen by the object modules that are brought in.

static can also be defined within a function. If this is done the variable is initalised at run time but is not reinita
the function is called. This inside a function static variable retains its value during vairous calls.
void func(void);

static count=10; /* Global variable - static is the default */

main()
{
while (count--)
{
func();
}

void func( void )


{
static i = 5;
i++;

printf("i is %d and count is %d\n", i, count);


}

This will produce following result

i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

Extern - Storage Class

Extern is used to give a reference of a global variable that is visible to ALL the program files
When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a stor
location that has been previously defined.
When you have multiple files and you define a global variable or function which will be used in other f
then extern will be used in another file to give reference of defined variable or function. Just for unders
extern is used to decalre a global variable or function in another files.
File 1: main.c
int count=5;

main()
{
write_extern();
}

File 2: write.c
void write_extern(void);

extern int count;

void write_extern(void)
{
printf("count is %i\n", count);
}

Here extern keyword is being used to declare count in another file.


Now compile these two files as follows
gcc main.c write.c -o write

This fill produce write program which can be executed to produce result.
Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value

*************************************************************

Discuss about preprocessor in C


The C Preprocessor
As the name implies, it is program that processes our source program before compilation. The
preprocessor operates under the following preprocessor directives.
File Inclusion
Macro Substitution
Conditional inclusion
1. File Inclusion This is used to include an external file, which contains functions or some
other macro definitions to our source program, so we need not rewrite functions and
macros in our source program
Syntax
#include <filename.h>
#include "filename.h"
filename.h is the name of the file,that can be included in our source program.
Eg:
#include <stdio.h>
#include stdio.h
1. Macro Substitutions This is used to define symbolic contants in the source program.
The identifier or string or integer defined is replaced by macro substitution.
Syntax:
#define identifier string/integer

The preprocessor accomplish the task specified in #define statement.


i) simple macros
This is commonly used to define symbolic constants
Example:
#define

age

20

#define

CITY

#define

9.8

#define

10

CHENNAI

The #define A 10 macro substitutes A with 10 in all occurrences in the source program.
ii) Argumented macros
The Argumented macros are used to define more complex and useful form of
replacements in the source program.
Syntax:
#define identifier (v1 v2 v5.v4)string/integer

iii) Nested macros


The macros defined within another macro called nested macros.
Example:
#define A

#define B A+2

2. Conditional Inclusion:
These are used to control the preprocessor with conditional statements.
Example:
#define op P
main()
{
#ifdef P printf(PENTIUM);
#else printf(CELERON);
#endif
}
The preprocessor directives are,

Directive

Function

#include

Used to include a file.

#define

Used to define symbolic constant

#ifdef

Used to test macro definition

#else

Used to specify alternative in #ifdef

#undef

Used to undefined a macro.

******************************************************************

Вам также может понравиться