0% found this document useful (0 votes)
5 views

C Complete Notes

The document provides an overview of computer fundamentals, including the definition, characteristics, limitations, and basic organization of computers. It discusses the classification of computers based on speed, storage, and price, detailing supercomputers, mainframe computers, minicomputers, and microcomputers. Additionally, it outlines various applications of computers across different sectors such as healthcare, education, and business.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C Complete Notes

The document provides an overview of computer fundamentals, including the definition, characteristics, limitations, and basic organization of computers. It discusses the classification of computers based on speed, storage, and price, detailing supercomputers, mainframe computers, minicomputers, and microcomputers. Additionally, it outlines various applications of computers across different sectors such as healthcare, education, and business.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 132

ADITYA DEGREE COLLEGE, TUNI

Computer Fundamentals and C programming


UNIT-I
General Fundamentals: Introduction to computers: Block diagram of a computer, characteristics
and limitations of computers, applications of computers, types of computers, computer
generations.
Introduction to Algorithms and Programming Languages: Algorithm – Key features of
Algorithms, Flow Charts, Programming Languages – Generations of Programming Languages –
Structured Programming Language- Design and Implementation of Correct, Efficient and
Maintainable Programs.

Define of COMPUTER.

Computer: Computer is an electronic machine that takes instructions and performs mathematical and
logical operations at high speed and output the result.

1. WRITE THE CHARACTERISTICS OF COMPUTERS.


CHARACTERISTICS OF COMPUTERS

1. SPEED: Computers can perform millions of operations per second. The speed of computers is
usually given in nanoseconds and picoseconds, where 1 nanosecond=1x10 -9 seconds and 1 per
second = 1X10-12 seconds.
2. ACCURACY: A computer is a very fast, reliable, and robust electronic device. It always gives
accurate results, provided the correct data and set of instructions are input to it. If the input data
is wrong, then the output will also be erroneous. In computer terminology, this is known as
garbage-in, garbage-out (GIGO).
3. VERSATILE: Versatility is the quality of being flexible. Computers are versatile devices as
they can perform multiple tasks or different nature at the same time. For example, personal
computers (PCs) for home use, for business-oriented tasks, whether forecasting, space
exploration, teaching, railways, banking, medicine etc.
4. ECONOMICAL: Using computers also reduce manpower requirements and leads to an
elegant and efficient way of performing various tasks. Hence, computers save time, energy, and
money.
5. NO IQ: We are making computers intelligent by inducing artificial intelligence (AI) in them;
they still do not have any decision-making abilities of their own. Thus, their IQ level is zero.
They need guidance to perform various tasks.
6. MEMORY: Similar to humans, computers also have memory. The computer stores a large
amount of data and programs in the secondary storage space. Secondary memory is the key for
data storage. For example secondary devices include floppy disks, optical disks (CDs and
DVDs), hard disk drives (HDDs), pen drives, etc.

DADIDFDDFDFD FDFD
Page 1 M.Tech
M.N.V.G.A.DEEPTHI,
ADITYA DEGREE COLLEGE, TUNI

7. AUTOMATION: Being very fast and accurate, computers are automatable devices that can
perform a task without any user intervention. The user just needs to assign the task to the
computer, after which it automatically controls different devices attached to it and executes the
program instruction.
8. DILIGENCE: Unlike humans, computers never get tired of a repetitive task. It can continually
work for hours without creating errors. Even if a large number of executions are needed, each
and every execution requires the same duration, and is executed with the same accuracy.

2. WRITE THE LIMITATIONS OF COMPUTER.(5M)


Limitations of Computer:

1. It reduces the need of people and increases unemployment in society


2. Computer does not work by itself, it requires set of instructions
3. Computer are not intelligent, they have to be instructed about each and every step which they
have to perform
4. Computers cannot take decisions by its self; one has to program the computer to take an
action.
5. Computers, unlike humans cannot learn by experience. They do not have emotions, feelings,
knowledge etc. It does not get tired and keep on doing its tasks.

3. EXPLAIN ABOUT THE BASIC COMPUTER ORGANIZATION.


(OR)
EXPLAIN ABOUT COMPUTER WITH A NEAT BLOCK DIAGRAM
Basically computer performs FOUR major operations

 INPUT UNIT (Accepting data / instructions)


 CPU (Processing)
 STORAGE (Storing data)
 OUTPUT UNIT (Displaying information)

Figure 1: Block diagram of Computer

Page 2

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
INPUT UNIT: It is a combination of input devices by which we give data and instructions to the
computer. Some input devices

1. Keyboard: Keyboard is an input device by which we give input to computer. It is just like
type writer keyboard .It is known as standard input device. The keys in keyboard vary form
101-108.
2. Mouse: Mouse is an input device with which we give input to the computer. The mouse
consists of 2 or 3 buttons. It is mostly used in windows applications. It performs operations
like clicking, double clicking, and dragging e.tc. It is mostly used to select text, access menus
e.tc.
3. Joystick: It is an input device that contains stick to move left, right, back, forward. It is
mostly used in video games to change the direction.
4. Track Ball: Trackball is a pointing device that consists of a ball, which can be rotated by
hand either in clock-wise or anti-clockwise direction. It is mostly used in Medical computers
for body scan, brain scan e.tc
5. Scanners: These are optical devices that use light as a source of input. There are various
types of scanners. They are
 OCR (Optical Character Reader): It is a device that is used to recognize/scan the
characters on a typed document.
 OMR (Optical Mark Reader): It is a device that is used to scan the marks marked
with pencil or pen.
 BCR (Bar Code Reader): It is a device that is used to scan the coded bars on the
product.
 MICR: (Magnetic Ink Character Reader): It is a device that is used to scan the
magnetic ink characters on bank cheques.

CPU (Central Processing Unit): It is known as the heart or “brain” of the computer and is
responsible for processing the information that has been entered into the computer. It contains Main
memory, ALU and control unit.
 Main memory: It stores the data and instructions temporarily.
 ALU: It stands for Arithmetic and Logic Unit that performs Arithmetic Calculations and
Logical Comparisons.
 Control Unit: It manages and controls each and every instruction and directs to concerned
device. It takes care of step-by-step processing of all operations

STORAGE: Storage is an area where we store the data and instructions temporarily or permanently.
It not only stores data and programs but also stores the intermediate results and final results after
processing. Computer has two types of storage areas
1. Primary storage
2. Secondary Storage
Primary storage: primary storage is also known as main memory or primary memory, which is
directly accessible by CPU. It is used to store the data temporarily prior to execution of the
program. It consist two parts. They are

 RAM: RAM stands for Random Access Memory. This is a volatile memory i.e. the
contents will be scratched with the loss of power. The user can read and write from this
memory. So it is also called as Read-Write Memory.

Page 3

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

 ROM: ROM stands for Read Only Memory. The user can read from this memory but he
can’t write. This is a non-volatile memory i.e. the contents will not be scratched with the
loss of power. Generally ROM is used to store system programs developed by the
manufacturers.
Secondary storage: Secondary memory is an area, which is used to store the data permanently.
It is also known as auxiliary memory. Data is stored permanently using devices known as
secondary Storage Devices like Hard disk, Magnetic disk, floppy disk, CD ‘s e.tc

OUTPUT UNIT: It is a combination of output devices by which we get the results from the
computer. Some output devices are Monitor, Printer. Speaker e.tc
1. MONITOR: Monitor is the standard output device. The output that is obtained through
monitor is called visual output and hence monitor is also called VDU (Visual Display Unit).
2. PRINTER: The output that is obtained through Printer is known as printed Output. The
printed output is also known as hard copy.
3. SPEAKER: The output that is obtained through Speaker is known as Audio Output.

4. EXPLAIN ABOUT THE CLASSIFICATION (OR) TYPES OF COMPUTERS.


COMPUTERS ACCORDING TO SPEED, STORAGE & PRICE: computers are classified into
four categories based on their speed, storage and price. They are
1. SUPER COMPUTERS
2. MAINFRAME COMPUTERS
3. MINICOMPUTERS
4. MICRO COMPUTERS

1. SUPER COMPUTERS: Super computers are fastest, powerful &more expensive computers to
process huge amounts of data.
 These computers use parallel processing Technology and perform trillion calculations/
instructions per second.
 These Computers are used for weather forecasting, aircraft design, nuclear research, scientific
applications, controlling industrial unit’s e.tc
 Eg. Cray2, Parma, SX-2, ETA A-10 etc.

Page 4

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

SUPER COMPUTERS IN WORLD


1. Fujitsu Fugaku , JAPAN
2. IBM Summit, USA
3. IBM/Nvidia/Mellanox Sierra, USA
4. Sunway TaihuLight , CHINA

SUPER COMPUTERS IN INDIA


1. PARAM Siddhi – AI
2. PRATYUSH
3. MIHIR

2. MAINFRAME COMPUTERS: The mainframe computers are large type of computers that
provide large amount of storage.
 The main memory capacity is above 256 MB and Speed is about 10 million instructions per
second
 They are very expensive and need a large room with air conditioning.
 It supports multiple processors, for example IBM S/390 supports 50,000 users at same time.
 Mainframe computers mostly acts as servers and Users can access them either by using
Dumb Terminals(having only monitor & keyboard or mouse) or Intelligent Terminals(PC).
 It is used large organizations such as Banks, Universities, Airline Companies, LIC e.tc.
 some examples of mainframe are IBM S/390, Control Data CYBER 176, VAX-8000, IBM-
4300.

3. MINI COMPUTERS: These computers are smaller, cheaper and slower than mainframes. They
are also known as midrange computers

 In these computers processor and storage exist separately.


 The speed of mini computers is about 1 million instructions per second.
 These computers are mainly used scientific , defense applications and act as servers in
network environment,
 The first minicomputer was developed by DEC(Digital Equipment Corporation)
 Some manufactures of mini computers are IBM, Prime Computer, Data General Corporation
 VAX 800, SWIPROS 90X are example of Mini Computers.

Page 5

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

4. MICRO COMPUTERS: These computers are commonly known as PC’s and are smaller &
cheap when compared to others
 It consists of microprocessor chips designed using VLSI (Very Large Scale Integrated)
Technology.
 The speed of these computers is 100 Kilo Instructions per second.
 These computers are mostly used in offices, homes and classrooms e.tc.
 PC, PC-AT,PC-XT are some examples of Micro Computers
 IBM-PC was the first micro computer designed by IBM in 1981
 The PC’s are classified into following categories
 Desktop Computers: It is a PC that is designed to sit on a desk or table. These
machines enable people to do their jobs, play games, and edit photos and videos
e.tc. Desktops can be Horizontal oriented (or) Vertical
 WorkStation Computers: Work stations are specialized single user computers
that have advanced processors, more RAM & Storage capacity. Therefore, they are
expensive and have greater power, processing speed as compared to ordinary PCs.
 Note book (or) laptop computers: These are lightweight computers that weigh
less than 6pounds and are too small to fit easily in a briefcase. They run on battery
or power.
 Handheld pc: HANDHELD PC’s are computing devices that can be fit in a hand
and they are smaller than a laptop computer. A Popular type of hand held
computer is PDA (PERSONAL DIGITAL ASSISTANT) ,used for taking notes,
displaying telephone numbers and addresses
 SMART PHONES: Smartphone is a device that lets you to make telephone calls
and also adds features such as the ability to send and receive e-mail and edit Office
documents. It includes special hardware such as camera, music player, and Keypad
e.tc.

Page 6

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

5. WRITE ABOUT THE APPLICATIONS OR USES OF COMPUTERS?


APPLICATIONS OF COMPUTERS OR USES OF COMPUTERS:

Computers are essential to modern society and are used in HOME, EDUCATION, BANKING,
BUSINESS, INDUSTRY, GOVERNMENT, HEALTH CARE e.tc

The following are some applications of computers where computers are used efficiently

1. Word Processing: It is used to read and write documents. Automatic spell Checking, adding
pictures, clip arts, graphs, charts etc are additional features.

2. Hospitals: computers are used in hospitals to record information about patients,, diagnose
problems, scan body e.tc

3. Astronomy: computers are used in monitoring the spacecrafts, their speed, direction, and fuel
and temperature etc.

4. Travel & Tourism: computers are used in booking tickets of buses, trains, aero planes. They
are used in searching hotels, rooms etc for reserving

5. Industry: computers are used in all kinds of industries like thermal power plants, oil
refineries and chemical industries for process control, CAD (Computer Aided Design), CAM
(Computer Aided Manufacturing).

6. Simulation: It is used in designing air craft models

7. Government: In almost all government offices computers are widely used. They are used for
counting census, maintaining records in income tax offices, storing the data of victims in
police dept.
8. Sports: In sports, computers are used to scoring, live telecasting, and umpiring (replaying)
and to identify the weak players from statistics.

9. Traffic control Systems: Computers are used to control the traffic that instructs the traffic
lights when to change.

10. Weather Forecasting: computers are used in predicting the climatic changes.

11. Online Business: It is used in business to enter orders, calculate costs and print reports. It also
used to keep inventory management, processing payroll etc

12. Retail Business: Computers are used in retail shops to enter orders, calculate costs, and print
receipts. They are also used to keep an inventory of the products available and their complete
description.

13. Legal Systems: Computers are used by lawyers to file and refer cases

14. Desktop publishing: Desktop publishing software enables to create page layouts for books.

Page 7

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

15. Music: It is used to link musical instruments to PC there by enabling computer to generate a
variety of sounds.’

16. Education: Computer is an interactive learning tool for students for learning computational
skills, developing logic, doing science projects e.tc

17. Movies: computers are used in creating effects, animations, cartoons, videos etc

18. Banking: It is used doing online banking, drawing money through ATM’s, checking balance
e.tc
19. Entertainment: Computers are used for playing games, watching movies e.tc

20. Robots: These are computer controlled machines which are used in conditions where humans
cannot work for eg in high temperature & pressure e.tc

6. WRITE THE GENERATIONS OF COMPUTERS.


GENERATIONS OF COMPUTERS
Generation means a particular time period. That is hardware and software technology used in a
particular time period. In general, indicates a state of improvement in the product development
process. According to that Computer generations is classified into five types. They are

1. First Generation(1940-55)
2. Second Generation (1956-1963)
3. Third Generation(1964-1971)
4. Fourth Generation (1971-1989)
5. Fifth Generation (Present and Beyond)
First Generation (1940-1956): Vacuum Tubes

 First-generation computers used a very large number of vacuum tubes for circuitry
 Memory: They used magnetic drums for memory.
 Input: Computer was fed using punched cards and paper tape.
 Output: the output was generated on printouts.
 Programming language: Programmed using machine language, which is the lowest-level
programming language (0’s & 1’s).
 Example: UNIVAC (Universal automatic computer) and ENIAC (Electronic numerical
integrator and calculator.
 Advantages: They were the fastest calculating devices of their time.
 Disadvantages:
 They generated a lot of heat.
 They consumed a lot of electricity.
 They were very bulky in size.
 They were very expensive.
 These computers had limited commercial use because they were difficult to program.

Second Generation (1956-1963): Transistors

 Second-generation computers were manufactured using transistors rather than vacuum tubes.
Page 8

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

 Memory: They used magnetic core technology for memory.


 Input: Computer was fed using punched cards.
 Output: the output was generated on printouts.
 Programming language: Assembly language and high-level languages such as COBOL,
FORTRAN, ALGOL, and SNOBOL were also being developed and programmed.
 Advantages:
 They consumed less electricity
 They were faster, cheaper, smaller, and more reliable than their first generation.
 They could be programmed using assembly language and high-level languages.
 These computers had faster primary memory and a larger secondary memory.

 Disadvantages:
 These are assembled manually.
 Production of computers difficult and expensive.

Third Generation (1964-1971): Integrated Circuits

 Third-generation computers were manufactured using Integrated Circuits rather than


transistors.
 Memory: They used magnetic Disks & store a few tens of megabytes of data per disk drive.
 Input: Computer was fed using Keyboard and mouse.
 Output: the output was generated on monitors (CRT) and printers.
 Programming language: High-level languages such as ANSI- COBOL, ANSI-FORTRAN,
PASCAL, and BASICA were introduced at this time.
 Advantages:
 They were faster than 2nd generation computers and could perform one million
transactions per second.
 They were smaller, cheaper, and more reliable than their predecessors.
 These computers had faster and larger primary memory and secondary storage.
 These are widely used for scientific as well as business applications.
 They can run time sharing operating systems, multi tasking.
 Disadvantages:
 These computers were difficult to maintain.
 They got heated very quickly.

Fourth Generation (1971 – 1989): Micro processors

 The microprocessor launched the fourth generation of computers, with thousands of


integrated circuits built onto a single silicon chip.
 The Intel 4004 chip, developed in 1971, consisted of all the components of the computer
(such as the central processing unit, CPU; memory; I/O controls, etc.) on a single chip.
 Memory: Semiconductor memories that were very fast were used and HDDs also became
cheaper, smaller in size, and larger in capacity.
 Input: Computer was fed using Keyboard.
 Output: the output was generated on monitors (LCD & PROJECTORS) and printers.

Page 9

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

 Operating System: Including MS-DOS, Micro-soft Window, UNIX, and Apple’s operating
system.
 Example: In 1981, IBM introduced the first PC that was specifically meant for the home user,
and in 1984 Apple introduced the Macintosh.
 Advantages:
 They consumed less electricity and generated less heat.
 It leads to, the development of the internet and other distributed systems.
 In this generation MS OFFICE packages were developed with different versions.
 They could be used as general-purpose computers.
 GUIs enabled people to learn to work with computers very easily.
 Networks allowed sharing of resources.
 Disadvantages:
 They were not intelligent systems

Fifth Generation (Present and beyond): Artificial intelligence

 In fifth Generation computers are based on Artificial Intelligence. A.I used in the areas like
Gaming, Expert Systems, Neural Networks and Robotics
 In these computers parallel processing, multiple pipelines, multiple processors are used
 In this period, ULSI (ultra Large Scale Integrated Circuit) were introduced. Superscalar
processors, Vector, Quad Processors were used.
 Portable notebook computers are developed.
 Object Oriented Languages like JAVA suitable for internet programming
 During this period WWW, applications like email, e-commerce were developed
 Quantum computation and nanotechnology changed the phase of computers.
 CRAY1, PARAM 10000 are some examples
=================================================================
Introduction to Algorithms and Programming Languages
7. Write about algorithms?
Algorithm: Algorithm means step-by-step representation of instructions to solve a problem
Characteristics of algorithm:
1. INPUT: It takes one or more data as inputs.
2. OUTPUT: It produces result
3. DEFINITENESS: Each instruction must be clear
4. EFFECTIVENESS: Instructions must be simple and carried out in a finite time.
5. FINITENESS: It should be close to the solution.
6. UNAMBIGUOUS: No confusions in algorithm.
7. NO REPETITIONS: Instructions should not repeat in algorithm.
Example: Algorithm to add two numbers.
START

Page 10

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Step1: Input two numbers into A, B


Step2: Add A, B and store the result in SUM
Step3: Output SUM.
STOP
Control structures used in Algorithms:
The control structures specify the flow of data. Algorithm uses three control structures. They are

1. Sequence structure
2. Decision making (or) conditional structure
3. Repetition (or) Looping structure

1. SEQUENCE: In this structure, the instructions are executed sequentially one after the another.
Example: Algorithm to add two numbers.
START
Step1: Input two numbers into A, B
Step2: Add A, B and store the result in SUM
Step3: Output SUM.
STOP
2. DECISION MAKING OR CONDITIONAL: In this structure the instructions are executed
basing on the condition. Branching means jumping from one Instruction to another Instruction.
Example:
START
Step 1: Input two numbers, A,B
Step 2: if A > B then.
Print A
Else
Print B
STOP
Looping (or) Repetition: Looping means repetition of instructions until condition is satisfied.
Example:
START
Step 1: i=1
Step 2: Print i
Step 3: i = i +1
Step 4: if i <=5 then Goto step 2
STOP

8. Write about Flowcharts?


Flowchart:
The graphical (or) pictorial representation of instructions to solve a problem is called Flow Chart.
Flowcharts are used in analyzing, designing, documenting or managing a program.

S.No Shape/symbol Name Description

Page 11

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

1 Oval Start / stop

2 Parallelogram Input/output statements

3 Rectangle Process /assignment statements

4 Rhombus Decision making/ conditions

5 Arrows Data flow lines

6 Connector Labels

7 Cylinder Statements to Store data on storage

Statements to Store data on the


8 Magnetic tape
magnetic tapes

Advantages/Benefits/uses of flowcharts:
1. Communication: Flowcharts are better way of communicating the logic.
2. Effective analysis: With the help of flowchart, problem can be analyzed
3. Proper documentation: Program flowcharts serve as good program documentation.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis
and program development.

Page 12

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

5. Debugging & Maintenance: The flowchart helps in debugging. The maintenance of


program becomes easy with the help of flowchart.
Disadvantages:
1. Drawing flow charts is a time-consuming activity.
2. Flow charts for complex programs becomes complex and clumsy
3. A little bit of alteration in a solution may require re-drawing of flow chart..
4. There are no well-defined standard rules in flowcharts

9. Explain different types of Programming Languages: (Or) Explain about the


Generations of Programming Languages
A programming Language is a computer language that establishes communication between user and
computer. It contains computations performed by the computer.
Generally there are five generations of programming languages. They are

First Generation:
1. Machine language is a low level programming language that is understandable by computer.
2. In this the commands and data are expressed in the form of 0’s and 1’s.
3. It is also known as Binary language or low level language.
4. It is machine dependent language i.e. program written in one computer could not work on
another computer.
Advantage:
1. Execution is very fast
Disadvantage:
1. Difficult to learn
2. Error correction is difficult

Second Generation:
1. Assembly Language Assembly language is a second generation language in which there are
certain codes for certain instructions.
2. These codes are known as mnemonic codes or Opposes. Example: ADD, CMP, MUL etc
3. A statement in assembly language consists of a label, an operation code and one or more
operands.
Example:
Mov AX,4
Mov BX,6
ADD AX, BX
4. Program written in assembly language is converted into machine language using a translator
program known as Assembler.

Page 13

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Advantages: Disadvantages
 Error detection and correction is  Machine dependent
easy  Programmer should have good knowledge in
 It is easy to modify hardware.

Third Generation:
1. High-level Language High level languages are just like English type language that follows
certain rules and regulations called Syntax & Semantics.
2. These languages are discovered during 1960 s-1970s and are designed to create user friendly
environment. Eg: BASIC, COBOL, FORTRAN,C, C++, JAVA etc
3. This language uses compiler (or) interpreter to convert High language into Machine
Language.
Advantage: Disadvantage:
 Machine independent  Code may not be optimized
 It is easy to detect and correct errors
 Easier to write and understand

Page 14

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Fourth Generation:
1. Very High-level Languages Fourth Generation Languages are non-procedural languages
which specify what is to be done rather than how to do.
2. The Example of 4GL is query language (SQL) that takes request and provides information
from database.
Advantage:
1. Easier to write and learn
2. Instructions are written in English-Like sentences
3. Code is easier to maintain.
Fifth Generation:
1. Constraint and logic Languages 5GL are centered on problem solving using constraints.
2. The constraint based and logic programming languages are a part of fifth Generation
Languages.
3. 5GLs are widely uses artificial intelligence, which makes computer think like human brain.
4. These languages contain visual tools.
5. Examples of 5GL: Prolog, Mercury, Lisp, KL-ONE etc.
=====================================================
10. Explain about Software or Program Development process?
Or
Write about Design and Implementation of Correct, Efficient and Maintainable
Programs.

 The program or software development process involves several phases to design and develop
correct, efficient and maintainable programs.
 Each phase performs certain well-defined task.

Phases in software development process:


1. Requirement analysis
2. Design
3. Implementation (coding)
4. Testing
5. Software Deployment
(training & support)
6. Maintenance

Page 15

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

1. Requirement analysis: In this phase user requirements are gathered and analyzed. The scope is
defined and feasibility study is conducted. During this phase Hardware & Software
Requirements, are identified and documented.
2. Design: The Document prepared in previous phase acts as input to this phase. In this phase, plan
of actions are made and the programs are broken into modules. Algorithms or flowcharts are
designed for each module.
3. Implementation (coding): In this phase, the appropriate language is selected and the designed
algorithms or flowcharts are converted into program code. This phase is also known as coding
phase.
4. Testing: During this phase, the developed software is tested and modules are integrated. Testing
is performed to ensure whether the developed software is working according to user requirements
or not.
5. Software Deployment (training & support): after testing the software or the program is
approved by users and then installed. During this phase users are trained on the developed
software.
6. Maintenance: Maintenance and enhancements are ongoing activities. It involves Backup &
Recovery Procedures e.tc. To rebuilt software then same steps are repeated from beginning the
following diagram shows the cycle of events involved in Software or Program Development
Cycle

11. What is structured programming language? Explain it briefly.

Structured programming language:

1. The concept of Structured programming also referred to as modular programming, was first
suggested by the mathematicians Corrado Bohm & Giuseppe Jacopinni.
2. It is basically a subset of procedural programming that enforces logical structure on the
program to make easy to understand.
3. It follows Top-down approach design model, in which the main task is divided into number
of sub tasks and each sub tasks can be further divided into simpler task. Each sub task is
known as function or procedure.

Page 16

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

4. Examples of structured programming languages ALGOL, Pascal, PL/I, Ada, C, etc. are
Structured programming supports the basic structures like sequential, selective, looping & branching,
nesting.
Sequence: In this structure the instructions are executed sequentially one after another sequentially.
The next instruction to be executed automatically follows the given instruction.
Example:
START
Step1: Input two numbers, A,B
Step2: Add A,B and store the result in C
Step3. Output C.
STOP
Selection: In this structure the instructions are executed basing on the condition.
Example:
START
Step1: Read N
Step2: if (N%2 = = 0) then,
Print “even”
else
Print “odd”
STOP
Looping (or) Repetition: Looping means repetition of instructions. Every loop contains initial value,
condition and increment/decrement.
Example:
Start
Step1: i=1
Step2: Print i
Step3: i=i+1
Step4: if i <=5 then Goto step2
STOP
Nesting: A loop within a loop is known as Nesting.
Example:
Start
Step1: read A,B,C
Step2: if ((A>B) && (A>C)) then,
Print “A is biggest number”
Page 17

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

else
if (B>C) then,
Print “B is biggest number”
else
Print “C is biggest number”
end-if
end-if
STOP
Advantages:
1. It supports procedures and modularization
2. Structured program can be written in less time than an unstructured program.
3. It is easy to debug.
4. It is easy to understand and modify
5. It is easily portable.
Disadvantages:
1. It doesn’t supports writing complex programs.
2. It totally based on one processor.
3. It doesn’t supports data-oriented

Page 18

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Unit-II

Introduction to C: Introduction – Structure of C Program – Writing the first C Program – File


used in C Program – Compiling and Executing C Programs – Using Comments –
Tokens: Keywords – Identifiers – Basic Data Types in C – Variables – Constants – I/O
Statements in C- Operators in C- Programming Examples.
Decision Control and Looping Statements: Introduction to Decision Control Statements–
Conditional Branching Statements – Iterative Statements – Nested Loops – Break and Continue
Statement – Goto Statement
Introduction to C
1. Explain the history of C or taxonomy of C or introduction of c language.

1. In 1960’s ALGOL was introduced for development of structured programming concepts.


2. At this time programming languages are used for special purpose, for example
 COBOL (Common Business Oriented language) is used for business applications
 FORTRAN (Formula Translation) is used for Scientific &
Engineering Applications.
3. At this stage people started thinking that instead of using many
languages why not we use single language that serves all the
applications.
4. Therefore an International Committee came out with a language
called CPL (Combined Programming Language). This CPL is
hard to learn.
5. In 1967, Martin Richard developed a language called BCPL
(Basic Combined Programming Language). It is more specific
and can access memory directly from main memory.
6. In 1970, Ken Thompson developed a language called B
Language.
7. In 1972, Dennis Ritchie developed C Language at AT&T Bell
Labs, USA using the features of BCPL & B language.
8. In 1978, C language was documented and popularized as a book
“The C programming Language” by Brain W Kernighan and
Dennis Ritchie and this book popular and the language was
called as ‘K & R C’.
9. In 1989, ANSI (American National Standards Institute) standardized C language and this
version came to known as ANSI C.
10. In 1990, ISO (International Standards Organization) adopted C and this version is known as
C89.
11. In 1995, new Version C95 was developed and in 1999, a new version C99 was developed.

Page 19

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

2. Write Characteristics of C Language Or features of C Language.


Characteristics of C Language:

1. C language is a high-level language (i.e. programmer concentrate on how write/run a


program rather than machine running)
2. C language is small in size (i.e. it uses less memory and it contains only 32 keywords)
3. C language supports structured oriented programming. (Functions, modules, procedures etc
;)
4. C language is a stable language (i.e. since 1983 ANSI C up to now still in use).
5. C language is an extensible language (i.e. contains rich set of libraries).
6. C language is a core language ( many languages like c++, java derived from C).
7. C language supports loose typing (in this characters can represent as integers and vice versa).
8. C language facilitates low-level language (i.e. it supports bit-level or bitwise programs).
9. C language is a portable language. (i.e. we can easily move/load c programs ).
10. C language is a quick language (i.e. once we write a function we can use many times).
11. C is a case-sensitive language (i.e. which shows the difference between Upper & Lower case
letters).

----------------------------------------------------------------------

3. Explain the structure of C Program


Every C program contains a no of building blocks known as functions. Each C program contains a no
of sections. They are

Every C program contains a no of building blocks known as functions. Each C program contains a no
of sections. They are

1. Documentation Section: It contains set of comment lines that include the details like name of
program, author, date & time of creation of program e.tc. The comments are non-executable
statements and are placed between /* and */.

Page 20

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

2. Header File Section: It link functions from system library using #include directive.

Eg: # include <stdio.h>

3. Global Declaration Section: It contains global variables declared outside all the functions. These
variables can be accessed in more than one function.

4. main () Function section : C program contains at least one function called main () from which
every program execution begins. It is compulsory section to be declared and contains two parts.

They are

 Declaration Part.
 Execution Part.

Declaration part contains declaration of variables used in the program.

Execution part contains set of statements.

In C every statement is ended with semicolon (;)

5. Sub program section (User defined Function): The functions written by user are called user
defined functions and are defined before or after main ().

4. Explain the process of writing a first C-program. (5m)


Writing the first C Program:

1. Open a text editor. If we are DOS user, we use C-editor and if we are unix/linux user we can use
ed / vi editors.

2. Type the program in the editor as shown below:

C-editor in DOS

Page 21

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

#include<stdio.h>

void main()

printf(“ ADITYA
DEGREE COLLEGE”);

3. Save the program(file) as filename.c Example : sample.c

4. Compile & Run the program. In c-editor COMPILE: Alt + f 9 and RUN: ctrl + f 9

5. To check the output: alt + f 5

5. Explain different files used in c program.(5m)


Files used in C Program:

C program consists of four types of files.

They are
1. Source file
2. Header file
3. Object file
4. Executable file

1. Source file: The code written by user is called source code and contains main() and other
functions. It is saved with an extension of .c Example: sample.c
2. Header Files: The header file contains functions that used in the source code. These files are
included by using #include and having an extension of .h Example: #include<stdio.h>
3. Object File: When source code is compiled object code is generated that is understandable by
computer. It contains binary code(0,1) with an extension of .obj Example: sample.obj
4. Executable File: The executable file is generated by linker when you execute the binary file. It
has an extension of .exe Example: sample.exe

Page 22

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

6. Explain about compiling and Executing C-Program?


Compiling and Execution of the program written in C involves a series of steps. They are

1. Creating the program

2. Compiling the program

3. Linking the program with functions needed

4. Executing the program

1. The program written in a c-editor is known as source file (or) source code.
2. The compiler, program translates the source code into object code.
3. The object code contains machine instructions for the CPU.
4. The object file is processed with another special program called Linker.
5. The linker combines object file with required Library files and produce the Executable
file(.exe)

In windows operating In unix operating system


system
Creating a program sample.c ed sample.c
After Compilation sample.obj sample.o
After Execution sample.exe sample.out

C TOKENS

C tokens are the basic buildings blocks in C language which are constructed together to write a C
program. Each and every smallest individual unit in a C program is known as C tokens. C tokens are
of five types. They are

 Keywords (eg: int, while)


 Identifiers(eg: main, total)
 Literals (Constants) (eg: 10, 20)
 Operators (eg: +, /,-,*)
 Special symbols (eg: (), {})

Page 23

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

7. Write about keywords in C language. (5m)


KEYWORDS:

1. The keywords are also called as Reserved Words.


2. Keywords are the words that have specific meaning and functioning and these words are already
explained to c-compiler what to do.
3. These keywords should not used as identifier names in the program.
4. There are 32 keywords in C language.

Keywords C programming language

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

8. Write about IDENTIFIERS in c language. (5m)


IDENTIFIERS: Identifiers are names given to program elements such as variables, constants, arrays
and functions. These identifier names are given by user (programmer).

Rules for naming Identifiers:

1. It must begin with an alphabet. (example : sum,avg,abc123 ---- valid 123abc--- invalid)

2. It should not be a keyword. (example : total,product---valid for,while,void ---- invalid)

3. It should not include any special character except underscore “_”.

4. It should not include any commas or blank spaces.

5. Length of identifier name is compiler dependent.

9. Write about constants in c language.


Constants are identifiers whose value does not change during execution. In C, Constants are declared
using keyword “const” or by #define.

Constants in C are classified into 4 types. They are:

1. Integer Constants

2. Floating-point Constants

3. Character Constants

Page 24

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

4. String Constants.

1. Integer Constants: Integer constants are used to store integer values and do not contain any
decimal point.

Rules:

1. An integer constant must have at least one digit


2. It should not have any decimal point
3. It can be either positive or negative
4. No commas or blank spaces should be included
1. Decimal constant: Decimal integer constants can have digits 0 -9.
Example: 456 – valid and 1,23 , 1 2 ---- invalid
2. Octal constant: An integer constant preceded by zero(0) is an octal number. octal integer
constants can have digits 0 -7.
Example: O123
3. Hexa decimal constant: An integer constant preceded by ox or OX is a hexadecimal
number. Hexa decimal integer constants can have digits 0 -9, A-F. Example: OX123,
OX9ABC

2. Floating-point Constants: Floating point constants contain real numbers with decimal points. It
may contain integer part, fraction part and an exponent field (e)

 A real constant must have at least one decimal point


 It can be either positive or negative
 No commas or blank spaces should be included

Example: valid: 0.45, -3.71, 567.0 invalid: 0. 56, 24

A floating point number can also be expressed in Exponential or Scientific form. In this, the part
appearing before ‘e’ is known as mantissa and part after ‘e’ is known as exponent.

Eg: 0.4e2 27E2 5.2E+3

The scientific notation is used to express numbers that are either very small or very large.

Eg: a) 240000000=2.4E8 b) -0.000000012=-1.2E-8

3. Character Constants: Character is one which can be an Alphabet, digit or special symbol that is
enclosed within single quotes. Characters are stored in ASCII code format and occupies 1 byte of
memory

Eg: ch=’y’;

4.String Constants: String is a group of characters that are enclosed within double quotes.

Eg: “Aditya” , “Degree”, “College”.

Page 25

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

10. Discuss about variables in C?


A variable is an identifier whose value changes during execution. C supports two types of variables.
They are

 Numeric Variables: These variables are used to either integer or floating point values
 Character Variables: character can be an Alphabet, Digit or special Symbol

Rules for naming Variables:

1. It should begin with an alphabet.


2. It should not include any blank spaces or commas
3. It should not be a keyword
4. The name of variable can be in uppercase or lowercase or both
5. The length of variable is compiler dependent
Example: empno, sum, TOTAL

Declaration of variables: A variable is defined by specifying the type of data that a variable will
store. The variables are declared before using them.
Syntax: datatype varlist;
Example: int sum;
int x,y,z;
Initialization of variables: Assigning the variables at the time of its declaration is known as
initialization. In C, variables are initialized as follows
Syntax: datatype variablename = value;
Example: int x = 10;

11. Explain about Data types in C


The data types specify the size, type of data and memory address allocated for an identifier. The
data types in C are classified into different types. They are

1. Standard or Built-in or Basic data types

2. Derived Data types

3. User Defined Data types

Page 26

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

1. Basic Data types:

The four basic data types in C are integer, float, character, double & void. They are also called as
standard or built-in data types. These data types come along with programming language itself.

1. Integer: The integer data types are used to store integer values and are declared with keyword int.
Integer type of data occupies 2 bytes of memory.

DATA TYPE SIZE RANGE


int or signed int 2 bytes -215 to 215-1 (-32,768 to 32,767)
short int 2 bytes -215 to 215-1 (-32,768 to 32,767)
unsigned int 2 bytes 0 to 216-1 ( 0 to 65,535)
31 31
long int 4 bytes -2 to 2 -1 (-214,74,83,648 to
214,74,83,647)
unsigned long int 4 bytes 0 to 232-1 ( 0 to
429,49,67,295)

2. Float: It is used to store real numbers or floating-point numbers with single precision. They are
declared with keyword float. Float type of data occupies 4 bytes of memory.

Double: It is used to store real numbers or floating-point numbers with double precision.
They are declared with keyword double. Double type of data occupies 8 bytes of memory.

DATA TYPE SIZE RANGE


float or signed float 4 bytes 3.4e-38 to 3.4e+38
Double 8 bytes 1.7e-308 to 1.7e+308
long double 10 bytes 3.4e-4932 to 3.4e+4932

3. Character: It is used to store character type of data. A character can be an Alphabet, Digit or
Special Symbol. They are declared with keyword char.

DATA TYPE SIZE RANGE


char (or) signed char 1 byte -127 to 128
unsigned char 1 byte 0 to 255

4. Void Data type: The void is a data type that doesn’t have value of any type. It is mostly used in
functions that doesn’t return a value

Example: void main ()

2. Derived Data types: The data types which are derived from fundamental data types are known as
derived data types. The derived data types in c are

 Array: It is group of consecutive memory locations that stores homogenous type of data.
 Structure: It collection of same or heterogeneous (different) type of data.

Page 27

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

 String: It is a collection of group of characters enclosed within double quotes (or) it is


defined as character array.
 Pointer: It is a variable which holds the address of another variable of same data type.
Pointers are used to access memory and manipulate the address.

3. User defined Data types: In C, typedef & enumerated dataypes are known as user-defined data
types. By using these, user can create his own data types that are equivalent to existing data types.

 typedef: It is used to create our own data types that are equivalent to existing one.
Syntax: typedef ExistingDatatype newDatatype;
Example: typedef int abc;
Now : abc x,y,z;
 Enumerated data type: It is declared with enum keyword and the user can create his/her
own data type and define values that are declared as constants

Syntax: enum variable { value1,value2,…….valuen};

Example: enum day{sun,mon,tue,wed,thu,fri,sat};

The constants take a value that begins from 0.

=============================================

12. Write about different types of operators in C.


An operator is a symbol that tells the computer to perform a specific (function) operation. An
operator acts on operand of certain data type. The operators are classified into various types based on
the utility and action.

They are

1. Arithmetic operators 6. Conditional operator


2. Relational operators 7. Bitwise operators
3. Logical operators 8. Comma operator
4. Assignment operator 9. sizeof operator
5. Increment/decrement operators

1. Arithmetic operators: These are the operators that perform arithmetic operations and are
classified into unary and binary operators. If operators performs only on one operand is called as
unary operation. If operators performs two operands is called as binary operation. These operators
always produce numeric values as outputs. “+” operator is also works to combine two strings is
called concatenation.

Description Example
Operators
+ Unary plus +a

Page 28

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

- Unary -a
minus
+ addition a+b
- subtraction a-b
* product a*b
/ division a/b
% modulo a%b

2. Relational operators: Relational operators are used to compare arithmetic, logical expressions.
These operators generate Boolean (1/0) outputs, i.e. expression returns 1 if the condition is true
otherwise returns 0 if the condition is false. These operators fall in the same group lower than unary
and binary operators.

The relational operators available in C are

Operators Description Example


checks if operand on the left is greater than a>b
>
operand on the right
checks if operand on the left is less than operand a<b
< on the right
Checks if left operand is greater than or equals a>=b
>= to right operand
Checks if left operand is less than or equals to a<=b
<=
right operand
Check if two operands are equal (comparative a==b
==
operator)
!= Check if two operands are not equal. a!=b
3. Logical operators: These operators are used to evaluate logical and relational expressions. The
logical operators are used to combine relational expressions. These generate Boolean outputs (1/0).
The logical operators are

Operators Description Example


(a>b)&&(a>c)
if both expressions are true it returns
&& Logical AND
1 other wise returns 0

(a>b)||(a>c)
if any one of the expression are true
|| Logical OR
it returns 1 other wise returns 0

!(a<b)
! Logical NOT it changes the value i.e. true to false
& false to true

4. Assignment operator: This operator is used to calculate the expressions on the right and assign
the value to the identifier on left. The most commonly used assignment operator is ‘=’.

Page 29

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax: Identifier = expression; Example: area = length * breadth;

Multiple assignments: In C- language multiple assignment of a value to number of identifiers is


possible.

Syntax: Identifier-1 = identifier-2 =……… = identifier n = value;


Example: x = y = z = 8;

5. Increment and decrement operators: The increment and decrement operators are used to
increment or decrement the contents of a variable. In C language,

 “++” is called as increment operator


 “--” is called as decrement operator.

These operators can be declared in two ways.

1. Pre increment(++a) and pre decrement(--a)


2. Post increment(a++) and post decrement(a--)

Pre increment: value is increments before Post increment: value is increments after
assigning respective variable assigning respective variable
Syntax: ++variable name; Syntax: variable name++;
Example: Example:
int i=5; int i=5;
Printf(“%d”,++i); Printf(“%d”,i++);
Output: i = 6 Output: i = 5

Pre decrement: value is decrements before Post decrement: value is decrements after
assigning respective variable assigning respective variable
Syntax: --variable name; Syntax: variable name--;
Example: Example:
int i=5; int i=5;
Printf(“%d”,--i); Printf(“%d”,i--);
Output: i = 4 Output: i = 5

Conditional operator: This operator first checks the condition and basing on the condition the
required expression is executed. The conditional operator is firmed with two symbols ? and :. This
operator contains three expressions so it is also called as ternary operator.

Syntax: Condition? Expression-1 : Expression-2; Example: int a=7,b=5,n;


Or n = (a>b) ? a : b;
Syntax: Expression-1? Expression-2 : Expression- Output: n=a; i.e. n=7.
3;

Page 30

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Bitwise operator: Some applications require manipulation of individual bit within a word of
memory. C contains the following bitwise operators.

1. Bitwise AND (&) 5. Left shift (<<)


2. Bitwise OR ( | ) 6. Right shift (>>)
3. Bitwise XOR (^)
4. Bitwise NOT (~)

Bitwise AND (&): This operator returns 1 if both the value of operand bits are equal to 1 otherwise it
returns zero.

Bitwise OR ( | ): This operator return 1 if any one of operand bits are equal to 1 otherwise it returns
0.

Bitwise XOR (^): This operator returns 1 if contains odd number of 1’s among the operand bits
otherwise it returns 0.

Bitwise NOT (~): This operator is called as compliment operator as it compliments each and every
bit in the given operand.

Left shift (<<): It is used to shift specified bits of operands towards left. The empty places filled with
zeros.

Example:

Page 31

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Right shift (>>): It is used to shift specified bits of operands towards right. The empty places filled
with zeros.

Example:

Comma operator: The set of expressions/variables are separated by comma operator is a valid
statement in C.

Syntax: Identifier = (expression 1, expression 2, ------------, expression n);

Example: int k , j;
k= (j=3 , j*10)
Output : k=30
Size of operator: This operator gives the size of the data type or variable in terms of bytes occupied
in the memory.

Syntax: sizeof(datatype/variable)

Example:
 sizeof (int) = 2 bytes
 sizeof (float) = 4 bytes
 sizeof (char) = 1 byte
 sizeof (double) = 8 bytes
-------------------------------
13. Write about various I/O Statements in C language.
Reading the data from input devices and Writing the data on screen are two main tasks of any
program. To perform such tasks input-output functions (I/O Functions) are used.

In C, I/O functions are classified into two types

1. Formatted Functions

2. Unformatted Functions

Page 32

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Formatted functions: The formatted functions are used to read/write any type of data. They require
conversion symbol like %d, %f e.tc. They return a value which is equal to number of values
read/write.

Example: scanf() , printf()

Scanf(): scanf() stands for scan formatting data and is used to read formatted data from the keyboard

Syntax: int scanf (“control string”, &var1,&var2...... &varn);

Example: scanf(“%d%d”,x,y);

 The control string specifies the type of data read from keyboard (Example:
%d,%s,%f,%c)
 “&” refers to address operator and var-1,var-2 -- var-n are variables
 scanf() always return integer type of value

printf(): printf() stands for print formatting data and is used to write or display formatted data on
console. We can use printf () function in two ways as shown below.

Syntax : int printf(“control string”, var-1, var-2…var-n); Syntax: int printf(“string”);


Example: printf(“%d%d”,x,y); Example: printf(“ C language”);

 The control string specifies the type of data displayed on screen (Example:
%d,%s,%f,%c)
 Var-1,var-2…..var-n are variables
 printf() always return integer type of value

Unformatted functions: The unformatted input/output functions works only with character type of
data. These functions do not require any conversion symbol. These functions always return same type
(char type) of data.

A. getchar (): This function reads character type of data from the standard input device.
Syntax: int getchar();
Example: ch=getchar();
B. putchar (): This function prints a character on the console.
Syntax: int putchar(char);
Example: putchar(ch);
C. getch() : It reads a character from the standard input device and doesn’t display the character
read on screen
Syntax: int getch();
Example: ch=getch();
D. getche() : It reads a character from the standard input device and echos the character on
screen.
Syntax: int getche();
Example: ch=getche();
E. putch(): It prints a character on the console.

Page 33

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax: int putch(char);


Example: putch(ch);
F. gets(): It reads a string from the standard input device.
Syntax: char * gets(char *string)
Example: gets(s);
G. puts(): It prints a string on the screen/console.
Syntax: int puts(char *string);
Example: puts(s);

-------------------------------------------- ----------------------- ----------------------------------- --------------

Operator precedence & Operators Associativity

Operator precedence: determines which operator is performed first in an expression with more than one operator with different
precedence.

For example: Solve 10 + 20 * 30


10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30
Output :70

Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be
either Left to Right or Right to Left.

For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is
treated as “(100 / 10) * 10”.
perators Precedence and associatively are two characteristics of operators that determine the evaluation order of sub-
expressions in absence of brackets

Priority Operator Description Associativity

() Parentheses (function call)


[] Brackets (array subscript)
1 . Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement left-to-right

++ — Prefix increment/decrement
+– Unary plus/minus
!~ Logical negation/bitwise complement
2 (type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation right-to-left

3 */ % Multiplication/division/modulus left-to-right

4 +– Addition/subtraction left-to-right

5 << >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to


6
> >= Relational greater than/greater than or equal to left-to-right

Page 34

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

7 == != Relational is equal to/is not equal to left-to-right

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
14
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment right-to-left

15 , Comma (separate expressions) left-to-right

Type conversion and type casting


Type conversion or type casting of variable refers to changing a variable of one data type into another
data type. Type conversion is internal process and typecasting is external process.

Type conversion: Type conversion is takes place, when the expression has different data types. To
evaluate the expression the data type is converted from lower to higher level. Type conversion is
done implicitly. The Type conversion is not done by force. It happens automatically. In type
conversion no need to mention data type.

They are two types of type conversions.

 Converting lower level data type into higher  converting higher level data type into lower
level of a variable is called as promotion level of a variable is called as demotion
Example: Example:
int x=5; float y=7.8;
float y; int x;
y=x; /* Type conversion low-high */ x=y; /* Type conversion low- high */

Page 35

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

output y=5.0 output x=7 Note : In this data will loss

Type casting: It is takes place, when the expression has different data types and programmer want to
change. To evaluate the expression the data type is converted from lower to higher level or vice
versa. It is done explicitly. It is done by force. It happens under the control of programmer. In type
casting we need to mention data type. They are two types of type casting. They are

 Converting lower level data type into higher  converting higher level data type into lower
level of a variable is called as promotion level of a variable is called as demotion
Example: Example:
int x=5; float y=7.8;
float y; int x;
y = (float) x; /* type casting low-high */ x= (int) y; /* type casting low- high */
now output: y=5.0 now output: x=7 Note : In this data will loss

Introduction for Decision Control and Looping Statements

14. Write about control structures or control statements in C language.


C language is a set of statements which are normally executed sequentially in the order in which they
appear. This happens when no options or no repetitions. In order to change the order of sequence of
execution according to situations, we use control statements.

In C control statements are classified into two types. They are

1. Decision making Statements


2. Looping Statements.

1. Decision making Statements: Selection process (selection of statements to be executed) done by


condition is called decision making statements or branching or Decision Control Statements.

C language contains branching statements to execute selected statement by taking decision


making conditions is called decision making statements or control statements. C language
contains two types of decision making statements. They are

a. Conditional branching statements: when branching takes place based on condition


then it is called as Conditional branching statements.
i. Example: if, if-else, if-else-if , switch-case statements
b. Unconditional branching statements: when branching takes place without any
condition then it is called as Unconditional branching statements.
i. Example: break, continue, goto, exit.

2. Looping Statements: Repetitive execution of statements is called iteration or looping.

There are two types of looping statements they are

Page 36

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

a. Entry controlled loop: first it checks condition and later it executes the body.
i. Example: while and for.
b. Exit controlled loop: first it executes the body and later it checks condition.
i. Example: do-while.

15. Write about decision making Statements (Or) Conditional Branching


Statements in C?
Decision Control Statements: Decision control statements execute the statements by the checking
condition. The decision making involves branching, which means jumping from one step to another
step by condition in a program.

Conditional Branching Statements: If branching occurs basing on condition then it is known as


conditional branching. C supports the following decision control and branching statements

1. Simple if statement
2. if…else statement
3. Nested if-else
4. if...else if statement or ladder if …else
5. Switch statement

1. Simple if: The simple if statement is used to execute a statement/block if the condition is true
otherwise the statement/block will be skipped.

Flow chart:
Syntax:
if (condition)
Statement/block;

Example:
if (age>=18)
printf(“eligible for
vote”);

3. if . . else statement: In this statement we have two blocks or statements, if the condition is
true then the statement-1/block-1 is executed otherwise the statement-2/block-2 will be
executed.

Page 37

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax: Flow chart:


if (test-condition)
Statement-1 / block-1;
else
Statement-2 / block-2;

Example:
if ( a > b)
printf(“ biggest number = %d” ,

else
printf(“ biggest number = %d” ,

3. Nested if-else: An if-else statement within another if-else statement is known as Nested if-else
statement.

Syntax: Example:
if (test-condition-1) Syntax:
statement1/block1; if ((a>b)&&(a>c))
else printf(“ biggest of 3 numbers = %d” , a);
{ else
if (test-condition-2) {
statement-2/block-2; if (b>c)
else printf(“biggest of 3 numbers = %d” , b);
statement-3 / block-3; else
} printf(“biggest of 3 numbers = %d” , c);
}

4. if..else if: It is used to check multiple conditions. It is also known as ladder if. It is a chain of if
statements in which each statement within else is an if statement.

Syntax: Example:

Page 38

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

if (condition-1) if (avg>=60)
statement-1/block-1; printf(“first class”);
else if (condition-2) else if(avg>=50)
statement-2/block-2; printf(“second class”);
.............. else if(avg>=35)
else if (condition-N) printf(“third class”);
statement-n/block-n; else
printf(“fail”);

Flow chart:

Switch-case: It is a multi-way decision statement. It is used to select a statement(s) out of several


available groups.

Syntax: Example:

switch( expression ) switch(n)


{ {
case value-1: case 1: printf(“C language ”);
Block-1; break;
Break; case 2: printf(“C++ lang”);
case value-2: break;
Block-2; case 3: printf(“java lang”);
Break; break;
case value-n: }
Block-n;
Break;
default:
Block-1;
Break;

Page 39

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

}
Statement-x;

Flow chart:

16. Write about looping statements or control loops in C language.


Looping (or) Iteration Statements: Looping is the process of repetition of instructions. Every loop
contains initial value, condition; body and increment/decrement (update statement).

C supports 3 types of looping or iterative statements. They are

1. while loop
2. do-while loop
3. for loop

While loop: It is an entry–controlled loop statement, which repeats the instructions until condition is
satisfied.

While loop, first it checks the condition if it is true then only it executes the body therefore it repeats
until condition false.

 while (0) the condition is false.


 while (1) the condition is true. while(1) is used for Infinite Loop
 It enters into loop minimum zero times if the condition is not satisfied [while(0)].

Page 40

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax: Example:

Initial-value; i=1;
while (text-condition) while(i<=10)
{ {
Statements; printf(“%d”,i);
Increment/decrement; i++;
} }
Statement-x;
Flow chart:

Do-while loop: It is an exit –controlled loop statement, which repeats the instructions until condition
is satisfied. It is also called Bottom Tested condition.

Do-while loop, first it executes the body, then it checks condition if it is true again it executes body
until condition false.

 This loop starts with “do” keyword.


 This loop ends with while (condition) which ends with “;” (semicolon).
 It enters into loop minimum one time without checking the condition.

Syntax: Example:

Initial-value; i=1;
do do
{ {
Statements; printf(“%d”,i);
Increment/decrement; i++;
} }
while (text-condition); while(i<=10);
Statement-x;
Flow chart:

Page 41

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

For loop: For loop is an entry controlled loop. It is used to repeat the loop for fixed number of times.

For loop, first it checks the condition if it is true then only it executes the body therefore it repeats
until condition false for fixed number of times.

 In for loop initial value, condition, increment/decrement is given in single statement.


 The initial value specifies the starting value, condition specifies the no of times the loop to be
repeated and increment/decrement specifies the next iteration value.

Syntax: Example:
for(intial value; condition;increment/decrement) for(i=1;i<=10;i++)
{ {
body; printf(“%d”,i);
} }

Flow chart:

Page 42

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

17. Write the differences between while loop and do...while loop.
while loop do...while loop
1. First it checks the condition if it is true 1. First it executes the body, then it
then only it executes the body therefore it checks condition if it is true again it
repeats until condition false. executes body until condition false.
2. It is an entry controlled loop statement. 2. It is an exit-controlled loop statement.
3. It enters into the loop minimum ZERO 3. It enters into loop minimum ONE
times. time.
4. Syntax: 4. Syntax:

Initial-value; Initial-value;
while (text-condition) do
{ {
Statements; Statements;
Increment/decrement; Increment/decrement;
} }
Statement-x; while (text-condition);
Statement-x;

18. Explain about different types of for loop? (Or) Explain about for
statement.
For loop/statement: For loop is an entry controlled loop. It is used to repeat the loop for fixed
number of times.

For loop, first it checks the condition if it is true then only it executes the body therefore it repeats
until condition false for fixed number of times.

Syntax: Example:
for(initial value; condition; increment/decrement) for(i=1;i<=10;i++)
{ {
body; printf(“%d”,i);
} }

Rules:

1. A for loop accepts more than one initial value. A for loop may contain more than one initial
value that are separated by comma.

Example:
for(i=0,j=0;i<10;i++)
{

Page 43

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

printf(“%d”,i);
j++;
}

2. A for loop accepts more than one updating expression. A For loop may contain more than one
increment or decrement section, that are separated by commas.

Example: j=0;
for(i=0;i<10;i++,s=n/10,j++)
{
printf(“%d”,i);
}
3. A for loop accepts more than one conditional expression. In for loop the test condition may
have compound relation which has multiple conditions.

Example: int total=0;

for(i=0;i<10&&total<1000;i++)
{
total=total+i;
printf(“%d”,total);
}
4. In for loop we can omit any of three expressions as shown below:
 for (;i<10;i++)  here initial value is omitted
 for (i=0;i<10;)  here increment/decrement value is omitted
 for (;i<10;)  here initial value and increment/decrement value is omitted.
 for (; ;)  this is empty for loop.

5. A for loop using expressions i.e. the for loop can have expressions in both initialization and
increment/decrement sections

Example: for (i=(m+n);j<100;n=n/10,k=k%10)

6. Nested for loops: A for loop within another for loop is known as nested for

Example:
for (i=1;i<row;i++)
{
for(j=1;j<column;j++)
{
printf(“%d”,i);
}
}

Page 44

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

19. Write about nesting loops.


C program allows using one loop inside another loop. A loop within another loop is known as
Nesting of loops.

The syntax for a nested for loop in C:


for ( initialvalue; condition; increment )
{
for (initialvalue; condition; increment)
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop in C:

while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

The syntax for a nested do...while loop in C:

do
{
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );

20. Explain about Unconditional Branching Statements (or) break, continue and
goto statements in C.
Unconditional Branching Statements: If branching takes place without checking condition, then
such statements are known as Unconditional statements.

C supports the following statements:

1. Break
2. continue
3. goto

Page 45

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Break: It is an unconditional statement which is used to transfer the control to the end of the loop. It
is mostly used in switch, for, while, do...While.

Syntax: break;

Continue: It is an unconditional statement which is used to transfer the control to the beginning of
the loop. When continue is used, it causes the loop to skip some statements and go to beginning of
loop. It is mostly used in while, do...While and for statements

Syntax: continue;

goto: It is an unconditional statement which is used to transfer the control to a specified label .

Label is a valid identifier followed by colon (:).

Label can be placed anywhere in the function or program.

Page 46

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax: goto labelname;


Example: abc: ....................
......................
goto abc;
There are two types of controls for goto statements. They are

1. forward jump
2. backward jump

Page 47

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

UNIT III

Arrays: Introduction – Declaration of Arrays – Accessing elements of the Array – Storing Values in Array–
Operations on Arrays – one dimensional, two dimensional and multi dimensional arrays,
Strings: character handling and strings.
Arrays
1. Write about arrays in c.
Definition: Array is a group of consecutive memory locations that stores homogenous (same) type of data.

The elements in array are referred by an index-number. The index numbers begin from 0 to size-1. The
number of index indicates the dimension of the array.

Arrays are generally used in to store

List of temperature readings


List of student’s data
List of employee’s salary statement.
List of products sold

Arrays are classified into three types. They are

1. Single Dimensional Arrays or one-dimensional arrays (1D array):


Array name followed by one subscript is called as one-dimensional arrays (1D array).
2. Two-Dimensional Arrays (2D array):
Array name followed by two subscripts is called as two-dimensional arrays (2D array).
3. Multi-Dimensional Arrays:
Array name followed by more than two subscripts is called as multi-dimensional arrays (3D array, 4D
array, etc, ;)

Advantages of an Array in C:

 Easy access to all the elements.

Page 48

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

 Random access of elements using array index.


 Use of less line of code. (as it creates a single array of multiple elements)
 Traversal through the array becomes easy using a single loop.
 Sorting becomes easy as it can be accomplished by writing less line of code.

Disadvantages of an Array in C:

 An array in C is not dynamic. Arrays Allows a fixed number of elements to be entered which
is decided at the time of declaration.
 Insertion and deletion of elements can be costly since the elements are needed to be managed
in accordance with the new memory allocation.

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

2. Write about One-dimensional arrays or Single Dimensional Arrays

One-dimensional arrays or Single Dimensional Arrays: Array name followed by with only one
subscript are known as single dimensional arrays or 1D arrays.

Declaration of 1D arrays
Syntax: Data-type arrayname[size];
Example: int a[10]; or float b[10]; or char ch[10];

Accessing elements of the Array: The individual elements in an array are accessed by using array name
followed by index-number. The elements are accessed for reading/writing.

Syntax: arrayname [index];


Example-1: a[0]=5;
Example-2: a[1]=10;

Storing values in Arrays: Elements in an array can be stored in three ways. They are

Page 49

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

1. Initialization of array: an array can be initialized at the time of declaration.

Syntax: data-type array-name[size] = { val-1,val-2,val-3,…,val-n};

Where data-type can be int, float, char etc.; and array-name is the user-defined name, size is the length of the
array and val-1,val-2, ….val-n; are the elements of the array.

Example: int a[5] = {1,2,3,4,5};

2. Input Values/ reading values: Elements can be stored in array by inputting values from keyboard. In this
method, a while, do-while or for loop are used.

Syntax: Example:
for( i=0; i<size; i++) for( i=0; i<3; i++)
scanf(“%d”, & a[i] ); scanf(“%d”, & a[i] );

3. Assigning values: The assignment operator is used to assign values to an array.

Example: int a[5];


a[0]=10;
Syntax: arrayname[index]= value; a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;

Program for to find sum of “n” array elements

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

int a[100], size, i, sum = 0;


clrscr();
printf("\nEnter array size : ");
scanf("%d",&size);
printf("\n Enter array elements ");
for(i = 0; i < size; i++)
scanf("%d",&a[i]);
for(i = 0; i < size; i++)
sum = sum + a[i];
printf("Sum of the array = %d\n",sum);
getch();

Page 50

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

******** for more programs on 1D-arrays goto page number- 8 *********

3. Write about Two-dimensional in C.


Two-dimensional array: if an array name followed by one subscript is called as one-dimensional arrays (1D
array). Similarly, if Array name followed by two subscripts is called as two-dimensional arrays (2D array).

In two dimensional arrays the cells are organized in consecutive memory locations in the form of rows and
columns. This is similar to matrix arrangement and requires two subscripts.

Declaration of 2D arrays
Syntax: Data-type arrayname[rowsize][columnsize];
Example: int a[10][10]; or float b[10][10];
Here
The rows are numbered from 0 to rowsize-1 and columns are
numbered from 0 to columnsize-1

Accessing elements of the Array: The individual elements of a two-dimensional array are accessed by using
array name followed by row-number & column-number.

Syntax: arrayname [row-number] [col-number] = value;


Example: a [2][2]=5;

Initialization of two-dimensional array: Initialization means assigning values at the time of declaration. The
two dimensional is array is initialized in the same way as one dimensional array.

1.Syntax: arrayname[row-size][col-size]={{row1-values},{row2-values},..,},{rowN-values}};

Example:

2. If some values are missing during initialization then it is automatically set with zero as shown below:

Page 51

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

3. During declaration or initialization the first index is optional where as second index size must be
compulsorily declared a[ ][2]={1,2},{3,4}};

Reading /Writing values: Elements can be stored in 2D-array by inputting values from keyboard. In this
method, a while, do-while or for loop are used.

Syntax: reading values Syntax: writing values

for( i=0; i<row-size; i++) for( i=0; i<row-size; i++)


for(j=0; j<col-size; j++)
scanf(“%d”, & a[ i ] [ j ] ); for(j=0; j<col-size; j++)
printf(“%d”, a[ i ] [ j ] );
printf(“\n”);

******* for more programs on 2D-arrays goto page number- 14 ********

4. Write different types of operations on Arrays


Array is a group of consecutive memory locations that stores homogenous (same) type of data.

There are no of operations that can be performed on arrays. They are

operations on 1D arrays: operations on 2D arrays:


1.sorting 1. matrix addition
2.searching 2. matrix difference
3.inserting 3. matrix multiplication
4.deleting 4. matrix transpose
5.traversing
6.merging

Operations on One-Dimensional Arrays (1D-arrays):

1. Sorting: Sorting means arranging the elements in an array in some relevant order i.e., either in ascending or
in descending order.

Example: If ‘a[]’ is an array ,the elements in that are sorted in ascending order pattern such as
a[0]<a[1]<a[2]<. ..... <a[n-1]
i.e., int a[ ]={77,53,75} (Before Sorting)
a[ ]={53,75,77} (After Sorting)
There are different types of sorting. They are Selection sort, Bubble sort, Insertion sort, Merge sort, Quick
sort, Heap sort Etc.;

Page 52

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

2. Searching: Searching means to find whether a particular value (key element) is present in the given array
or not. If the value is present in the given array then searching is successful (found) otherwise unsuccessful
(not found). There are 2 popular methods for searching the array elements:

1. Linear Search 2.Binary Search

3. Insertion: Inserting means adding new element into the array. Elements in an array can be inserted either in
the first, middle or last.

4. Deletion: Deleting means removing an element from the array. Elements in an array can be removed either
in the first, middle or last.

5. Merging: Merging means copying the elements of two different arrays into third array is known as
merging.

6. Traversing: Traversing means accessing the elements of an array either for printing or storing

Operations on Two-Dimensional Arrays(2D-arrays):

Array is a group of consecutive memory locations that stores homogenous (same) type of data.

There are no of operations that can be performed on two dimensional arrays. They are

1. Matrix Addition
2. Matrix Subtraction
3. Matrix Multiplication
4. Matrix Transpose

Matrix Addition: Two matrices can be added when they have same number of rows & cols. Elements can be
added by writing

Ci, j = Ai, j + Bi, j


Matrix Subtraction: Two matrices can be subtracted when they have same number of rows & cols. Elements
can be subtracted by writing

Ci, j = Ai, j - Bi, j

Page 53

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Matrix Product/ multiplication: Two matrices can be multiplied when number of columns of first matrix is
equals to number of rows of second matrix. If we multiply two matrices of order m x n and p x q then the
resultant matrix will be of order m x q. Elements can be multiplied by writing

Matrix Transpose: The matrix obtained by interchanging rows & cols is known as Transpose. The Transpose
of m x n matrix A is given as n x m

B i, j = A j, i
****************************

5. Write about Multi-Dimensional Arrays.


A Multi-Dimensional array is an array having n indices and is a collection of m1 * m2 * m3... mN elements.

The Three dimensional Arrays is an example of Multidimensional array having 3 indices. The first index
indicates the number of rows, second index indicates number of columns and third index indicates the number
of pages

Declaration of 3-Dimensional Arrays:

Syntax: Datatype Arrayname[rows][columns][pages];

Example: int a [2][3][4]; The below 3-D array contains 2 X 3 X 4 =24 elements

Program for Multidimensional arrays

#include<stdio.h>
void main()
{
int a[2][3][4]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24};
int i,j,k;
for (i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for (k=0;k<3;k++)
{
printf(“%d”,a[i][j][k]);
}
}

Page 54

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

}
getch();
}

*******************************programs on 1D arrays*********************************

Linear Search

Linear Search: Linear Search is also called as Sequential search. It is very simple method for
searching an array for a particular value.Linear Search is popularly known for the searching, takes
place on unsorted arrays.

Working: It works by comparing every element of the array one by one in sequence (linear) until a
match is found.

Program for linear search


#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],size,i,key,flag=0;
clrscr();
printf("\n enter size of the array :");
scanf("%d",&size);
printf("\n enter %d elements into array: ",size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
printf("\n enter key element to search: ");
scanf("%d",&key);
for(i=0;i<size;i++)
{
if(a[i]==key)
{
flag=1;
break;
}
}
if(flag==1)
printf("\n found");
else
printf("\n not found");

Page 55

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

getch();
}

Time Complexity of linear Search:

 Best case: f(n)=O(1)


 Worst case: f(n)=O(n)

Binary Search

Binary Search: Binary search is a searching algorithm that works efficiently with a sorted list.
The Binary searching algorithm uses a recursive mechanism to implement. It is one of the fastest
searching algorithms.

Working:

1. This algorithm finds out the mid position of a given array and compares the key element
with a [mid] element.
2. If (a[mid]==key) is equal, the key element is found otherwise this algorithm divide the
total array list into two halves by comparing the key element with before the mid element
or after the mid element.
3. This process continuous recursively until the array list is available (first<=last).

Program for binary search


#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],size,key,i,f,l,mid,flag=0;
clrscr();
printf("\n enter the size of an array : ");
scanf("%d",&size);
printf("\n enter %d elements into an array : ",size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
printf("\n enter the key element : ");
scanf("%d",&key);
f=0;

Page 56

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

l=size-1;
while(f<=l)
{
mid=(f+l)/2;
if(key==a[mid])
{
flag=1;
break;
}
else
if(key>a[mid])
f=mid+1;
else
l=mid-1;
}
if(flag==1)
printf("\n found");
else
printf("\n not found");
getch();
}
Time Complexity of Binary search:

Best case: f(n)= O(1).


Worst case: f(n)=O(log n).

Selection Sort
Selection Sort: The selection sort is a sorting algorithm that has quadratic running time complexity
as O(n2).. It is generally the preferred choice for sorting files with large objects (records) and small
keys.

Tracing of selection sort

Program for selection sorting

#include<stdio.h>
#include<conio.h>

Page 57

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

void main()
{
int a[100],n,i,j,temp,small;
clrscr();
printf("\n enter array size : ");
scanf("%d",&n);
printf("\n enter %d elements into array : ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);

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

printf("\n after sorting : ");

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

getch();
}
Time complexity of Selection sort:

Best case Average case Worst case


O(n2) O(n2) O(n2)
Therefore the time complexity of selection sort = O(n2).

Bubble Sort
Bubble sort: It is a very simple method that sorts the array elements by repeatedly moving the largest
element to the highest index position of an array a[n-1](in the case of an ascending order).This bubble
sort is also called as sinking sort.

Page 58

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Program for bubble sort

#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,j,n,temp;
clrscr();
printf("\n ***** bubble sort ****** \n");
printf("\n enter array size : ");
scanf("%d",&n);
/* entering data items into array */
printf("\n enter %d elements into an array : ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);

/* main logic */
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1]) /* if condition is true swap(a[j],a[j+1]) */
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
/* to display sorted data elements */
printf("\n after sorting sorted data elements = ");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
}
Time complexity of Bubble sort:

Best case Average case Worst case


O(n2) O(n2) O(n2)

Therefore the time complexity of Bubble sort = O(n2).

*******************************programs on 2D arrays*********************************

Page 59

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Matrices addition using 2D arrays

/* program to find sum of two matrics*/


#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],row,col,i,j;
clrscr();
printf("\n enter row and col size : ");
scanf("%d%d",&row,&col);
printf("\n enter %d x %d elements into first array a[][] : \n",row,col);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&a[i][j]);
printf("\n enter %d x %d elements into second array b[][] : \n",row,col);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&b[i][j]);
/* main logic*/
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=a[i][j] + b[i][j];
printf("\n**** the result c[][] = sum two matrics a[][] and b[][] *****\n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%4d",c[i][j]);
printf("\n");
}
getch();
}
Matrix multiplication or matrix product
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10];
int i,j,k,m,n,p,q;
clrscr();
printf("\n enter row and col size of first mat a[][] : ");
scanf("%d%d",&m,&n);
printf("\n enter row and col size of second mat b[][] : ");
scanf("%d%d",&p,&q);

if(n!=p)
printf("\n matrix multiplication is not possible");

Page 60

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

else
{
printf("\n enter %d x %d elements into a[][] \n ",m,n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\n enter %d x %d elements into b[][] \n ",p,q);
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);

/* main logic*/
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}

printf("\n **** output **** \n");


for(i=0;i<n;i++)
{
for(j=0;j<p;j++)
printf("%4d",c[i][j]);
printf("\n");
}
}
getch();
}

Transpose of matrix elements


/* program to find transpose of a matrix*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],i,j,m,n;
clrscr();
printf("enter the no.of rows and columns");
scanf("%d%d",&m,&n);
printf("enter the elements");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n to transpose the matrix");
for(i=0;i<n;i++)

Page 61

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

{
for(j=0;j<m;j++)
{
b[i][j]=a[j][i];
}
}
printf("the resultant matrix is \n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%4d",b[i][j]);
}
printf("\n");
}
getch();
}

STRINGS
Introduction: Char data type: char data type stores only one character enclosed within single quotes
(‘’). It stores only one byte of data.

Syntax : char charname = ‘character’; Example: char ch = ‘V’;

String: String is a group of characters which ends with a null character “\0”

Example: char st[]= “PARNIKA”


Char variable vs string variable:

String variable:
Char variable:
Char ch[] = “A”;
Char ch = ‘A’;

6. Write about Strings (or) Reading/writing Operations on Strings Reading strings.


Definition: String is a group of characters terminated by NULL (\0) character. In C, string constants
are enclosed within double quotes (“”). Or

String is also defined as character array appended by NULL (\0) character.

Declaration of strings: Strings can be declared in two ways. They are

Page 62

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

1. Declaration for fixed length strings:


Syntax: char stringname [size]; Example: char st[10];
Here String name is followed by subscript.
Subscript [ ]  stores size of string

2. Declaration for variable length strings:


Syntax: char *stringname; Example: char *s;

Important points about strings:

1. A string is a collection of characters.


2. A string is also called as an array of characters.
3. A String must access by “%s” access-specifier in C.
4. A string is always terminated with “\0” (Null) character.
Example of string: “aditya”
5. A string always recognized in double quotes “”.
6. A string also considers space as a character.
Example: “aditya tuni”
7. The above string contains 11 characters.
Example: Char st[20]
The above example will store 19 characters with 1(one) null character.
8. In strings the starting index number is ‘0’ and ending index number is (n-1). And at “n” the null
character i.e. “\0” is stored.
9. To store a string of length 5 we require 5+1 locations( 1 extra for null character)
10. In C, characters in a string are stored in ASCII format
Example: N is stored as 78 but not as ‘N’ and ‘n’ is stored as 110 but not as ‘n’. Therefore ‘N’
and ‘n’ are equal because ‘N’  ASCII value is 78 and
‘n’  ASCII value is 110.

Initialization of strings: Giving values to string at the time of its declaration is known as initialization
of string.

The string can be initialized as follows.

char st[ ]= “deepthi” (or) char st[ ]={‘d’, ‘e’, ‘e’, ‘p’, ‘t’, ‘h’, ‘i’, ‘\0’};

Accessing elements of a string: Similar to arrays, the subscripts are used to access the string
elements. char st[ ]= “deepthi”

Page 63

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Reading/writing Operations on Strings Reading strings:

There are three ways to read a string. They are

1. Using scanf() function


2. Using gets( ) function
3. Using getchar ( ), getch() or getche()

scanf() function: The string can be read using scanf( ) as follows scanf(“%s”, str); scanf( ) terminates
the string Whenever white space or enter key is encountered .

gets( ) function: The string can be read using gets( ) as follows gets(string); gets( ) includes white
space character and is terminated only when null character is encountered.

Using getchar ( ), getch() or getche(): It is used to read a group of characters until terminated
character is encountered. Writing strings: There are three ways to read a string.

They are
1. Using printf() function
2. Using puts( ) function
3. Using putchar ( ), putch()
1. Using printf () function: The string can be printed by using printf( ) as follows
printf(“%s”, str);
printf( ) terminates printing string Whenever white space or Null character is encountered .

2. Using puts ( ) function: The string can be read using puts( ) as follows
puts(string);
puts( ) includes white space character and is terminated when null character is encountered

3. Using putchar ( ), putch(): It is used to print a group of characters one after another until string is
terminated
i=0;
ch=putchar();
while(ch!=’*’)
{
s[i]=ch;
i++;
ch=putchar();
}

7. Write different String handling functions in C. (OR) Write various String operations (or)
String functions in C

Page 64

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Definition: String is a group of characters terminated by NULL (\0) character. In C, string constants are
enclosed within double quotes (“”). Or String is also defined as character array appended by NULL (\0)
character.

String functions for manipulating the string|:

All the string functions are available in string.h header file.

Some of String functions are: .

1. strlen(). 5. strcat().
2. strupr(). 6. strcpy().
3. strlwr(). 7. strrev().
4. strcmp().

1. strlen(): This string function is basically used for the purpose of computing the length of string.
Syntax : strlen(stringname);
Example: char str=“arvl narayana”
int length= strlen(str);
printf(“The length of the string is =%d”,length);
ouput: The length of the string is =13
2. strupr(): This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e. it converts string case sensitiveness into uppercase.

Example: char str = “deepthi”


strupr(str);
printf(“The uppercase of the string is : %s”,str);
output: DEEPTHI

3. strlwr (): This string function is basically used for the purpose of converting the case sensitiveness of the
string i.e it converts string case sensitiveness into lowercase.

Example: char str = “DEEPTHI”


strlwr(str);
printf(“The Lowercase of the string is :%s “,str);
output: deepthi
4. strcmp (): This string function is basically used for the purpose of comparing two string. This string
function compares two strings character by characters.

Thus it gives result in three cases:

Case 1: if string-1 > than string-2 then, result will be true.

Case 2: if string-1 < than string-2 then, result will be false.

Case 3: if string-1 = = to string-2 then, result will be zero.

Example:
char str1= “paarvin”;
char str2= “parnika”;
strcmp(str1,str2);
output:

Page 65

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

5. strcat(): This string function is used for the purpose of concatenating two strings ie.(merging two or more
strings)

Example: char str[]=“parvin”; char str2[] =“parnika”;


str3=strcat(str1,str2);
printf(“%s”,str1);
output:parvinparnika

6. strcpy(): This string function is basically used for the purpose of copying one string into another string.
char str1=“parvin”;

char str2[20];
str2 = strcpy(str2,str1);
printf(“%s”,str2);
output: parvin

7. strrev(): This string function is basically used for the purpose of reversing the string.

Example: char str1=“parvin”; strrev(str1);


printf(“%s”,str1);
output:nivrap
PROGRAM-1
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int len;
char st1[]="PARVIN";
char st2[]="parnika";
char st3[]="shashwat";
char st4[]="vihaan";
char st5[]="narayana";
char st6[50];
clrscr();
printf("\nst1 = %s, st2 = %s, st3 = %s, st4 = %s, st5 = %s",st1,st2,st3,st4,st5);
printf("\n\n *********** STRING OPERATIONS ********\n");
len=strlen(st1);
printf("\nLength of the given string-1 = %d",len);
strlwr(st1);
printf("\nstring-1 in lowercase = %s",st1);
strupr(st2);
printf("\nstring-2 in uppercase = %s",st2);
strcpy(st6,st3);
printf("\nstring-6 after copying = %s",st6);
strcat(st4,st3);
printf("\nstring-4 after concatenation st4 and st3 = %s",st4);
strrev(st5);
printf("\nstring-5 after string reverse = %s",st5);
if((strcmp(st1,st2))>0)
printf("\nstring-1 is bigger than str2 = %s",st1);
else
printf("\nstring-2 is bigger than str1 = %s",st2);
getch();
}

Page 66

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

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

8. Explain different character handling functions in C.


In c language we have some character manipulating functions. Some character functions are part of ctype.h,
string.h ,stdlib.h

The following are the character functions in C

1. isalnum():It checks whether given character is an alphanumeric character Syntax: isalnum (int c)
eg: isalnum(‘A’)
2. Isalpha(): It checks whether given character is an alphabetic character
Syntax: isalpha (int c) eg: isalpha(‘A’)
3. Isdigit() : It checks whether given character is digit or not.
Syntax: Isdigit (int c) eg: Isdigit (‘A’)
4. isxdigit(): it checks whether given character is a hexadecimal digit Syntax: isxdigit (int c)
eg: isxdigit(‘A’)
5. Islower( ): It checks whether given character is in lowercase or not
Syntax: islower (int c) eg: islower(‘a’)
6. Isupper( ): It checks whether given character is in uppercase or not
Syntax: isupper (int c) eg: isupper(‘A’)
7. tolower(): It converts the character to lowercase
Syntax: tolower (int c) eg tolower(‘A’)
8. toupper(): It converts the character to uppercase
Syntax: toupper (int c) eg toupper(‘a’)
9. isspace(): it checks whether given character is a white space character.
Syntax: isspace (int c) eg isspace(‘ ’)
10. ispunct(): it checks whether given character is a punct character
Syntax: ispunct (int c) eg: ispunct(‘?’)

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

9. Write about string arrays.


String Arrays: In int arrays, float arrays, char arrays, array name followed by only one subscript as shown
below,

int a[10];  integer array

float b [10];  float array

char c[10];  character array

But in string arrays array name followed by two subscripts, first subscript specifies size of the array and
second one specifies the size of the string.

Declaration of array of strings:

Page 67

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax: char arrayname[array-size][string-size];

Example: char a[5][10];

Initialization of array of strings: We can initialize array of strings in 3 ways.

Method-1: Initialing strings at the time of declaration, at the compile-time.

Example : char st[5][10]={“earth” , “water”, “fire”, “air”, “sky”};

Method-2: Initialing strings using assignment operator (=) at the compile-time.

Example: char st[5][10];

St[0] = “dharma”;

St[1] = “bhima”;

St[2] = “arjuna”;

St[3] = “nakula”;

St[4] = “sahadeva”;

Method-3: Initialing strings at the time of run-time using scanf() or gets(). But we have to use a loop.

Example: char st[5][10];


int i
for(i=0;i<5;i++)
scanf(“%s”,st[i]);

Program to read and write (display) array of strings

#include<stdio.h>
#include<conio.h>

void main()
{
int i,size;
char st[10][20];
clrscr();
printf(" \n enter array size : ");
scanf("%d",&size);
printf(" \n enter %d strings into array\n ",n);
for(i=0;i<size;i++)
{
printf(" \n enter string - %d into array : ",i+1);
scanf("%s",st[i]);

Page 68

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

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

Page 69

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

UNIT-4

Functions: Introduction – using functions – Function declaration/ prototype – Function definition –


function call – return statement – Passing parameters – Scope of variables – Storage Classes – Recursive
functions.
Structure, Union, and Enumerated Data Types: Introduction – Nested Structures – Arrays of
Structures – Structures and Functions– Union – Arrays of Unions Variables – Unions inside Structures –
Enumerated Data Types.
Functions

Top down approach:

Top down approach is a process of splitting the main task into several sub tasks. Again these sub tasks can be
spitted (divided) into simpler tasks.

Each subtask is known as function in C.

Advantages:

1. It saves main memory


2. It facilitates readability
3. Error finding and debugging is easy
4. It minimizes program complexity.

1. Write about Functions in C.


Function: Function is a self contained block of statements that does some specific and well-defined task. In C,
Programs are divided into small segments known as functions. C contains at least one function called main ().

Basically there are two types of functions. They are

1. Library functions
2. User-defined functions
1. Library functions: These are functions that come along with the language and are prewritten and
pretested. These functions can be used by programmers during program development
Example: clrscr(),scanf(),getch(),printf() .... etc
2. User defined functions: The functions that are defined by users are known as user defined functions.
Example:

Page 70

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

void display()
{
printf(“ADITYA DEGREE COLLEGE ”);
}

The function that is invoked (or) called is known as called function and the function from which another
function is called (or) invoked is known as calling function.

Function Definition: When a function is defined, space is allocated for the function in memory.

Function definition consists of two parts, they are

1) function Header 2) function body

Syntax Example

Function Declaration / Function Prototype:

Function Declaration or prototype is an indication to the compiler about the function name, returntype,
number of parameters and type of parameters passed to a function.

Syntax: returntype functionname(parameters);

Example: void sum(int a,int b);

Note: If the function declaration does not specify any return-type, then by default a function returns an integer
value.

The function declaration or prototype can be eliminated when we write the user defined function above the
main ().

Page 71

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Function Call: The function can be invoked either from main () or other functions. When a function is
invoked the compiler jumps to the called function and execute the statements within it. Once the called
function is executed, the control passes back to the calling function.

Syntax: functionname(arg1, arg2 ...);

Eg: swap(a,b)

ACTUAL PARAMETERS AND FORMAL PARAMETERS:

Actual parameters: parameters with which functions are called or invoked are known as actual parameters.
These are also called as arguments.

Formal Parameters: Parameters with which functions are developed are known as formal parameters

2. Write short notes on Return Statement in C?

Return statement: A function may or may not return a value. If it returns, it returns only one value. The
return statement is used to return a value to the calling function.

Syntax: return(variable/value); or return(expression);

 Example-1: return 0;
 Example-2: return (x);
 Example-3: return (a+b); or return a*b;

A function that has void as its return type doesn’t return a value to the calling function.

 The return statement should be the last statement used in the functions.
 When a function uses return statement, it should specify the return type.

3. Explain different types of functions based on number of arguments and return statement. Or Explain
different types of user defined functions.

Definition: Function is a self contained block of statements that does some specific and well-defined task.

There are four types of functions based on number of arguments and return statements. They are

 No parameters and no return type


 With parameters but no return type
 No parameters but with return type

Page 72

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

 With parameters and with return type

1. No parameters and no return type: In this function there are no parameters and no return statement.
Therefore we need define function with void data type.

/* no parameters and no return type */


#include<stdio.h>
#include<conio.h>
void sum()
{
int a,b,c;
printf("\n enter 2 values : ");
scanf("%d%d",&a,&b);
c=a+b;
printf("\n sum of 2 numbers =%d",c);
}
void main()
{
clrscr(); // predefined function
sum(); // user-defined calling function , first time
sum(); // user-defined calling function, second time
sum(); // user-defined calling function , third time
getch(); // predefined function
}

2. With parameters but no return type: In this function we have to mention parameters in the called function
and no need to mention the return statement. In calling function we can use values or variables as function
arguments. Therefore we need to define function with void data type.

Example:

Sum(2,3); // calling function with values

Sum(a,b); // calling function with variables

/* with parameters and no return type */


#include<stdio.h>
#include<conio.h>
void sum(int x,int y) //called function with parameters with no return type
{
int c;
c=x+y;
printf("\n\nSum of %d and %d = %d",x,y,c);
}
void main()
{

Page 73

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

int a,b;
clrscr(); // predefined function
printf("\n\nEnter 2 values : ");
scanf("%d%d",&a,&b);
sum(a,b); // user-defined calling function with variable arguments
sum(6,7); // user-defined calling function with value arguments
getch(); //predefined function
}

3. No parameters but with return type: this function does not contain parameters but it contains return
statement i.e. called function gets a value. Therefore the result should be given in calling function.

/* no parameters and with return type */


#include<stdio.h>
#include<conio.h>
int sum() //called function without parameters and with return type
{
int a,b;
printf("\n\nenter two numbers : ");
scanf("%d%d",&a,&b);
return a+b; //returns value to result variable in main()
}
void main()
{
int result;
clrscr(); // predefined function
result = sum(); //called function which returns a value to result variable.
printf("\n\n result = %d ",result);
getch(); //predefined function
}
4. With parameters and with return type: In this function the calling function pass the arguments to the
called function and get the return value.

/* with parameters and with return type */


#include<stdio.h>
#include<conio.h>
int sum(int x,int y) // function with arguments and with return type.

Page 74

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

{
return x+y; //return statement
}
int product(int x,int y) // function with arguments and with return type.
{
return x*y; //return statement
}
void main()
{
int a,b,result;
clrscr(); // predefined function
printf("\n\n enter two numbers : ");
scanf("%d%d",&a,&b);
result=sum(a,b); //called function which returns a value
printf("\n\n sum = %d ",result);
result=product(a,b); //called function which returns a value
printf("\n\n product = %d ",result);
getch(); //predefined function
}

4. Write about call-by- value and call-by-reference in c(************).

Call by value in C:

 In call by value method, the value of the actual parameters is copied into the formal parameters. In
other words, we can say that the value of the variable is used in the function call in the call by value
method.
 In call by value method, we cannot modify the value of the actual parameter by the formal parameter.
 In call by value, different memory is allocated for actual and formal parameters since the value of the
actual parameter is copied into the formal parameter.
 The actual parameter is the argument which is used in the function call whereas formal parameter is
the argument which is used in the function definition.

Call by Value Example: Swapping the values of the two variables

#include <stdio.h>
void swap (int a, int b)
{
int temp;
temp = a;
a=b;

Page 75

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
}

void main()
{
int a = 10;
int b = 20;
printf("\n Before swapping the values in main a = %d, b = %d",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}

Call by reference in C:

 In call by reference, the address of the variable is passed into the function call as the actual parameter.
 The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
 In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address of the
actual parameters, and the modified value gets stored at the same address.

Call by reference Example: Swapping the values of the two variables

#include <stdio.h>
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
void main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b); //call –by -reference
printf("After swapping values in main a = %d, b = %d\n",a,b);

Page 76

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

5. Write about scope of the variables in c.


In c language all variables or constants have a defined scope. Scope of the variable specifies the visibility and
accessibility of variables used in the program. Scope is the region over which the variable is visible. A
Variable in C has four types of Scope.
They are
1. Block Scope
2. Function Scope
3. Program Scope
4. File Scope
1. BLOCK SCOPE: A group of statements enclosed within opening and closing braces ( { } ). Blocks may
be nested in C, for example a main () block may contain while block. A variable declared in a block is
accessible within the block and also in inner blocks of that block, but is not accessible to outside.
If an inner block contains a variable with same name as outer block, then the visibility of the outer block
variable ends at the point of declaration by inner block.
Example:

2. FUNCTION SCOPE: The variables that are declared in the function are called local variables and are
visible within the defined block.
Example:

Page 77

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

void main()
{
int a=5; // local variable.
...............
…............
}
In c, only goto label has function scope and there cannot be same label name inside the function. The function
scope is applicable with goto label names. i.e., this means programmer cannot have the same label name inside
a function.
Example:
void main()
{
ABC: // goto label ABC has function scope
.......
.....
......
goto ABC;
}

3. PROGRAM SCOPE:
Global variables are having program scope.
 The variables declared outside the main () are called Global variables and can be accessed from any
point in the program.
 These variables are created in the beginning and remain in memory until execution of program ends.
 When global and local variables have same name, the compiler access the local variable. And global
variable is accessed by using Scope resolution operator (::).
Example:
#include<stdio.h>
#include<conio.h>
void display();
int x=10; //global variable
void main()
{
int x=5; // local variable
printf("\n \n local variable () x = %d",x);
printf("\n \n global variable() x = %d",::x); // to access global variable
display();
getch();
}
void display()

Page 78

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

{
printf("\n \n in the sub function display() x = %d",x); //global variable
}

4. FILE SCOPE: when a global variable is accessible until the end of the file then the variable is said to have
file scope. To provide a file scope for a variable then we have to declare that variable with static keyword
before the datatype. It can be accessed from anywhere in the file
Syntax: static datatype variable=value;

Example:
int a = 5; // program scope
static int b = 0; // file scope
static float pie = 3.14; // file scope
void main()
{
int n=6; // block scope */
printf(“ n = %d”,n);
}

Note: These file scope variables are useful when the programmer write his own header files.

6. Write about Storage classes in C

The storage class of a variable defines the scope (visibility) and Lifetime of a variable. Scope is defined as part
of memory (region) over which a variable is visible & Lifetime is the period of time up to which a variable
resides in the memory. In addition it specifies where the variable is stored i.e. either in Main memory or CPU
registers & also it specifies the default value of a variable.

Syntax : <storage-class-specifier> datatype variable=value;

Basically there are 4 types of storage classes in C. They are:

1. Automatic Storage Class


2. Register Storage Class
3. Static Storage Class
4. External Storage Class

1. Automatic Storage Class: Automatic storage class is the default storage class and is defined with the
keyword “auto”. By default, all the local variables declared inside the function are of automatic storage class

Page 79

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

type. The variables of type auto are stored in Main Memory (Stack). Its scope is visible within the defined
block and its lifetime is until it comes out of block. Its default value is Garbage value

Syntax: auto datatype variablename;

Example: auto int x;

2. Register Storage Class: The Register storage class variables are defined with the keyword “register”. The
variables of type register are stored in CPU Registers. Its scope is visible within the defined block and its
lifetime is until it comes out of block. Its default value is Garbage value

Syntax: register datatype variablelist;

Example: register int x;

If we store same variable in the register memory then we can access that memory location directly without
using the Address operator.

{ In the above program we have declared two variables num1,num2. These two variables are stored in RAM.
Another variable is declared which is stored in register variable.Register variables are stored in the register of
the microprocessor. Thus memory access will be faster than other variables. If we try to declare more register
variables then it can treat variables as Auto storage variables as memory of microprocessor is fixed and
limited.}

If we store same variable in the register memory then we can access that memory location directly without
using the Address operator.

3. Static Storage Class: The Static storage class variables are defined with the keyword “static”. The
variables of type static are stored in Main Memory (data segment). Its scope is visible within the defined
block and its lifetime is that its value persists between the function calls. Its default value is “zero”

Syntax: static datatype variable;

Example: static int x;

Program for static variables

#include<stdio.h>
#include<conio.h>
void display()
{
auto int a=1;
static int s=1;
printf("\nauto variable a = %d",a);
printf("\nstatic variable s = %d",s);

Page 80

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

a++;
s++;
}
void main()
{
clrscr();
printf("\n\n\n first call of display() ");
display();
printf("\n\n\n second call of display() ");
display();
printf("\n\n\n third call of display() ");
display();
}
Example: static int x;

External Storage Class: The External storage class is defined with the keyword “extern”. The variables of type
extern are stored in Main Memory(Data segment). Its scope is global i.e. Visible to all functions in a
program and its lifetime is as long as the program execution comes to end. Its default value is “zero”.

Syntax: extern datatype variablelist;

Example: extern int x;

#include<stdio.h>
#include<conio.h>
extern i;
void abc()
{
printf("\nabc() i = %d ",i);
}
void main()
{
clrscr();
printf("\n main() i = %d ",i);
abc();
getch();
}
int i = 20;
output

Page 81

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

*******************************************
Recursion
7. Write about recursion in C.
Definition: Recursion is a function which calls by itself in the same function for number of times.
Recursion rules or characteristics:
 A recursive function is defined as a function which calls by itself to solve a smaller version of its task
until a final call is made which does not require a call to itself.
 The Recursive process is, in which a function calls by itself directly or indirectly.
 Each time a function calls to itself must be closer to the solution
 There must be some condition to stop the process of computation otherwise it may generates infinite
loop.

Every recursive solution has two cases. They are


1. Base Case
2. Recursive Case
1. Base Case: In this, the problem is simply solved directly without making further calls
Example:
if (r = = 0)
return y;
2. Recursive Case: In this, the problem is solved by calling the same function within itself any
number of times
Example:
return gcd(y,r); // recursion call

Page 82

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Program to find GCD of two numbers using Recursion:


#include<stdio.h>
int gcd(int x, int y)
{
int r=x%y;
if (r = = 0)
return y; // base call
else
return gcd(y,r); // recursion call
}
void main()
{
int a,b,c;
clrscr();
printf(“ enter two numbers : ”);
scanf(“%d%d”, &a, &b);
c=gcd(a,b);
printf(“\n gcd of %d and %d is %d”,a,b,c);
}
Program for Factorial using Recursion:
#include<stdio.h>
int fact(int n)
{
if (n==0)
return 1;
else
return n* fact(n-1); // Recursion CALL
}
void main()
{
int n,result;
scanf(“%d”, & n);
result=fact(n);
printf(“%d”,result);
}

8. Write about different types of recursions in c

Definition: Recursion is a function which calls by itself in the same function for number of times.
Recursive functions are of 4 types. They are
1. Direct recursion
2. Indirect Recursion
3. Tail-recursion
4. Linear or Tree Recursion
1. Direct Recursion: A Function is said to be directly recursive if it explicitly calls within itself.
Here Function fact() calls itself for all positive values of n so it is called as direct recursion.

Page 83

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

2. Indirect Recursion:
A function is indirectly recursive if it contains a call to another function that automatically calls it.
Example:

3. Tail-Recursion: A recursive function is tail recursive if no operations are pending to be performed when
the recursive function returns its caller.
 Tail recursive function is efficient to use as the amount of information that has to be stored on
the system stack is independent of the number of recursive calls.
 Non-tail recursive function: whenever there is a pending operation to be performed, the
function becomes non-tail recursive.
Program for Factorial using Recursion:
#include<stdio.h>
int fact(int n)
{
if (n==0)
return 1;
else
return n* fact(n-1); // Recursion CALL
}
void main()
{
int n,result;
scanf(“%d”, & n);
result=fact(n);
printf(“%d”,result);
}

Page 84

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Recursion using Stack

4. Linear & Tree Recursion: In linear recursive if the pending operation (if any) does not make another
recursive call to the function.
Example: In factorial program only multiplication is performed no recursive call to fact.
In Tree recursive (non-Linearly recursive) if the pending operation makes another recursive call to the
function recursive call to the function
Example: In case of Fibonacci function “fib()” in which the pending operations , recursively calls fib
function.
// C program for Fibonacci series
#include <stdio.h>
int fib(int n) // Function for fibonacci
{
if (n == 0) // Stop condition
return 0;
if (n == 1 || n == 2) // Stop condition
return 1;
else
return (fib(n - 1) + fib(n - 2)); // Recursion function
}
void main()
{
int n = 5; // Initialize variable n.
printf("Fibonacci series of %d numbers is: ",n);
for (int i = 0; i < n; i++) // for loop to print the fiboancci series.
{
printf("%d ", fib(i));
}
getch();
}

Page 85

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

9. Write Differentiate between Recursion & Iteration.

Differentiate between Recursion & Iteration.

RECURSION ITERATIONS
1. Iterative is statements or Instructions –
1. Recursive is a function which calls by itself
are loop based repetitions of a process
2. Recursion Uses selection structure 2. Iteration uses repetition structure
3. Infinite recursion occurs if the recursion
step does not reduce the problem in a 3. An infinite loop occurs with iteration if
manner that converges on some the loop-condition test never becomes
condition.(base case) false

4. Recursion terminates when a base case is


4. Iteration terminates when the loop
recognized
condition fails Recursion
5. Recursion is usually slower then iteration
5. Iteration does not use stack so it's faster
due to overhead of maintaining stack
than recursion
6. Recursion uses more memory than iteration
6. Iteration consume less memory
7. infinite looping uses CPU cycles
7. Infinite recursion can crash the system
repeatedly

8. Recursion makes code smaller 8. Iteration makes code longer


9. It follows top-down approach
9. It follows bottom up approach

10. Write about towers of HONAI or application of recursion.


TOWERS OF HONAI:

Page 86

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Towers of HONAI is to move the disks on source tower ‘A’ to destination tower ‘B’ using temporary tower
‘B’.
The towers of HONAI are one of the main applications of a recursion.
The main objective of the towers of Hanoi is if we can solve (n-1) cases then you can easily solve the nth case.

It is one of the applications of recursion. The problem of towers of HONAI is to move the disks on source
tower ‘S’ to destination tower ‘D’ using temporary tower ‘T’.
Rules:
1. Only one disk can be moved at a time.
2. A disk can only be moved if it is the uppermost disk on the tower.
3. No bigger disk may be placed on top of a smaller disk.
Process (or) algorithm
If n=1 Move S to D using T
Otherwise
a. Move n-1 disks from source to Temporary using Destination
b. Move Source to Destination
c. Move n-1 disks from Tempary to Destination using Source
Program: towers of HANOI
#include <stdio.h>
#include <conio.h>

void Hanoi(int n, char a, char c, char b)


{
if (n == 1)
{
printf("\n Move from %c to %c", A, C);
return;
}
hanoi(n-1, A, B, C);
printf("\n Move from %c to %c", A, C);
hanoi(n-1, B, C, A); }
void main()
{
int n ;

Page 87

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

printf(“enter the no of disks:”);


scanf(“%d”,&n);
hanoi(n, 'A', 'B', 'C');
}

Passing array as function parameters

11. Explain about passing arrays as function parameters.

Like variables of other data types, we can also pass an array to a function as parameters.

 Passing 1D-array as function parameters


 Passing 2D-array as function parameters

Passing 1D-array as function parameters

Passing 1D-array as function parameters: This is also called as one dimensional array for inter-function
communication. We can pass 1D-array as function parameters in three methods. They are

 Method-1: passing individual elements // functionname( arrayname[index])


 Method-2: Passing array with size or Passing entire array // functionname( arrayname)
 Method-3: Passing array to function using call by reference // functionname(&arrayname[index])

Method-1

Passing individual elements: The individual elements of array can be passed either by passing values (Or)
passing addresses. Declaring blank subscript notation [] is the widely used technique.

Syntax :
return_type functionname(datatype variable) //called function or function definition
{
…..
}
Syntax:
functionname( arrayname[index]); //calling function - passing a single element in the array

PROGRAM

#include<stdio.h>
void modify(int n) //called function or function definition
{
n=n+10;
printf(“ modified value : %d”,n);
}
void main()
{
int a[5]={50,35,26,40,50};
modify(a[2]); //calling function - passing a single element in the array
}
Output : 36
Method-2

Page 88

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Passing array with size or Passing entire array : The array name refers to base address (first element
address) of an array. The addresses of rest of elements are calculated by arrayname and the index value.

Syntax :
return_type function(type arrayname[SIZE]) //called function or function definition
{
…..
}
Syntax:
functionname( arrayname); //entire array in calling function

Program

#include<stdio.h>
#include<conio.h>
void marks(int x[]) //called function or function definition
{
int i,j;
printf("\n before modification array elements : ");
for(i=0;i<5;i++)
printf("%4d",x[i]);

printf("\n after modification array elements \n");


for(i=0;i<5;i++)
printf("%4d",x[i]+10); // updating marks by 10-- x[][]+10
}

void main()
{
int a[]={45,55,65,26,48}; // a[] is 1d-array.
clrscr();
marks(a); // passing entire array as arguments in calling function
getch();
}
Output : 55 65 75 36 58
Method-3

Passing 1D-array to function using call by reference: When we pass the address of an array while calling a
function then this is called function call by reference. When we pass an address as an argument, the function
declaration should have a pointer as a parameter to receive the passed address.

Syntax :
return_type function(type *arrayname) // pointer as a parameter in called function
{
…..
}
Syntax:
functionname(& arrayname[index]); //reference(&) of an array element in calling function .

Program

Page 89

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

#include <stdio.h>
void display( int *num) // pointer as a parameter in called function
{
printf("%d ", *num);
}

int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
display (&arr[i]); // (reference) Passing addresses of array elements
}

return 0;
}

Passing 2D-array as function parameters

Passing 2D-array as function parameters: This is also called as two dimensional array for inter-function
communication. We can pass 2D-array as function parameters in four methods . They are

 Method-1: passing individual elements // functionname( arrayname[row][col])


 Method-2: Passing array row // functionname( arrayname[row])
 Method-2: Passing array with size or Passing entire array // functionname( arrayname)
 Method-4:Passing array to function using call by reference// functionname(&arrayname[row][col])

Method-1

Passing individual elements: The individual elements of array can be passed either by passing values (Or)
passing addresses. Declaring blank subscript notation [] is the widely used technique.

Syntax :
return_type functionname(datatype variable) //called function or function definition
{
…..
}
Syntax:
functionname( arrayname[row][column]); //calling function - passing a single element in the array

PROGRAM

#include<stdio.h>
void modify(int n) //called function or function definition
{
n=n+10;
printf(“ modified value : %d”,n);
}
void main()
{
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};

Page 90

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

modify(a[1][1]); //calling function - passing a single element in the array


}
Output:15

Method-2

Passing array row: A row of 2D-array is passed as argument in calling function with rownumber.

Syntax :
return_type function(type arrayname[row]) //called function or function definition
{
…..
}
Syntax:
functionname( arrayname[row]); //calling function with row number

Program

#include <stdio.h>
void changerow( int x[]) // row as a parameter in called function
{
for (int i=0; i<2; i++)
{
Printf(“%4d”,x[i]+10);
}

void main()
{
int a[2][2]={{1,2},{3,4}}; // a[][] is 2d-array.
changerow(arr[1]); // Passing row-1 of array as argument.
}

Method-3

Passing 2D array with size or Passing entire 2D array: The array name refers to base address (first element
address) of an array. The addresses of rest of elements are calculated by arrayname and the index value.

Syntax :
return_type function(type arrayname[row][column]) //called function or function definition
{
…..
}
Syntax:
functionname( arrayname); //calling function

Page 91

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Program

#include<stdio.h>
#include<conio.h>
void modify(int x[2][2]) //called function or function definition
{
int i,j;
printf("\n before modification array elements \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%4d",x[i][j]);
printf("\n");
}
printf("\n after modification array elements \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%4d",x[i][j]+10); // modifying x[][]+10
printf("\n");
}
}
void main()
{
int a[2][2]={{1,2},{3,4}}; // a[][] is 2d-array.
clrscr();
modify(a); // passing 2d-array as arguments in calling function
getch();
}
Method-4

Passing 2D-array to function using call by reference: When we pass the address of an array while calling a
function then this is called function call by reference. When we pass an address as an argument, the function
declaration should have a pointer as a parameter to receive the passed address.

Syntax :
return_type function(type *arrayname) // pointer as a parameter in called function
{
…..
}
Syntax:
functionname(& arrayname[row][column]); //reference(&) of an array element in calling function .

Program

#include <stdio.h>
void display( int *n) // pointer as a parameter in called function
{
printf("%d", *n);
}

void main()
{
int a[][] = {{1, 2},{3, 4}};

Page 92

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

for (int i=0; i<10; i++)


for (int j=0; j<10; j++)
{
display (&arr[i][j]); // Passing addresses of array elements
}

}
Program for matrix addition and subtraction using functions

#include<stdio.h>
#include<conio.h>
void addmat(int x[2][2],int y[2][2]) // called function with 2d array arguments.
{
int i,j,c[2][2];
for(i=0;i<2;i++)
for(j=0;j<2;j++)
c[i][j]=x[i][j]+y[i][j];

printf("\n after matrix addition \n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%4d",c[i][j]); // printing c[][] sum of a and b
printf("\n");
}
}
void submat(int x[2][2],int y[2][2])
{
int i,j,c[2][2];
for(i=0;i<2;i++)
for(j=0;j<2;j++)
c[i][j]=x[i][j]-y[i][j];

printf("\n after matrix subraction \n");


for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%4d",c[i][j]); // printing c[][]
printf("\n");
}
}
void main()
{
int a[2][2]={{9,8},{7,6}}; // a[][] is 2d-array.
int b[2][2]={{5,4},{3,2}}; //b[][] is 2d-array.
clrscr();
addmat(a,b); // calling function passing 2d-array as arguments.
submat(a,b); // calling function passing 2d-array as arguments.
getch();
}

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

Page 93

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Structures
INTRODUCTION TO STRUCTURE:

 As we know that Array is collection of the elements of same data type, but many time we have to store
the elements of the different data types.
 Suppose in library books record is to be stored, then for storing the record we have to group together
all the information such as book-no, book-name, author, price which may be of different data types.
 Ideally Structure is collection of different variables under single name.
 Basically Structure is for storing the complicated data.
 A structure is a convenient way of grouping different data types of related information together.

12. Write about structures in c (************).


Definition of Structure: : Structure is a user-defined data-type and it is a collection of heterogeneous data
type elements. It composes different variable values into single entity. (or) Structure is a user-defined data-
type is composition of the different variables of different data types, grouped under same name. .

Some Important Points Regarding Structure in C Programming:

 “Struct” keyword is used to declare structure.


 Members of structure are enclosed within opening and closing braces{}.
 Declaration of Structure reserves no space.
 Memory is created, very first time when the variable is created /Instance is created.

Utilization of structures in C language: structure is a user-defined data-type i.e. the programmer himself
should prepare structure data-type. This data type is prepared by deriving built-in data-types (int, char…).

The following steps for Utilization of structures in C language.

Step-1: define a structure

Step-2: declare structure variables.

Step-3: initialize structure variables.

Step-4: accessing structure members in the structure variable.

Step-1: define a structure: structure should define with the “struct” keyword and with tag-name (optional).

Syntax: Example:

Page 94

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

struct <tag-name> struct Book


{ {
data-type-1 variable-1; int bno;
data-type-2 variable-2; char bname[20];
data-type-3 variable-3; float bprice;
}; };

Step-2: declare structure variables: we can define structure variables in program only after defining the
structure. Declaring structure variables using two words i.e. struct (keyword) and tag-name.

Syntax:
Struct <tag-name> var-1,var-2,….var-n;

Example:
struct Book b1,b2;

Another method for Defining structure and structure variables

Syntax: Syntax:
struct <tag-name> struct Book
{ {
data-type-1 variable-1; int bno;
data-type-2 variable-2; char bname[20];
data-type-3 variable-3; float bprice;
} stuct-var-1,struct-var-2; }b1,b2;

or

Note: In the below case in a program we can create only one structure

Syntax: Syntax:
struct struct
{ {
data-type-1 variable-1; int bno;
data-type-2 variable-2; char bname[20];
data-type-3 variable-3; float bprice;
} stuct-var-1,struct-var-2; }b1,b2;
Step-3: initialize structure variables:

Syntax:
Struct <tag-name> struct-variable = {val-1,val-2,…};

Example:
struct Book b1 = {1001, “c-programming”, 450.50 };
struct Book b2 = {2001, “java-programming”, 650.50 };

Note: here we have to follow structure definition order for assign values

Step-4: accessing structure members in the structure variable: we can access structure members by using
“dot” operator.

Syntax: Structure-variable .structure-member;


Example:

Page 95

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

b1.bno;
b1.bname;
b1.bprice;

Example: to print the structure members:

 Printf(“\n book number = %d”,b1.bno);


 Printf(“\n book name = %s”,b1.bname);
 Printf(“\n book price = %f”,b1.bprice);

Limitations of C Structures
1. The C structure does not allow the struct data type to be treated like built-in data types.
2. We cannot use operators like +, - , * etc. on Structure variables.
3. No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed by any
function, anywhere in the scope of the Structure.
4. Functions inside Structure: C structures do not permit functions inside Structure
5. Static Members: C Structures cannot have static members inside their body

Example: Program
#include<stdio.h>
#include<conio.h>
struct Book // defining structure
{
int bno;
char bname[20];
float price;
};
void main()
{
struct Book b1={1001,"c-programming",450.50}; // declaring and initializing structure variable b1
struct Book b2={2001,"data structues",565.50}; // declaring and initializing structure variable b2
struct Book b3={3001,"java programming",999.99};// declaring and initializing structure variable b3
clrscr();
printf("\n*** acessing structure members ***\n"); // accessing structure members bno,bname,price
printf("\n BOOK-1 bno = %d bnmae = %s price = %f",b1.bno,b1.bname,b1.price);
printf("\n BOOK-2 bno = %d bnmae = %s price = %f",b2.bno,b2.bname,b2.price);
printf("\n BOOK-3 bno = %d bnmae = %s price = %f",b3.bno,b3.bname,b3.price);
getch();
}

0utput

Page 96

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

13. Write about nested structures


Nested Structures: Nested structure means structure inside another structure.

C provides us the feature of nesting one structure within another structure by using which, complex data types
are created.

{For example, we may need to store the DOB of an entity student in a structure. The attribute DOB may also
have the subparts as day, month, and year. Hence, to store DOB of student, we need to store the DOB of the
student into a separate structure and nest the structure DOB into the structure student. }

The structure can be nested in the following ways:

1. By separate structure
2. By Embedded structure

1. Separate structure: Here, we create two structures, but the dependent structure should be used inside the
main structure as a member. Consider the following example.

struct Date // nested structure


{
int dd;
int mm;
int yy;
};
struct student // main structure
{
int id;
char name[20];
struct Date dob; // Date structure is nested
}st1;

2. Embedded structure: The embedded structure enables us to declare the structure inside the structure.
Hence, it requires less line of codes but it cannot be used in multiple data structures. Consider the following
example.

struct student
{

Page 97

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

int id;
char name[20];
struct Date
{
int dd;
int mm;
int yy;
}dob;
}st1;

Accessing nested structures: We can access the member of the nested structure by
Outer_Structure.Nested_Structure.member as given below:
St1.dob.dd
St1.dob.mm
St1.dob.yy
----------------------------------------------------------------------------------------------

14. Write about Array of structures


Array of structures: If the individual cell of an array is a structure, then that declaration is known as Array of
Structures.

1. The most common use of structure in C programming is an array of structures.


2. To declare an array of structure, first the structure must be defined and then an array variable of that type
should be defined.
3. For Example − struct student st[4]; //4 elements in an array of structures of type ‘student’

Step-1: first define a structure as shown below

struct student
{
long int id; -- 4 bytes
char name[5]; -- 5 bytes
float mpercent; -- 4 bytes
};

Step-2: array variable of that type(struct student) should be defined as shown below.

struct student st[4]; //4 elements in an array of structures of type ‘student’

Size of each array element = 4+5+4=13

Page 98

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Total array st[4] size = 13 x 4 = 52 bytes

Program

#include <stdio.h>
#include <conio.h>
#include<string.h>
struct student //define structure
{
int id;
char name[10];
float mpercent;
};
void main()
{
long int i;
struct student st[4]; // declare array
// 1st student's data stores in s[0]
st[0].id=1;
strcpy(st[0].name, "parvin");
st[0].mpercent = 86.5;
// 2nd student's data stores in s[1]
st[1].id=1;
strcpy(st[1].name, "parnika");
st[1].mpercent = 96.5;
// 3rd student's data stores in s[2]
st[2].id=3;
strcpy(st[2].name, "shashwat");
st[2].mpercent = 97.5;
// 4th student's data stores in s[3]
st[3].id=4;
strcpy(st[3].name, "vihaan");
st[3].mpercent = 98.5;
for(i=0; i<4; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", st[i].id);
printf(" Name is: %s \n", st[i].name);
printf(" Percentage is: %f\n\n",st[i].mpercent);
}
}

Output

Page 99

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

15. Write about Structures as function parameters


A function may access the members of a structure by passing structures to functions in the following ways:
1. Passing individual members
2. Passing entire structure

Passing Individual Members:


To pass individual member to structure we pass the structure variables to a function just as we
Pass normal variables

Example:
struct Point // structure defination
{
int x;
int y;
};
void display(int a , int b) // function declaration
{
printf(“\n a= %d b = %d”,x,y);
}
void main()
{
struct Point p={3,4}; // creating structure variable
display(p.x,p.y); // call function with structure-members as parameters
}

Passing entire structure:We can pass entire structure to function. When a structure is passed as an argument
to function it is passed using the call by value method. The general syntax for passing a structure to a function
is as follows
Syntax:returntype functioname(struct struct-name struct-var);
Example: void display(struct Student s);
Example:
struct Point // structure defination
{

Page 100

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

int x;
int y;
};
void display(struct Point p) // function declaration
{
printf(“\n x= %d y = %d”,s.x,s.y);
}
void main()
{
struct Point p={3,4}; // creating structure variable
display(p); // call function with entire structure as parameters
}

Self referential Structures: These are structures that contain a reference to data of its same type

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

Unions
Like Structures, union is a user defined data type. In union, all members share the same memory location.

16. Write about unions in C.


Definition of Union: Union is a user-defined data-type and it is a collection of heterogeneous data type
elements. It composes different variable values into single entity but all members share the same memory
location. (or) Union is a user-defined data-type is composition of the different variables of different data
types, grouped under same name but all members share the same memory location.

Page 101

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Utilization of unions in C language: union is a user-defined data-type i.e. the programmer himself should
prepare union data-type. This data type is prepared by deriving built-in data-types (int, char…).

The following steps for Utilization of unions in C language.

Step-1: define a union

Step-2: declare union variables.

Step-3: initialize union variables.

Step-4: accessing union members in the union variable.

Step-1: define a union: union should define with the “union” keyword and with tag-name (optional).

Syntax: Example:
union <tag-name> union Book
{ {
data-type-1 variable-1; int bno;
data-type-2 variable-2; char bname[20];
data-type-3 variable-3; float bprice;
}; };

Step-2: declare union variables: we can define union variables in program only after defining the union.
Declaring union variables using two words i.e. union (keyword) and tag-name.

Syntax:
union <tag-name> var-1,var-2,….var-n;

Example:
union Book b1,b2;

Another method for Defining union and union variables

Syntax: Syntax:
union <tag-name> union Book
{ {
data-type-1 variable-1; int bno;
data-type-2 variable-2; char bname[20];
data-type-3 variable-3; float bprice;
} stuct-var-1,struct-var-2; }b1,b2;

Step-3: initialize union variables:

Page 102

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax:
union <tag-name> union -variable = {val-1,val-2,…};

Example:
union Book b1;
b1.bno = 1001;
strcpy(b1.bname, “c-programming”);
b1.bprice= 450.50;

Note: here in unions we can initialize only one member at a time

Step-4: accessing union members in the union variable: we can access union members by using “dot”
operator.

Syntax: union -variable . union -member;


Example:
b1.bno;
b1.bname;
b1.bprice;
Example: to print the union members:

 Printf(“\n book number = %d”,b1.bno);


 Printf(“\n book name = %s”,b1.bname);
 Printf(“\n book price = %f”,b1.bprice);
Note: here it displays only one value of the above

17. Write about Array of unions.


Array of unions: If the individual cell of an array is a union, then that declaration is known as Array of
unions.

Step-1: first define a union as shown below

union student
{
long int id; -- 4 bytes
char name[5]; -- 5 bytes
float mpercent; -- 4 bytes
};

Step-2: array variable of that type(struct student) should be defined as shown below.

struct union st[4]; //4 elements in an array of union of type ‘student’

size: st[4] =4*5=20 bytes

Note: in array-unions one array location stores only one member-value at time

#include <stdio.h>
#include <conio.h>

Page 103

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

#include<string.h>
union student
{
long int id;
char name[10];
float mpercent;
};
void main()
{
int i;
union student st[4];
clrscr();
st[0].id=1;
st[1].id=2;
st[2].id=3;
st[3].id=4;
for(i=0; i<4; i++)
{
printf(" Records of STUDENT -- id : %d \n", i+1);
printf(" Id is: %d \n", st[i].id);
}
strcpy(st[0].name, "parvin");
strcpy(st[1].name, "parnika");
strcpy(st[2].name, "shashwat");
strcpy(st[3].name, "vihaan");
for(i=0;i<4;i++)
{
printf(" student names in the record\n ");
printf(" Name is: %s \n", st[i].name);
}
st[0].mpercent = 86.5;
st[1].mpercent = 96.5;
st[2].mpercent = 97.5;
st[3].mpercent = 98.5;
for(i=0;i<4;i++)
{
printf(" student percentage in the record \n");
printf(" Percentage is: %f\n\n",st[i].mpercent);
}
}

18.Write about unions in structures(5m)


Unions in structures: This is similar to nested structures, unions in structures saves the memory.

Example program

/* program for unions in structures*/


#include<stdio.h>
#include<conio.h>
struct Emp //defining structure
{
union // defining union

Page 104

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

{
int eno;
float esal;
}u; // union variable
};

void main()
{
struct Emp e; //structure variable
clrscr();
e.u.eno=101; // assigning value struct-union-member
printf("e.u.eno = %d", e.u.eno);
e.u.esal=12000.50; // assigning value struct-union-member
printf(" e.u.esal = %f",e.u.esal);
getch();
}

19. Write difference between structure and union(*********)


Struct Union
1. The struct keyword is used to  The union keyword is used to define union.
define a structure.
2. When the variables are declared in a  When the variable is declared in the union, the
structure, the compiler allocates compiler allocates memory to the largest size
memory to each variables variable member. The size of a union is equal
member. The size of a structure is to the size of its largest data member size.
equal or greater to the sum of the
sizes of each data member.
3. Each variable member occupied a  Variables members share the memory space of
unique memory space. the largest size variable.
4. Changing the value of a member  Changing the value of one member will also
will not affect other variables affect other variables members.
members.
5. Example:  Example:
struct Book union Book
{ {
int bno; int bno;
char bname[20]; char bname[20];
float bprice; float bprice;
}b1; }b1;
6. In the Above Example struct  In the Above Example union variable b1
variable b1 occupies 26 (2+20+4) occupies 20 bytes (bname is highest occupied
bytes variable-20)
7. All variable members store some  Exactly only one data member stores a value
value at any point in the program. at any particular instance in the program.
8. The structure allows initializing  Union allows initializing only one variable
multiple variable members at once. member at once.
9. It is used to store different data type  It is used for storing one at a time from

Page 105

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

values. different data type values.

20. Write about Enumeration (or enum) in C (5m)


Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants,
the names make a program easy to read and maintain.

Declaration: The keyword ‘enum’ is used to declare new enumeration types.

Syntax: enum enum-variable{identifier-1, identifier-2,…, identifier-n};

{By default, the values of the constants are as follows: identifier-1 = 0, identifier-2= 1, identifier-3= 2
and so on.}

Example: enum colors{red, green, blue, yellow, black};

Variables of type enum can also be defined in following ways:


colors c1=blue; output--2
or
enum colors {red = 1, green = 5, blue=0};
or
enum colors{red, green, blue}c1;

// An example program of enum in C


#include<stdio.h>
enum day{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
void main()
{
enum day d1;
clrscr();
d1 = Wed;
printf("%d",d1);
getch();
}

Page 106

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Rules for enum:


1. Two enum names can have same value. For example, in the following C program both ‘green’ and ‘blue’
have same value 2.

#include <stdio.h>
enum colors {red = 1, green = 2, blue = 2};
void main()
{
printf("%d, %d, %d", red,green,blue);
}
2. If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0.

For example, in the following C program, sunday gets value 0, monday gets 1, and so on.

#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
void main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
}
3. We can assign values to some name in any order. All unassigned names get value as value of previous name
plus one.

#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,wednesday, thursday = 10, friday, saturday};
void main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,wednesday, thursday, friday, saturday);
}
4. The value assigned to enum names must be some integeral constant, i.e., the value must be in range from
minimum possible integer value to maximum possible integer value.

5. All enum constants must be unique in their scope. For example, the following program fails in compilation.

enum machine{working, failed};


enum result {failed, passed}; // in machine-enum failed is already assign and so should not here
void main()
{
}
Output:

Page 107

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Compile Error: 'failed' has a previous declaration as 'machine failed'

21. Write about typedef in C (5m).

 typedef is a user-defined data type.

Typedef: The typedef is a keyword used in C programming to provide some meaningful names to the already
existing variable in the C program. It behaves similarly as we define the alias for the commands. (or)

In short, we can say that this keyword is used to redefine the name of an already existing variable.

Syntax: typedef <existing_datatype-name> <alias_name>


In the above syntax, “existing_datatype-name” is the name of an already existing variable while 'alias name' is
another name given to the existing variable.

Example: typedef int my_int;


In the above statements, we have declared the my_int variable of data-type int by using a typedef keyword.

Now, we can create the variables of data-type int by writing the following statement:

Example: my_int a, b;
The typedef is used to give data type a new name.

// C program for typedef


#include <stdio.h>
typedef int my_int; // After this line my_int can be used in place of int
void main()
{
my_int a,b;
clrscr();
a=5;
b = 10;
printf("\n a = %d b = %b ", a,b);
getch();
}
#define: #define in C is a preprocessor directive which is used to #define alias.

// C program for #define


#include <stdio.h>

Page 108

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

#define HYD "Hyderabad" // After this line HYD is replaced by "Hyderabad"


void main()
{
printf("%s ", HYD);
}
Difference between typedef and #define:

1. typedef is limited to giving symbolic names to data-types only, whereas #define can be used to define an
alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc.
2. typedef interpretation is performed by the compiler where #define statements are performed by
preprocessor.
3. #define should not be terminated with a semicolon, but typedef should be terminated with semicolon.
4. #define will just copy-paste the definition values at the point of use, while typedef is the actual definition
of a new type.
5. typedef follows the scope rule which means if a new data-type is defined in a scope (inside a function),
then the new data-type name will only be visible till the scope is there. In case of #define, when
preprocessor encounters #define, it replaces all the occurrences, after that (No scope rule is followed).

Page 109

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

UNIT -V SEM-1

Pointers: Understanding Computer Memory – Introduction to Pointers – declaring Pointer Variables –


Pointer Expressions and Pointer Arithmetic – Null Pointers - Passing Arguments to Functions using
Pointer – Pointer and Arrays – Memory Allocation in C Programs – Memory Usage – Dynamic Memory
Allocation – Drawbacks of Pointers
Files: Introduction to Files – Using Files in C – Reading Data from Files – Writing Data to Files –
Detecting the End-of-file – Error Handling during File Operations – Accepting Command Line
Arguments.

Understanding Computer Memory: Every computer has primary memory. All data and programs need to
place in the primary memory for execution. The primary memory or RAM is a collection of memory locations
and each location has a specific address and each memory location is capable of storing 1 byte of data.

Generally the computer memory has three areas of memory each of which is used for a specific task. These
are

1. Stack: A fixed size of stack is allocated by the system and is filled from the bottom to top one element
at a time. These elements can be removed from the top to bottom by removing one element at a time.
It follows LIFO principle.
2. Heap: It is a contiguous block of memory that is available for use by the program when the need
arises. A fixed size heap is allocated by the system and is used by the system in a random fashion i.e in
heap the addresses of memory locations are not currently allocated to the program.
3. Global memory: The block of code that is the main () program is stored in the global memory. The
memory in the global area is allocated randomly to store the code of different functions in the program
in such a way that one function is not contiguous to another function. All the global variables declared
in the program are stored in the global memory.
4. Other memory layouts: text segment, BSS (block started by symbol), and shared library segment.

Pointers
1. Write about Pointers in C language.
Pointers: The pointer in C language is a variable which stores the address of another variable. Or Pointer is
a variable which contains address of another variable rather than its value.

For example “a” is a variable which is located at address 6245 containing the value 10.

Note: Since the addresses are whole numbers therefore pointers always contain whole numbers.

Declaring Pointer Variables:

Page 110

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Syntax: data-type *pointer-variablename;

Example : int *ptr;


Here data-type can be int, float, char.double,long etc.

int *pint; // pint is a pointer pointing to integer address

char *pchar; // pchar is a pointer pointing to character address

float *pfloat; // pfloat is a pointer pointing to float address

In above statements all these pointers pint, pchar, and pfloat point to different data types but they will occupy
the same amount of space in memory.

#include<stdio.h>
#include<conio.h>
void main()
{
int *pint;
char *pchar;
float *pfloat;
double *pdouble;
clrscr();
printf("\n size of integer pointer = %d",sizeof(pint));
printf("\n size of char pointer = %d",sizeof(pchar));
printf("\n size of float pointer = %d",sizeof(pfloat));
printf("\n size of double pointer = %d",sizeof(pdouble));
getch();
}

NOTE: Pointer variables are not allowed to store memory addresses but they can store addresses of variables
of a given type.

Example:
int *ptr;
int a=10;
*ptr=1000; (Invalid)
*ptr=&x; (Valid)

& and * operators: The ‘&’ operator is known as address operator which gives the address of a variable.

Example: ‘&a’ returns the address of the variable “a”. The ‘*’ operator is called as “value at address
operator”. It returns the value stored at a particular address. This operator also called as “indirection operator”.
It is used as a prefix to pointer variable.

Example:
#include<stdio.h>
void main ()
{
int *ptr, a = 10;
ptr = & a;

Page 111

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

*ptr = 20;
printf(“%d”,*ptr);
}
Output : a= 20

Advantages or Uses of pointers:

1. Pointers used for accessing array elements.

2. Pointers used to return more than one value from functions

3. Pointers used for passing array and strings to functions.

4. Pointers used in creating complex data structures like linked list, trees, graphs etc.

5. Pointers are used in dynamic memory allocation.

6. Pointers are used in passing function to another function.

-----------------------------------------------------------------

2. Write about Pointer Expressions and Pointer Arithmetic (5marks).


Pointer Expressions and Pointer Arithmetic:

Like normal variables pointer variables can also be used in expressions.

Example:

int a =10,b =20,c;

int *ptr1,*ptr2;

ptr1=&a; and ptr2=&b;

c =*ptr1 + *ptr2; c =*ptr1 - *ptr2; c =*ptr1 x *ptr2; c =*ptr1 / *ptr2;


output: c=30 output: c=-10 output: c=200 output: c=0 (integer)
actual value: 0.5

A limited set of arithmetic operations can be performed on pointers. The arithmetic operations use the
following operators

1. incremented ( ++ )
2. decremented ( - -)
3. an integer may be added to a pointer ( + or += )
4. an integer may be subtracted from a pointer ( – or -= )
5. Relational operators can apply on two pointers (>, <…)

Example:

int a =10,b =20,c;

Page 112

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

int *ptr1,*ptr2;

ptr1=&a; and ptr2=&b;

*ptr1++;

*ptr2--;

Pointer arithmetic is meaningless unless performed on an array.

Note: Pointers contain addresses. Adding two addresses makes no sense, because there is no idea what it
would point to. Subtracting two addresses lets you compute the offset between these two addresses.

#include <stdio.h>
#include <conio.h>
void main()
{
int a[3] = {10, 20, 30}; // Declare an array
int i;
int *ptr; // Declare pointer variable
clrscr();
ptr = a; // Assign the address of a[0] to ptr
for ( i = 0; i < 3; i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("Value of ptr = %p\n\n", ptr);
ptr++; // Increment pointer ptr by 1
}
getch();
}

3. Write about null pointers and generic pointers (void pointers) (5marks).
Null Pointers: A null pointer is a special pointer value that is known as not to point any variable. Pointer does
not point to any valid memory address.

To declare null pointer we use the predefined constant NULL.

Syntax: int *ptr = NULL;

Example:
int *ptr;
*ptr=NULL; or *ptr=0;
To pass a null pointer to a function argument when we don’t want to pass any valid memory address.

Generic Pointers (or) void Pointers:

A generic pointer is a pointer that can be used to point to variable of any data type. It is also called as void
pointer. To declare generic or void pointer we use “void” keyword.

Syntax: void *ptr;

int i=9; // integer variable initialization.

Page 113

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

int *p; // integer pointer declaration.


float *fp; // floating pointer declaration.
void *ptr; // generic (void) pointer declaration.
p=fp; // incorrect.
fp=&i; // incorrect
ptr=p; // correct
ptr=fp; // correct

4. Explain about passing arguments to a function using pointers (10m).


Passing Arguments to Functions using Pointer: The calling function sends the addresses (&) of the
variables and the called function must declare those incoming arguments as pointers(*).

Passing arguments to function using pointers must do the following.

 Declare the function parameters as pointers


 Use the dereference pointer in the function body.
 Pass the addresses as the actual argument when the function is called.

Syntax: data-type function_name(data-type *ptr ,…) { }


Example program

#include <stdio.h>
void swap (int *a, int *b) // passing parameters to a function
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d",*a,*b);
}
void main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d",a,b);
swap(&a,&b); // passing actual arguments with variable address
printf("After swapping values in main a = %d, b = %d",a,b);
}

Passing Array to Function using pointer: An array can be passed to a function using pointer. When we pass
the name of array to a function, the address of the 0th element of the array is copied to the pointer variable in
the function.

Syntax:
function-name(data-type a[]);
function-name(data-type *a);
function-name(data-type a[], int n);

Page 114

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

function-name(data-type *a,int n);


where ‘n’ is the size of array.

To access all the elements of the array we using the expression

*(array_name + index) Example: *(a+i) or *(i+a)

Example:
void display(int a[])
{
for(i=0;i<5;i++)
printf(“%d”, *(a+i))
}
void main()
{
int a[5]={1,2,3,4,5};
display(a);
}

5. Explain about Pointers and Arrays (or) Explain about Pointers to


arrays?
Pointer and Arrays: The concept of array is very much bounded to one of pointer concept. An array
occupies consecutive memory locations.

Example: int a[] = {10,20,30,40,50};

The array name itself indicates the pointer to first element of that array. It is known as the base address
(1000). In other words, base address is the address of the first element in the array or the address of a [0].

Pointer and 1D Array: The first element of 1D-array can be expressed as (a+0), second array element as
(a+1) and so on the ith element is expressed as (a+i)

To obtain the contents we use *(a+0),*(a+1) .................. *(a+i)

Declaration: a[i], i[a], *(a + i), *(i + a) gives the same value.

Example:
#include<stdio.h>
#include<conio.h>

Page 115

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

void display(int a[])


{
int i;
for(i=0;i<5;i++)
printf("\n %d",*(a+i)); (or) printf("\n %d",*(i+a));
}
void main()
{
int a[]={10,20,30,40,50};
clrscr();
display(a);
getch();
}
Output

Pointer and 2D Arrays: A two-dimensional array is a collection of one dimensional array so we define two
dimensional arrays as pointer to group of contiguous one dimensional array.

Example: int a[2][2]={{1,2},{3,4}};

to access individual elements of the array “a[ ][ ]” or a[i][j]; or *(*(a+i)+j)) or *(a[i]+j);

Declaration: datatype (*pointer-variable)[column-size];

Example: int (*ptr)[2];

Here a is a pointer to array of 4 elements and 2 columns.

In two dimensional array,

a+0 (or) a pointer to first row


a+1 pointer to second row
*(a+0) pointer to first element of 0th row
*(a+i) pointer to first element of ith row
*(a+i)+j pointer to jth element of ith row
*(*(a+i)+j) gives the contents of jth element of ith row

Page 116

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2]={{1,2},{3,4}};
int i,j;
clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%4d",*(*(a+i)+j));
printf("\n");
}
getch();
}
Output

Pointer and 3D-Arrays: Pointers are used to access 3d-arrays using below declaration:

Int *(*(*(a+i)+j)+k);

Example for Pointers to 3D-arrays:

int a[2][2][2] ={1,2,3,4,5,6,7,8};

int *ptr[2][2]; //initialization 3D

a[i][j][k]= *(*(*(a+i)+j)+k); // accessing individual element.

------------------------------------------------

6. Write about array of pointers in c.


Array of pointers: “Array of pointers” is an array of the pointer variables. It is also known as pointer arrays.

An array of pointers is an array that consists of variables of pointer type, which means that the variable is a
pointer addressing to some other element. Suppose we create an array of pointer holding 3 integer pointers;
then its declaration would look like:

Syntax: data type *pointer-array-name[size];


Example: int *ptr[3]; // array of 3 integer pointer.

In the above declaration, we declare an array of pointer named as ptr, and it allocates 3 integer pointers in
memory.

Page 117

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

// C program for array of pointers.

#include <stdio.h>
#include<conio.h>

void main()
{
int a[] = { 10, 20, 30 }; // creating an array
int i, *ptr[3]; // we can make an integer pointer array to storing the address of array elements
for (i = 0; i < 3; i++)
{
ptr[i] = &a[i]; // assigning the address of integer.
}
for (i = 0; i < 3; i++) // printing values using pointer
{
printf("Value of a[%d] = %d\n", i, *ptr[i]);
}
}

7. Write the differences between arrays name and pointers.


Arrays pointers
1. Array is a group of consecutive memory 1. Pointer is a variable that contains address
locations that stores homogenous type of of another variable
data
2. Once array is declared its base address is 2. Pointer variables can refer any address in
fixed and its value cannot change. an array.
3. Array can’t be assigned to another array 3. Pointers can be assigned to another pointer
Example: if a, b are arrays a =b produces Example: ptr1=ptr2
error
4. Array name gives the address of array 4. Pointer name doesn’t specify any address
5. sizeof operator with array gives the size of 5. sizeof operator with pointer returns the
array number of bytes used for pointer variable
i.e.
6. 2 bytes always.

Page 118

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

8. Write about pointer to strings.


Pointers and Strings: In c language strings are treated as array of characters that are terminated with null
character ‘\0’.

In C, Example:
char str[10]="sri";
str[0] = ‘ s ‘;
str[1] = ‘ r ‘;
str[2] = ‘ i ‘;
str[3] = ‘ \0‘;
therefore it is written as char s[10]={'s','r','i','\0'};
C language provides 2 alternate ways of declaring and initializing a string.

1. char str[10] = {‘s’,’r’,’i’,’\0’};

2. char str[10] = “sri”;

When the double quotes are used, null character (‘\0’) is automatically appended at the end of the string.

Declaration:
char str[] = “narayana”;
char *ptr;
ptr = str;
// c program for pointers to strings.
#include <stdio.h>
#include<conio.h>
void main()
{
char s[] = "parvin";
char *ptr;
clrscr();
ptr=s;
while(*ptr!='\0')
{
printf("%c",*ptr);
ptr++;
}
getch();
}

9. Write about Pointer to Functions


Function pointers: Function pointers must be initialized prior to use. We have to declare pointers to that
function then the pointer can be assigned the address of the correct function by using its name. It is optional to
use address (&) operator in the front of the function name.

Declaration: Return-type (*function-name)(parameter_list);

Initialization: Function-pointer=& function-Name;

Page 119

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Example-1: Void display(int x);

Void (*fp)(int);

fp=display; or fp=&display;

Example-2: int (*fptr)(int a, int b);

When we declare a pointer to function, it can be called using two forms

(*functionpointer)(argumentlist) (or) functionpointer(argumentlist)

Example: (*fptr)(1,2) (or) fptr(1,2)

#include<stdio.h>
#include<conio.h>
void display(int x);
void (*fp)(int);
void main()
{
clrscr();
fp=display;
(*fp)(10);
fp(20);
getch();
}
void display(int n)
{
printf("\n using pointers display n = %d",n);
}
Advantages:

1. It is used to pass function as argument to another function


2. It is used to memory resident programs
3. It is used in writing programs to remove virus

Passing function pointer as an argument to a function:

A Function pointer can be passed as the calling argument to a function.


Example:
void read (int x);
void (*fp)(int);
void sum(int a, int *fp); // function-pointer as argument in the function.
----------------------------------------

10. Write about pointer to pointers.


Pointers to Pointers: A pointer to a pointer is a form of multiple indirections, or a chain of pointers.
Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to the location that contains the actual value as shown
below.

Page 120

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk(*) in front of its name. For example, the following declaration declares a pointer to a pointer of type
int
int **pptr;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the
asterisk(*) operator be applied twice, as is shown below in the

Example

#include <stdio.h>
void main ()
{
int a;
int *p;
int **pptr;
a = 100;
p = &a; // take the address of variable a.
pptr = &p; // take the address of p using address of operator &
printf("\nValue of a = %d", a );
printf("\nValue available at *ptr = %d", *ptr );
printf("\nValue available at **pptr = %d", **pptr);
}

11. Write about Memory Allocation in C.


C Supports three kinds of memory allocation through the variables. They are

1. Static Memory Allocation

2. Automatic Memory Allocation

3. Dynamic Memory Allocation

1. Static Memory Allocation: In Static Allocation, the memory is allocated during compile-time and
cannot be changed during execution of the program. When we declared static or global variables static
memory allocation is done.
2. Automatic Memory Allocation: when we declare variables inside a function memory is allocated
from heap at compile-time. Such allocation is known as Automatic Allocation
3. Dynamic Memory Allocation: Allocation of memory to variables at run-time is known as dynamic
memory allocation. C provides four functions to allocate memory at runtime. They are

Page 121

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

1. malloc( ): It Allocates memory dynamically and returns a pointer to memory. Mostly it allocates memory to
the structures.

Syntax: pointer-variable=(data-type*)malloc(datatype-size);

Example: ptr =(int*)malloc(sizeof(int));

2. calloc ( ): Allocates array of memory and initializes them to zero. It returns pointer to memory. Mostly it
allocates memory to the arrays.

Syntax: pointer-variable =(data-type*)calloc(sizeofarray, sizeofelement);

Example: p=(int *) calloc(5,sizeof(int));

3. realloc( ): It changes(increases or decreases) the size of allocated memory

Syntax: ptr=realloc(ptr,newsize);

Example: p=realloc(p,3*sizeof(int));

4. free( ): It is used to free the memory space allocated by malloc( ),calloc( ) or realloc( )

Syntax: free(pointer-variable);

Example: free(ptr);

12. Write about Dynamic Memory Allocation Functions in C (or) write the
differences between malloc() and calloc().
Dynamic Memory Allocation: Allocation of memory to variables at run-time is known as dynamic memory
allocation. C provides four functions to allocate memory at runtime. They are

 malloc()
 calloc()
 realloc()
 free()

1. malloc(): It Allocates memory dynamically and returns a pointer to memory. Mostly it allocates memory to
the structures.

Syntax: pointer-variable=(data-type*)malloc(datatype-size);

Example: ptr =(int*)malloc(sizeof(int));

Features of malloc():
1. malloc() function contains only one parameter.(bytesize)
2. The method “malloc” is used to assign a block of memory when it is requested.
3. It doesn’t clear the memory.
4. It only initializes the allocated memory when explicitly requested.
5. It allocates memory of a specific ‘size’.
6. This size is passed as parameter to it.
7. This size is allocated from a heap and it performs its job quickly.

Page 122

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Example:void *malloc(size_t size);

#include <stdio.h>
#include <stdlib.h>
int main ()
{
char *str;
str = (char *) malloc(15); /* Initial memory allocation */
strcpy(str, "spaces");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
}

2.calloc ( ): Allocates array of memory and initializes them to zero. It returns pointer to memory. Mostly it
allocates memory to the arrays.

Syntax: pointer-variable =(data-type*)calloc(sizeofarray, sizeofelement);

Example: p=(int *) calloc(5,sizeof(int));

Features of Calloc():
1. calloc() function contains two parameters.(no.of elements,bytesize)
2. It assigns the requested memory to multiple blocks.
3. This memory allocated is initiated to zero.
4. This initialization to 0 is done by “calloc” method.
5. It allocates memory to the required operation of a specific ‘size’, i.e num * size.
6. The ‘num’ refers to number of blocks of memory.
7. It is slow in comparison to ‘malloc’ method.

Program for calloc()


#include <stdio.h>
#include <stdlib.h>
void main()
{
int* ptr; // This pointer will hold the base address of the block created
int n,i;
clrscr();
printf("Enter number of elements: ");
scanf("%d",&n);
ptr = (int*)calloc(n, sizeof(int)); // Dynamically allocate memory using calloc()
for (i = 0; i < n; ++i)
ptr[i] =5*(i + 1);
printf("The elements of the array are: "); // Print the elements of the array
for (i = 0; i < n; ++i)
printf("%d, ", ptr[i]);
getch();
}

3.realloc( ): It changes(increases or decreases) the size of allocated memory

Syntax: ptr=realloc(ptr,newsize);

Example: p=realloc(p,3*sizeof(int));

Page 123

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

4. free( ): It is used to free the memory space allocated by malloc( ),calloc( ) or realloc( )

Syntax: free(pointer-variable);

Example: free(ptr);

Program for realloc() and free()


#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include<string.h>
void main ()
{
char *str;
clrscr();
str = (char *) malloc(15); /* Initial memory allocation */
strcpy(str, "arvlnarayana");
printf("\n String = %s, Address = %u\n", str, str);
str = (char *) realloc(str, 25); /* Reallocating memory */
strcat(str, "[email protected]");
printf("\n String = %s, Address = %u", str, str);
free(str);
getch();
}

13. Write the disadvantages of using pointers


1. Pointers are slower than normal variables.
2. If pointers are updated with incorrect values, it might lead to memory corruption.
3. Uninitialized pointers might cause segmentation fault.
4. Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.
5. Dangling pointers arise when an object is deleted or de-allocated without modifying the value of the
pointer

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

FILES
14. Write about files in C or write about streams in C
Definition: A file is a container in computer storage devices used for storing data. (or) File is a collection of
stream of information stored on the memory disk.

When we read data from file, the computer reads the data from disk into memory and when we write data into
file, the computer transfers the data from memory into file.

Types of Files

When dealing with files, there are two types of files:

 Text files
 Binary files

Page 124

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

1. Text files: Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.

 Text files are files that contains a stream of characters


 In text files each line is ended by a newline character (\n) and each file is ended by a special character
called EOF (End-Of-File).The Value of EOF is -1
 When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.
 They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.

2. Binary files: Binary files are mostly the .bin files in your computer.

 A binary files store the data in the form of 1’s and 0’s. It takes less space when compared to text files
 Example: the data “4567”
 Text files take 4 bytes where as binary files takes 2 bytes
 In Binary files also the file is ended by a special character called EOF (End-Of-File)
 The Value of EOF is -1
 Instead of storing data in plain text, they store it in the binary form (0's and 1's).
 They can hold a higher amount of data, are not readable easily, and provides better security than text
files.

Streams: Streams in C are logical interface to the devices and are also referred as a buffer that holds data
temporarily. Streams are used when you read/write data into or from files.

Basically there are 3 types of standard streams in C. They are

 STDIN: is an Input stream by which program receives data


 STDOUT: is an output stream by which program writes the output data
 STDERR: It is an output stream which reports error messages to program

Streams or buffers associated with files: The stream or buffer act as interface between the program and disk.
When we write the data into the file the data stored in buffer is transferred into file. Similarly, when we read
the data from file the data in buffer is transferred to a program

Advantages of files:

 When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if
the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
 However, if you have a file containing all the data, you can easily access the contents of the file using
a few commands in C.
 You can easily move your data from one computer to another without any changes.

15. Write about Basic File Operations in C (OR) Explain about file
handling functions in C (***vvimp****)
The Basic file operations in c are

1. Opening a file or creating a file

Page 125

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

2. Reading data from file


3. Writing data into file
4. Closing a file

The following functions are used to perform file operations.

fopen(): this function opens a file for reading or writing the data

Syntax:
FILE *fp;
Fp= fopen(“filename”, mode)
 “Filename” is the name of the file.
 Mode specifies the type of operation performed on a file
File opening modes in C:

File opening modes for text files:

1. r  (r-read)Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a
cursor-pointer which points to the first character in it. If the file cannot be opened fopen( ) returns
(error)NULL.
2. w  (w-write)Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a
new file is created. Returns (error)NULL, if unable to open file.
3. a  (a-append)Searches file. If the file is opened successfully fopen( ) loads it into memory and sets
up a cursor-pointer that points to the last character in it. If the file doesn’t exist, a new file is created.
Returns (error)NULL, if unable to open file.
4. r+  open for reading and writing, start at beginning
5. w+open for reading and writing (overwrite file)
6. a+open for reading and writing (append if file exists)

File opening modes for binary files:

7. rb- open a binary file for reading


8. wb - open a binary file for writing (overwrite file)
9. ab - open a binary file for appending
10. rb+  open a binary file for reading and writing, start at beginning
11. wb+  open a binary file for reading and writing (overwrite file)
12. ab+ open a binary file for appending in read/write mode

Example for fopen() with modes:


FILE * fp;
fp=fopen(“deepthi.txt”, “w”) -- file opens with write mode
fp=fopen(“parvin.txt”, “r”) -- file opens with read mode

Reading data from files: To read the data from files, the files must be opened in read mode. Data from files is
read by using the following functions

1. fscanf():The fscanf() function is used to read set of characters from file. It reads a word from the file and
returns EOF at the end of file.

Syntax: int fscanf(FILE *stream, const char *format [, argument, ...])

Page 126

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Example: fscanf(fp, “%d”,&number);


2. fgets():this function reads a line of characters from file. It gets string from a stream.

Syntax: char* fgets(char *s, int n, FILE *stream)


Example: fgets(str,20,fp)

3. fgetc(): It is used to read a character from the file stream.

Syntax: int fgetc(FILE * Stream);


Example: fgetc(fp);
4. fread(): It is used to read data from the file stream.

Syntax: fread( ptr, int size, int n, FILE *fp );


Example: fread(str,1,10,fp);
Program-1

#include <stdio.h>
#include <stdlib.h>
void main()
{
int st[20];
FILE *fptr;//step-1
if ((fptr = fopen("Example1.txt","r")) == NULL)//step-2
{
printf("Error! opening file");
exit(1);
}
fscanf(fptr,"%s",st); //step-3 access data from file to program
printf("Value of string = %s",st);//step-4 access data from program to output screen
fclose(fptr); //step-5
getch();
}
Writing data from files:

To write the data from files, the files must be opened in write or append mode.Data into files can be written
by using the following functions

1. fprintf():It is used to write formatted data into the file stream.

Syntax: int fprintf(FILE * Stream, const char * format,. .... );


Example: fprintf (fp, “%d ”,number);
2. fputs(): It is used to write a line or string into the file stream.

Syntax: int fputs(char * str, FILE * Stream);


Example: fputs(str,fp);
3. fputc(): It is used to write a character into the file stream.

Syntax: int fputc(int c, FILE * Stream);


Example: fputc(ch,fp);
4. fwrite(): It is used to write data into the file stream.

Syntax: fwrite( ptr, int size, int n, FILE *fp );

Page 127

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

Example: fwrite(str,1,10,fp);
Program-2

//program for writing data onto a file


#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
void main()
{
char st[20];
FILE *fptr; //step-1
fptr = fopen("Example1.txt","w");//step-2
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter name: ");// step-3 data access from keyboard to program
scanf("%s",st);
fprintf(fptr,"%s",st); //step-4 data access from program to file
fclose(fptr); //step-5
getch();
}
Closing files:

fclose(): It is used to close the files opened by fopen()

Syntax: int fclose(FILE *fp)


Example:
FILE * fp;
fp=fopen(“sample.txt”, “w”);
fclose(fp);

fcloseall():It is used to close all the files opened.

Syntax: int fcloseall(void)


Example:
FILE * fp1,*fp2;
fp1=fopen(“deepthi.txt”, “w”);
fp2=fopen(“arvl.txt”,”r”);
fcloseall();

Detecting the End of file: The End-of-File is detected by using symbolic constant EOF, Whose value is -1
and other by using feof() function

feof(): It checks whether end of file is reached or not. If end of file is reached it returns 1(true) and if end of
file is not reached it returns 0(false)

Syntax: int feof(FILE * fp)


Example: feof(fp);

Page 128

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

16. Write about Error Handling During File Operations. (5m)(******)


Errors may occur while reading data from a file or writing data into a file. The errors may occur when

1. We try to read a file beyond EOF


2. We try reading a file that doesn’t exist
3. Specified file is not opened
4. Writing to a file that is opened in read mode

To handle errors in C, We have the following functions

1. ferror(): It is used to check for errors in the stream. It returns 0 if no errors occur and returns non zero if
errors occur

Syntax: int ferror(FILE * Stream);


Example:
if (ferror(fP))
{

printf(“error occurs”);
}

2. clearerr(): It clears the end of file and errors from the stream.

Syntax: void clearerr(FILE * Stream);


Example:
if (ferror(fp))
{
clearerr(fp);
break;
}

3. perror(): It stands for print error and is used to print error messages to stderr.

Syntax: void perror(char *msg);


Example:
if (ferror(fp))
{
perror(“OOPS:”);
break;
}
*******PROGRAM FOR COPYING ONE FILE ANOTHER FILE********

Page 129

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

printf("Enter the filename to open for reading \n");


scanf("%s", filename);
fptr1 = fopen(filename, "r"); // Open one file for reading
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
fptr2 = fopen(filename, "w");// Open another file for writing
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
c = fgetc(fptr1); // Read contents from file
while (c != EOF) // char c is detecting EOF
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
getch();
}

Output

17. Write about Command Line Arguments in C.(******vvimp*******)


Command line arguments are arguments passed from command line to main() during program execution.
These arguments are supplied at the time of invoking the program.

The main ( ) function can take arguments as:

void main(int argc, char *argv[])


{
....
}

 The first argument argc is known as 'argument counter'. It represents the number of arguments
passed from the command line.

Page 130

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

 The second argument argv is known as 'argument vector'. It is an array of char data-type pointers that
points to the command line arguments.
 The first element args[0] in array is the name of the file into which command line arguments are
passed. Size of this array will be equal to the value of argc.

Steps to execute Command Line Arguments program in C:


Step-1: write a program, save and execute
Save file Example: filename.c (i.e. zc.c)
Step-2: In c-editor file-menuos-shell ()
Step-3: at command line type c:\tc\bin\>filename arg-1 arg-2 ….,
Example : c:\tc\bin\>zc arvlnarayana spaces degree college

program

#include <stdio.h>
void main(int argc, char *argv[] )
{
int i;
printf("arguments = %d\n", argc);
for(i=0;i<argc;i++)
printf("argument[%d] is: %s\n",i,argv[i]);
}

Output: The command lines are executed from command line as follows
Arguments:3
Argument[0] is:welcome
Argument[1] is:to
Argument[2] is:Aditya

18. Write about Functions for selecting records randomly.


The functions that can access the records randomly in file are

1. fseek(): It is used to set the file position pointer in the specified file

syntax: int fseek(FILE * stream, long offset,int origin);

 offset specifies the no of bytes to move forward or backward origin should be one of the following

a) SEEK_SET: to perform read/write from beginning of file. It’s value is 0

b) SEEK_CUR: to perform read/write from the current position. It’s value is 1

Page 131

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI

c) SEEK_END: to perfom read/write from the end of file. It’s value is 2

Example: fseek(fp,1,SEEK_CUR)

2. ftell():It is used to know the current position of the file pointer.

Syntax: long ftell(FILE * stream)

Example: ftell(fp)

3. rewind(): It is used to move the file pointer to the beginning of file

Syntax : void rewind(FILE * fp);

Example:rewind(fp);

4. fgetpos(): It determines the current position of the stream

Syntax : int fgetpos(FILE *fp,fpos_t pos);

Example: fgetpos(fp,&pos);

5. fsetpos(): It sets the position of the stream to a new position

Syntax: int fsetpos(FILE * fp,const pos);

Example: fsetpos(fp,90);

OTHER FUNCTIONS

6. remove(): It is used to erase or delete a file

Syntax: remove(“filename”);

Example: remove(“abc.txt”);

7. renaming a file: File can be renamed by using rename()

Syntax: int rename(const char * oldfilename,const char * newfilename)

Example: rename(“abc.txt”, “xyz.txt”);

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

Page 132

DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech

You might also like