C Complete Notes
C Complete Notes
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. 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.
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.
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
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
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
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).
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
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 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
Disadvantages:
These are assembled manually.
Production of computers difficult and expensive.
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
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
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
Page 11
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
6 Connector Labels
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
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.
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
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
Page 19
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
----------------------------------------------------------------------
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.
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.
5. Sub program section (User defined Function): The functions written by user are called user
defined functions and are defined before or after main ().
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.
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”);
4. Compile & Run the program. In c-editor COMPILE: Alt + f 9 and RUN: ctrl + f 9
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
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)
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
Page 23
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
1. It must begin with an alphabet. (example : sum,avg,abc123 ---- valid 123abc--- invalid)
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:
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 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.
The scientific notation is used to express numbers that are either very small or very large.
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.
Page 25
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
Numeric Variables: These variables are used to either integer or floating point values
Character Variables: character can be an Alphabet, Digit or special Symbol
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;
Page 26
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
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.
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.
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
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
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
=============================================
They are
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.
(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
5. Increment and decrement operators: The increment and decrement operators are used to
increment or decrement the contents of a variable. In C language,
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.
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.
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.
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.
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.
Scanf(): scanf() stands for scan formatting data and is used to read formatted data from the keyboard
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.
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
Operator precedence: determines which operator is performed first in an expression with more than one operator with different
precedence.
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
++ — 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
Page 34
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
12 || Logical OR left-to-right
= 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
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.
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
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
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.
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
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:
Syntax: Example:
Page 39
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
}
Statement-x;
Flow chart:
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.
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.
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.
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.
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
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
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
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.
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 .
Page 46
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
Advantages of an Array in C:
Page 48
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
************************************
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.
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
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.
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] );
#include<stdio.h>
#include<conio.h> Output
void main()
Page 50
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
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.
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:
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
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
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
****************************
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
Example: int a [2][3][4]; The below 3-D array contains 2 X 3 X 4 =24 elements
#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.
Page 55
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
getch();
}
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).
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:
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.
#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;
}
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
}
Time complexity of Selection sort:
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
#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:
*******************************programs on 2D arrays*********************************
Page 59
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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]);
}
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.
String: String is a group of characters which ends with a null character “\0”
String variable:
Char variable:
Char ch[] = “A”;
Char ch = ‘A’;
Page 62
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
Initialization of strings: Giving values to string at the time of its declaration is known as initialization
of string.
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
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.
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.
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 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)
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.
Page 66
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
******************************************
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(‘?’)
******************************
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.
Page 67
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
#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
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.
Advantages:
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.
Syntax Example
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.
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.
Eg: swap(a,b)
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
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.
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
Page 72
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
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:
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.
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
}
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.
#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.
#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
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.
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.
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
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
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”
#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”.
#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.
Page 82
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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
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
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
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>
Page 87
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
Like variables of other data types, we can also pass an array to a function as 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: 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]);
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: 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: 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
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
}
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];
************************************************
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.
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…).
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
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;
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.
Page 95
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
b1.bno;
b1.bname;
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
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. }
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.
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
----------------------------------------------------------------------------------------------
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.
Page 98
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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
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.
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…).
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;
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;
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;
Step-4: accessing union members in the union variable: we can access union members by using “dot”
operator.
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.
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);
}
}
Example program
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();
}
Page 105
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
{By default, the values of the constants are as follows: identifier-1 = 0, identifier-2= 1, identifier-3= 2
and so on.}
Page 106
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
#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.
Page 107
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
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.
Page 108
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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
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.
Page 110
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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
4. Pointers used in creating complex data structures like linked list, trees, graphs etc.
-----------------------------------------------------------------
Example:
int *ptr1,*ptr2;
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:
Page 112
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
int *ptr1,*ptr2;
*ptr1++;
*ptr2--;
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.
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.
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.
Page 113
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
#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
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);
}
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)
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
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.
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);
------------------------------------------------
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:
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
#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]);
}
}
Page 118
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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.
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();
}
Page 119
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
Void (*fp)(int);
fp=display; or fp=&display;
#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:
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);
}
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);
2. calloc ( ): Allocates array of memory and initializes them to zero. It returns pointer to memory. Mostly it
allocates memory to the arrays.
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);
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
#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.
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.
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);
************************************
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
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.
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.
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
Page 125
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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:
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)
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.
Page 126
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
#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
Page 127
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
Example: fwrite(str,1,10,fp);
Program-2
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)
Page 128
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
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
printf(“error occurs”);
}
2. clearerr(): It clears the end of file and errors from the stream.
3. perror(): It stands for print error and is used to print error messages to stderr.
Page 129
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
Output
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.
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
1. fseek(): It is used to set the file position pointer in the specified file
offset specifies the no of bytes to move forward or backward origin should be one of the following
Page 131
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech
ADITYA DEGREE COLLEGE, TUNI
Example: fseek(fp,1,SEEK_CUR)
Example: ftell(fp)
Example:rewind(fp);
Example: fgetpos(fp,&pos);
Example: fsetpos(fp,90);
OTHER FUNCTIONS
Syntax: remove(“filename”);
Example: remove(“abc.txt”);
************************************************
Page 132
DADIDFDDFDFD FDFD
M.N.V.G.A.DEEPTHI, M.Tech