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

??C Programming (PPS)

The document provides an introduction to computer programming and data structures. It discusses that computer technology plays an increasing role in today's information revolution. It states that a sound knowledge of how computers process data has become indispensable for employment in any field. It then discusses that computer programming involves writing, testing, and maintaining programs for computers to perform functions. The book aims to teach students to master programming skills in C language and use data structures and algorithms effectively. It also provides an overview of the course contents which cover topics like C programming language, data structures, arrays, pointers, structures, file input/output, searching and sorting algorithms.

Uploaded by

siddivinaymamidi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

??C Programming (PPS)

The document provides an introduction to computer programming and data structures. It discusses that computer technology plays an increasing role in today's information revolution. It states that a sound knowledge of how computers process data has become indispensable for employment in any field. It then discusses that computer programming involves writing, testing, and maintaining programs for computers to perform functions. The book aims to teach students to master programming skills in C language and use data structures and algorithms effectively. It also provides an overview of the course contents which cover topics like C programming language, data structures, arrays, pointers, structures, file input/output, searching and sorting algorithms.

Uploaded by

siddivinaymamidi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 320

C PROGRAMMING & DATA STRUCTURES

COURSE - MATERIAL

INTRODUCTION
Computer technology plays an increasing role in the information revolution. Today, the application
of computers is all pervasive in everybody‟s life. A sound knowledge of how computers process data
and information has, therefore, become indispensable for anyone who seeks employment not only in
the area of IT but also in any other field.

COMPUTER PROGRAMMING
Computer Programming is dedicated to writing, testing and maintaining programs that computers
follow to perform their functions. To create programs that control the behaviour of a machine, we
need programming languages. This book enables students to master the necessary skills for computer
programming with C language shows them how to use these skills wisely with data structures and
algorithms.

C PROGRAMMING LANGUAGE
C is a general-purpose structured programming language that is powerful, efficient and compact. C
combines the features of high-level language with the elements of the assembler and is thus close to
both man and machine. The growth of C during the last few years has been phenomenal. It has
emerged as the language of choice for most applications due to speed, portability and compactness of
code. It has now been implemented on virtually every sort of computer , from micro to mainframe.

DATA STRUCTURES
Data Structures are prevalent in almost every program, since they provide specialized formats of
storing and organizing data in a computer

HOW IS THE BOOK ORGANIZED


The book covers the basic anatomy of a computer system,input devices, processor,output devices and
memory management and also discusses algorithms and flowcharts in Unit-I. Unit II introduces
programming in C language, which talks about the basic structure of C programs and their execution,
how to declare constants,variables and data types,details the input and output operations, built-in
operators and how to build expressions using them and also covers decision making and looping
structures. Unit-III provide detailed exposition of functions and arrays. Pointers,perhaps the most
difficult part of C, and also the basic concepts of strings are covered in Unit-IV in a user-friendly
manner. Unit-V covers the concepts of structures and unions. Management of files is dealt in Unit-
VI. Unit-VII covers sorting and searching techniques. Unit-VIII deals with datastructures, dynamic
memory allocation and lined lists.

1
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
SYLLABUS

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD


I Year B.Tech. L T/P/D C
3 -/-/- 6

COMPUTER PROGRAMMING AND DATA STRUCTURES

UNIT - I
Introduction to Computers – Computer Systems, Computing Environments, Computer
Languages, Creating and running programmes, Software Development Method,
Algorithms, Pseudo code, flow charts, applying the software development method.

UNIT - II
Introduction to C Language – Background, Simple C Programme, Identifiers, Basic data
types, Variables, Constants, Input / Output, Operators. Expressions, Precedence and
Associativity, Expression Evaluation, Type conversions, Bit wise operators, Statements,
Simple C Programming examples.
Selection Statements – if and switch statements, Repetition statements – while, for, do-
while statements, Loop examples, other statements related to looping – break,
continue, goto, Simple C Programming examples.

UNIT - III
Designing Structured Programmes, Functions, basics, user defined functions, inter
function communication, Standard functions, Scope, Storage classes-auto, register,
static, extern, scope rules, type qualifiers, recursion- recursive functions, Preprocessor
commands, example C programmes
Arrays – Concepts, using arrays in C, inter function communication, array applications,
two – dimensional arrays, multidimensional arrays, C programme examples.

UNIT - IV
Pointers – Introduction (Basic Concepts), Pointers for inter function communication,
pointers to pointers, compatibility, memory allocation functions, array of pointers,
programming applications, pointers to void, pointers to functions, command –line
arguments.
Strings – Concepts, C Strings, String Input / Output functions, arrays of strings,
string manipulation functions, string / data conversion, C programme examples.

UNIT - V
Derived types – Structures – Declaration, definition and initialization of structures,
accessing structures, nested structures, arrays of structures, structures and functions,
pointers to structures, self referential structures, unions, typedef, bit fields, enumerated
types, C programming examples.

UNIT - VI
Input and Output – Concept of a file, streams, standard input / output functions,
formatted input / output functions, text files and binary files, file input / output
operations, file status functions (error handling), C programme examples.

2
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
SYLLABUS

UNIT – VII
Searching and Sorting – Sorting- selection sort, bubble sort, insertion sort, quick
sort, merge sort, Searching-linear and binary search methods.

UNIT - VIII
Data Structures – Introduction to Data Structures, abstract data types, Linear list
– singly linked list implementation, insertion, deletion and searching operations on
linear list, Stacks-Operations, array and linked representations of stacks, stack
application-infix to postfix conversion, postfix expression evaluation, recursion
implementation, Queues-operations, array and linked representations.

TEXT BOOKS :
1. C Programming & Data Structures, B.A.Forouzan and R.F. Gilberg, Third Edition,
Cengage Learning.
2. Problem Solving and Program Design in C, J.R. Hanly and E.B. Koffman, Fifth Edition,
Pearson education.

REFERENCES:
1. C& Data structures – P. Padmanabham, Third Edition, B.S. Publications.
2. The C Programming Language, B.W. Kernighan and Dennis M.Ritchie, PHI/Pearson
Education
3. C Programming with problem solving, J.A. Jones & K. Harrow, dreamtech Press
4. Programming in C – Stephen G. Kochan, III Edition, Pearson Eductaion.
5. C for Engineers and Scientists, H.Cheng, Mc.Graw-Hill International Edition
6. Data Structures using C – A.M.Tanenbaum, Y.Langsam, and M.J. Augenstein, Pearson
Education / PHI
7. C Programming & Data Structures, E. Balagurusamy, TMH.
8. C Programming & Data Structures, P. Dey, M Ghosh R Thereja, Oxford University Press
9. C& Data structures – E V Prasad and N B Venkateswarlu, S. Chand&Co.

3
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

COURSE CONTENTS
Page No.s
UNIT-I
Introduction to Computers - 5-24

UNIT – II
Introduction to C Language - 25-58

UNIT – III
Designing Structured Programmes - 59-78

Arrays - 79-86

UNIT – IV
Pointers - 87-103
Strings - 104-116

UNIT - V
Derived types – Structures &Unions - 117-134

UNIT – VI
Input and Output -- Files - 135-155

UNIT – VII
Searching and Sorting - 156-174

UNIT – VIII
Data Structures - 175-214

Objective type questions - 215-267

Questions with answers - 268-272

Viva Questions - 273-276

JNTU Objective/Bit Papers - 277-296

JNTU External Question Paper - 297-320

4
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

5
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
COMPUTER :

It is a high speed electronic device that accepts and stores input data and instructions, processes the
data and produces the desired output.

Input Output
(raw data / Instructions) (Information i.e. processed data)

COMPUTER SYSTEMS
* It is made up of 2 major components
COMPUTER
* They are : 1) Hardware SYSTEM
2) Software

HARDWARE SOFTWARE

Computer Hardware :
 These are the physical components of a computer
 It consists of 5 Parts

1) Input Devices 4) Primary Storage


2) Output Devices 5) Secondary Storage
3) CPU
Block diagram of a Computer

ALU CU

Input Output
Devices Devices
Primary Memory

Secondary Memory

6
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Input Devices
 These are used to enter data and programs into the computer
 These are for man to machine communication
 egs: Keyboard, mouse, scanner, touch screen, audio input.

Output Devices
 These are used to get the desired output from the computer
 These are for machine to man communication
 egs: Printer, Monitor, Speakers
 If the output is shown on monitor then it is called “Soft copy”
 If the output is printed on a paper using printer then it is called “hard copy”
CPU (Central Processing Unit)
 It is responsible for processing the instructions
 It consists of 3 parts
1) ALU – Arithmetic & Logic Unit
2) CU- Control Unit
3) Memory
 ALU performs arithmetic operations like addition,subtraction,multiplication,division and
logical operations like comparisons among data
 CU is responsible for movement of data inside the system
 Memory is used for storage of data and programs. It is divided into 2 parts.
1) Primary Memory/ Main Memory
2) Secondary Memory/ Auxilary Memory
1) Primary Memory
 It is also called main memory
 Data is stored temporarily i.e. data gets erased when computer is turned off
 Eg: RAM
2) Secondary Memory
 It is also called as auxilary memory
 Data is stored permanently so that user can reuse the data even after power loss.
 Eg: Hard disk, CD, DVD, Floppy etc.
COMPUTER SOFTWARE
 The software is used to make the hardware of the computer to function
 Software is collection of programs (or) instructions

7
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 Computer software is divided into 2 categories
1) System Software
2) Application Software

Hard
ware

1. System Software
 They constitute set of programs that manage the hardware resources of a computer
 It is divided into 3 classes

System
Software

Operating System System


System Support Development

Operating System
 It acts as an interface between the user and the hardware
 It makes the system to operate in an efficient manner
 Egs: MS DOS, Windows, UNIX, LINUX, etc.
System Support
 They provide some utilities and other operating services
 eg: Sort utilities, disk formatting utilities, Security monitors

8
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
System Development
 It includes
a) Language translators – Used for converting programs into machine language
b) Debuggers – for error free programs
c) CASE tools – Computer Assisted Software Engineering Tools
2. Application Software
 It contains programs for performing tasks
 It is divided into 2 classes
Application
Software

general application
purpose specific

General purpose software


 These are purchased from software developers
 They can be used for more than one application
 Eg: word processors, DBMS etc…
Application Specific Software
 It can be used only for intended purpose i.e. for which they were designed
 eg: Accounting system, hospital management system, banking system. Etc.
Computer
System

Computer Computer
Hardware Software

CPU Peripherals System Application


Software Software

i/p o/p Operating System General Application


devices devices System Support Purpose Specific

System
Development

9
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
COMPUTER ENVIRONMENTS
 In early days, there was only one environment i.e. the mainframe computer. It occupies much
space and consumed large amount of power.
 With the invention of transistor and IC (Integrated Circuits) technology, mini computers were
introduced in which many components are fused together.
 After invention of microprocessor technology, the environment changed resulting in mini-
computers and personal computers
 The computing environments are classified into 4 types. They are
1) Personal computing environment
2) Time sharing environment
3) Client – server environment
4) Distributed computing environment
1) Personal computing environment
 In a personal computer, all the basic elements of the CPU are combined into the
microprocessor and all the hardware components are tied together.
 The whole computer can be used by the user to perform his task independently

Fig : personal computing environment


 Disadvantage
Much of the CPU time is wasted
2) Time- Sharing environment
 For effective usage of CPU time, many users are connected to one (or) more computers to
form a time- sharing environment.
 There will be a central computer which performs the following:
- controls the shared resources
- manages shared data & printing
- does the computing

10
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Advantage :
Computer is busy always reducing CPU idle time
Disadvantage
Response becomes slow as the number of users connected to the central computer increases

Terminals
Fig : Time-sharing environment
3) Client – Server environment
 This environment splits the computing function between a central computer and user
computer
 Users are given personal computer (PC‟s) on workstations so that some of computation
responsibility can be moved from central computer and assigned to the workstation
 User‟s workstations (or) micro computers are called as “Clients”
 The powerful central mainframe (or) micro computer is known as “Server”

Advantages
- Response time is faster
- Users are more productive

11
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Fig: Client-server environment


4) Distributed computing environment
 It provides integration of computing functions between different servers and clients
 “Internet” provides connectivity to different servers throughout the world.
 It provides
-- reliable
-- scalable
-- highly available network

Fig:Distributed computing environment

12
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
COMPUTER LANGUAGES
 Computer programming languages are used to give instructions to the computer in a language
which computer understands
 Computer languages are classified into 3 types
1) Machine languages
2) Symbolic languages
3) High level languages
1) Machine languages
 Computer is a machine and since its memory can store only 1‟s and 0‟s, instructions must be
given to the computer in streams of 1‟s and 0‟s i.e. binary code.
 These are easily understandable by the machine
 Programs written in binary code can be directly fed to computer for execution and it is known
as machine language.
Advantage :
 Execution is very fast since there is no need of conversion
Disadvantage :
 Writing and reading programs in machine language is very difficult
 Machine instructions are difficult to remember
2) Symbolic Languages
 It is also called as assembly language
 An assembly program contains “Mnemonics”
 “Mnemonic” means information can be memorized easily and is generally in the form of
abbreviations.
Advantage :
 Easy to read and write programs in assembly language when compared to machine language
 Mnemonics are easy to remember
Disadvantage :
 Assembly programs are machine dependent
 Execution is slow since it needs conversion into machine language
 “Assembler” is used to convert assembly language program into machine language.

Assembler
Assembly language program Machine Language code

13
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
3) High level languages
 A set of languages which are very close to our native languages are called “ high-level
languages”.
 High level languages have control structures, I/O facilities, hardware independence
 eg: FORTRAN, COBOL, PASCAL, C, C++ etc..
Advantage :
 Machine independence i.e. programs are “Portable” i.e. programs can be moved from one
system to another
 Easy to learn and understand
 Takes less time to write programs
Disadvantage :
 High level language programs needs a translator for conversion into machine language
 „Compilers‟ (or) „Interpreters‟ are used for converting high level language program into
machine language..

Compiler /
High level language program Interpreter Machine Language code

 Compiler converts entire statements in the program at a time.


 Interpreter converts one statement at a time.
CREATING AND RUNNING PROGRAMS
 Program consists of set of instructions written in a programming language
 The job of a programmer is to write and test the program.
 There are 4 steps for converting a „C‟ program into machine language.
1) Writing and editing the program
2) Compiling the program
3) Linking the program
4) Executing the program
1) Writing and editing the program
 „Text editors‟ are used to write programs.
 Users can enter, change and store character data using text editors
 Special text editor is often included with a compiler
 After writing the program, the file is saved to disk. It is known as „source file‟
 This file is input to the compiler

14
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
C file

#include<stdio.h>
Programmer Text Editor Source file main ( )
{
-----
-----
-----
}
2) Compiling the program
 “Compiler” is a software that translates the source file into machine language
 The „C‟ compiler is actually 2 separate programs
a) Preprocessor
b) Translator
A) Preprocessor
 It reads the source code and prepares it for the translator
 It scans for special instructions known as „preprocessor‟ commands which start with „ #‟
symbol
 These commands tell the preprocessor to look for special code libraries and make
substitutions
 The result of preprocessing is called „translation‟ unit

Preprocessor
Source File translation unit
B) Translator
 It does the actual work of converting the program into machine language
 It reads the translation unit and results in „object module‟ i.e., code in machine language
 But it is not yet executable because it does not have the „C‟ and other functions included.

Translator
Translation unit Object Module .obj file
00110 100
10101 010
3) Linking programs
 „Linker‟ assembles input /output functions, mathematical library functions and some of the
functions that are part of source program into final executable program
 It is called as executable file that it is ready for execution .exe file
1011001100
Linker 110111011
Object file executable file 1100101010

15
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

4) Executing Programs
 „Loader‟ is the software that gets the program that is ready for execution into the memory
 When everything is loaded, the program takes control and the „Runner‟ begins its execution.
 In the process of execution, the program reads the data from the user, processes the data and
prepares the output

SOFTWARE DEVELOPMENT METHOD


 Software is collection of programs
 Programming is a problem solving task / activity
 Programmers use the software development method for solving problems
 It consists of the following 6 phases
1) Requirements
2) Analysis
3) Design
4) Coding
5) Testing
6) Maintenance
1) Requirements
 Information about the problem must be stated clearly and unambiguously
 Main objective of this phase is to eliminate unimportant aspects and identify the root problem
2) Analysis
 It involves identifying the problem inputs, outputs, that the program must produce
 It also determines the required format in which results should be displayed

16
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

3) Design
 It involves designing algorithms, flowcharts (or) GUI‟s (Graphical User Interfaces)
 Designing the „algorithm‟ is to develop a list of steps called algorithm to solve the problem
and then verify that the algorithm solves the problem intended.
 “Top – down design” is followed i.e. list the major steps (or) sub problems that need to be
solved
 “Flow charts” are used to get the pictorial representation of the algorithm.
 Algorithm for a programming problem consists of at least the following sub problems
1. Get the data
2. Perform the computations
3. Display the results
4) Coding / Implementation
 This step involves writing algorithm as a program by selecting any one of the high – level
languages that is suitable for the problem.
 Each step of the algorithm is converted into one (or) more statements in a programming
language.
5) Testing
 Checking / verifying whether the completed program works as desired is called “ Testing”
 Running the program several times using different sets of data verifies whether a program
works correctly for every situation provided in the algorithm.
 After testing, the program must be free from the following errors.
a) Syntax errors
b) Logical errors
c) Run-time errors
6) Maintenance
 It involves modifying a program to remove previously undetected errors and to keep it
up-to-date as government regulations (or) company polices change.
 Many organizations maintains a program for some period of time i.e. 5 years

17
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

System
requirements

Analysis

Design

Coding

Testing

 This is called „waterfall‟ model Maintenance

 It is necessary to go back to the previous phase to rework it


APPLYING THE SOFTWARE DEVELOPMENT METHOD
1) Problem requirement
 Finding the roots of a quadratic equation, ax2+bx+c
 There will be 2 roots for such quadratic equation
2) Analysis
Input : a,b,c values
Output: r1, r2 values

b  b 2  4ac
Procedure : r1 
2a

b  b 2  4ac
r2 
2a
3) Design
Algorithm
1. start
2. Read a,b,c values
3. Compute d = b2  4ac
4. if d > 0 then
a) r1 =  b+ sqrt (d)/(2*a)
b) r2 =  b  sqrt(d)/ (2*a)

18
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

5. otherwise if d = 0 then
a) compute r1 = -b/2a
r2=-b/2a
b) print r1,r2 values
6. otherwise if d < 0 then print roots are imaginary
7. Stop
Flowchart
Start

Read 3 Numbers
a,b,c

Compute d b2-4ac

True IS False
d>0?

Compute
r1 -b+sqrt(d)/ (2*a) False True
Is
r2  -b- sqrt(d)/ (2*a) d==0?

Print roots are Compute


imaginary r1 -b/(2*a)
r2  -b/(2*a)
Print r1, r2 values

Print r1, r2
values

Stop

4. Implementation
C-code
# include<stdio.h>
# include<conio.h>
# include<math.h>
main ( )

19
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
float a,b,c,r1,r2,d;
clrscr ( );
printf (“enter a,b,c values”);
scanf (“ %f %f %f”, &a, &b, &c);
d= b*b – 4*a*c;
if (d>0)
{
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf (“Roots are real and are %f %f”, r1, r2);
}
else if (d= =0)
{
r1 = -b/(2*a);
r2 = -b/(2*a);
printf (“Roots are equal and are %f %f”, r1, r2);
}
else
printf(“Roots are imaginary”);
getch ( );
}
5) Testing
Case 1: Enter a,b,c values : 1 4 3
r1 = -1
r2 = -3
Case 2: Enter a,b,c values : 1 2 1
r1 = -1
r2 = -1
Case 3: Enter a,b,c values : 1 1 4
Roots are imaginary
ALGORITHM:
 It is a step – by – step procedure for solving a problem
 If algorithm is written in English like sentences then it is called as „PSEUDO CODE‟

20
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Properties of an Algorithm
An algorithm must posses the following 5 properties. They are
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
1. Input : An algorithm must have zero (or) more number of inputs
2. Output: Algorithm must produce one (or) more number of outputs
3. Finiteness : An algorithm must terminate in countable number of steps
4. Definiteness: Each step of the algorithm must be stated clearly
5. Effectiveness: Each step of the algorithm must be easily convertible into program statements
Example
Algorithm for finding the average of 3 numbers
1. start
2. Read 3 numbers a,b,c
3. Compute sum = a+b+c
4. compute avg = sum/3
5. Print avg value
6. Stop
FLOW CHART
Diagramatic representation of an algorithm is called flow chart
Advantages of flow chart
 It is very easy to understand because the reader follows the process quickly from the
flowchart instead of going through the text.

 It is the best way of representing the sequence of steps in an algorithm

 It gives a clear idea about the problem

 Various symbols are used for representing different operations

 Arrows are used for connecting the symbols and show the flow of execution

21
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Symbols used in flowchart:

Name Symbol Purpose


Terminal Start /stop/begin/end

oval
Input / output Input/output of data

Parallelogram
Process Any processing to be performed
can be represented

Rectangle
Decision box Decision operations that
determine which of the
alternative paths to be followed
Diamond
Connector Used to connect different parts
of flowchart
Circle
Flow Joins 2 symbols and also
represents flow of execution
Arrows
Pre defined process Modules (or)subroutines
specified else where

Double sided rectangle


Page connector Used to connect flowchart in 2
different pages

Pentagon
For loop symbol Shows initialization, condition
and incrementation of loop
variable.
Hexagon
Document Shows the data that is ready for
printout

Printout

22
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Example
Flowchart for finding the average of 3 numbers

Start

Read 3 Numbers a,b,c

Compute sum a+b+c

Compute avg sum/3

Print avg value

Stop

23
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

24
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

25
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
INTRODUCTION TO „C‟ LANGUAGE
 „C‟ is a high –level programming language developed in 1972 by Dennis Ritchie at AT & T
Bell Laboratories
 It was primarily developed for system programming i.e. for designing operating systems,
compilers etc
Importance of ‟C‟ Language
1. It is a robust language, whose rich set of built-in functions and operations can be used to write
any complex program
2. It is a middle level language because the „C‟ compiler combines the capabilities of an assembly
language with the features of a high-level language and therefore it is well suited for writing both
system software and business packages.
3. „C‟ Programs are efficient and fast
4. C is highly portable, that is „C‟ programs written on one computer can be run on another with
little (or) no modification.
5. „C‟ Language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules (or) blocks.
6. „C‟ program has the ability to extend itself.
 It was named „C‟ because it is an offspring of BCPL (Basic Combined Programming
Language) which was popularly called „B‟ language.
General form of a „C‟ program
/* documentation section */
preprocessor directives
global declaration
main ( )
{
local declaration
executable statements
}
returntype function name (argument list)
{
local declaration
executable statements
}

26
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Example:
/* Author : Ramu
Aim : Program for finding circumference of circle*/
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
main ( )
{
float c, r;
clrscr ( );
printf (“enter radius of circle”);
scanf (“%f”, &r);
c = 2 * PI * r;
printf (“Circumference = %f”, c);
getch ( );
}
„C‟ LANGUAGE ELEMENTS
„C‟ program contains several elements which are present in structure of „C‟ program. They are
1) Comment lines
2) Preprocessor directives
3) Variable declaration & data types
4) Executable statements
1. Comment lines
 In „C‟, comment lines are placed in “ /* */”
 Single line and multiple lines are enclosed in /* and */
 Comment lines are ignored by the compiler
 The documentation section is enclosed in comment lines
 Documentation section consists of a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to use later.
2. Preprocessor directives
 It consists of a) link section
b) Definition Section
 The link section provides instructions to the compiler to link functions from the system
library

27
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
eg : #include < stdio.h>
 The definition section defines all symbolic constants
eg : #define PI 3.1415
 Preprocessor directive must start with „#‟ (hash) symbol.
3. Variable declaration & data types
Variable
 It is the name given to a memory location that may be used to store a data value
 A variable may take different values at different times during execution
 A variable name may be chosen by the programmer in a meaningful way so as to reflect its
function (or) nature in the program
Eg: sum, avg , total etc.
Rules for naming a variable
1) They must begin with a letter
2) The length of the variable must not exceed 31 characters in ANSI standard. But first eight
characters are treated as significant by many compilers
3) Upper and lowercase characters are different
Eg: total, TOTAL, Total are 3 different variables
4) The variable name should not be a keyword
5) White space is not allowed
Data Types
 Data type specifies the set of values and the type of data that can be stored in a variable.
 They allow the programmer to select the type appropriate to the needs of application.
Types :
1) Primary data types
2) Derived data types
1. Primary data types
„C‟ compilers support 4 fundamental data types
They are
1) integer
2) character
3) Floating – point
4) Double precision floating point

28
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
PRIMRARY DATA TYPES

Integral Type

Integer
character
Signed Unsigned
signed char
int unsigned int
short int unsigned short int unsigned char
long int unsigned long int

Floating point type


float double long double

1. Integral data type


 Integral data types are used to store whole numbers and characters
 It is further classified into
a) integer data type
b) character data type
a) Integer data type
 This data type is used to store whole numbers
 It has 3 classes of integer storage namely, short int, int and long int in both signed and
unsigned forms

Integer Data type


Type size (in bytes) Range Control string
Short int (or) 1 -128 to 127 %h
signed short int
Unsigned short int 1 0 to 255 % uh
int (or) signed int 2 -32768 to 32767 % d or %i
unsigned int 2 0 to 65535 %u
Long int (or) 4 -2147483648 to %ld
signed long int 2147483647
Unsigned long int 4 0 to 4294967295 %lu
b) character data type
 This data type is used to store characters
 These characters are internally stored as integers
 Each character has an equivalent ASCII value
eg: „A‟ has ASCII value 65

29
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Character data type


Type Size (in bytes) Range Control string
Char (or) signed 1 - 128 to +127 %c
char
Unsigned char 1 0 to 255 %c
2. Floating – point Data types
 It is used to store real numbers (i.e., decimal point numbers).
 For 6 digits of accuracy, „float‟ is used.
 For 12 digits of accuracy, „double' is used.
 For more than 12 digits of accuracy, „long double‟ is used..

Floating point data type


Type Size (in bytes) Range Control string
float 4 3.4 E – 38 to 3.4 E + 38 %f
double 8 1.7 E – 308 to 1.7 E +308 %lf
long double 10 3.4 E – 4932 to 1.1 E +4932 %Lf

Variable declaration
Syntax:
Datatype v1,v2,… vn;
Where v1, v2,...vn are names of variables
eg: int sum;
float a,b;
 Variable can be declared in 2 ways
1. local declaration
2. global declaration
 „local declaration‟ is declaring a variable inside the main block and its value is available within
that block
 „global declaration‟ is declaring a variable outside the main block and its value is available
through out the program.
 Eg :
int a, b; /* global declaration*/
main ( )
{
int c; /* local declaration*/
- - -
}

30
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
EXECUTABLE STATEMENTS:
 A „C‟ program contains executable statements
 The „C‟ compiler translates the executable statements into machine language
 The machine language versions of these statements are executed by the compiler when a user
runs program
Types
1) Input – output statements
2) Assignment statements
1. Input – output statements
 Storing a value into memory is called „ input operation‟.
 After executing the computations, the results are stored in memory and the results can be
displayed to the user by „output operation‟
 All input / output operations in „C‟ are performed using input / output functions
 The most common I/O functions are supplied as part of the „C‟ standard I/O library through
the preprocessor directive # include<stdio.h>
 Most commonly used I/O functions are
a) printf ( )
b) scanf ( )
a) printf ( ) function:
Syntax:
printf(“format string”, print list);
e.g.: printf (“average of 3 numbers = %f”,avg);
* The printf ( ) function displays the value of its format string after substituting the values of
the expressions in the print list.
* It also replaces the escape sequences such as „\n‟ by their meanings.
b) scanf ( ) function
Syntax:
scanf (“format string”, input list);
e.g.: scanf (“%d %f”, &a, &b);
 The scanf ( ) function copies into memory data typed at the keyboard by the program user
during program execution.
 The input list must be preceded by ampersand ( &)

31
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2) Assignment statements
 The assignment statements stores a value (or) a computational result in a variable and is used
to perform most arithmetic operations in a program.
 Syntax: variable=expression
 e.g.:
1. c = a+b;
2. avg = sum/3;
3. r1 = (b*b – 4 * a*c);
 The variable before the assignment operator is assigned the value of the expression after it.
 The previous value of variable is destroyed
EXPRESSIONS
 Def: An expression is a combination of operators and operands which reduces to a single
value
 An operand is a data item on which an operation is performed.
 An operator indicates an operation to be performed on data
eg; z = 3+2*1
z=5
Types Expression

Primary Postfix prefix unary binary ternary

1. Primary expressions
The operand in the primary expression can be a name, a constant or any parenthesized expression
E.g.: c = a+ (5*b);
2. Postfix expressions:
The operator will be after the operands in a postfix expression
Eg:
ab+
3. Prefix expressions
The operator is before the operand in a prefix expression.
Eg:
+ab

32
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
4. unary expression:
It contains one operator and one operand
eg: a++, --b
5. Binary expression
It contains 2 operands and one operator
Eg: a+b, c-d
6. Ternary expression
It contains 3 operands and one operator
Eg ; Exp1? Exp2 :Exp3
If Exp1 is true ,Exp2 is executed. otherwise Exp3 is executed.

OPERATORS AND EXPRESSIONS


 Operator performs an operation on data
 Operators are classified into
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Bitwise operators.
7. Conditional operators.
8. Special operators.
1). Arithmetic operator
 These operators are used for numerical calculations (or) to perform arithmetic operations like
addition, subtraction etc.

Operator Description Example a =20, b=10 output


+ Addition a+b 20+10 30
- Subtraction a-b 20-10 10
* Multiplication a*b 20*10 200
/ Division a/b 20/10 2 (quotient)
% Modular division a%b 20%10 0 (remainder)

33
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 Program:
main ( )
{
int a= 20, b = 10; Output
printf (“ %d”, a+b); 30

printf (“ %d”, a-b); 10

printf (“ %d”, a*b); 200

printf (“ %d”, a/b); 2

printf (“ %d”, a%b); 0

}
2).Relational operators :
 These are used for comparing two expressions.

Operator Description Examble a =10, b=20 output


< less than a<b 10<20 1
<= less than (or) a<=b 10< = 20 1
equal to
> greater than a>b 10>20 0
>= greater than (or) a>=b 10> =20 0
equal to
== equal to a= =b 10 = = 20 0
!= not equal to a! = b 10 ! =20 1
 The output of a relational expression is either true (1) (or) false (0)
 Program
main ( )
{
int a= 10, b = 20; Output
printf (“ %d”, a<b); 1
printf (“ %d”, a<=b); 1
printf (“ %d”, a>b); 0
printf (“ %d”, a>=b); 0
printf (“ %d”, a = =b); 0
printf (“ %d”, a ! =b); 1

} 1
3. Logical Operators 1
 These are used to combine 2 (or) more expressions logically

34
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 They are logical AND (&&) logical OR ( || ) and logical NOT (!)
Logical AND ( && )
exp1 exp2 exp1&&exp2
T T T
T F F
F T F
F F F

Logical OR( || )
exp1 exp2 exp1||exp2
T T T
T F T
F T T
F F F

Logical NOT (!)


exp !(exp)
T F
F T

Operator Description Example a =10, b=20,c=30 output


&& logical AND (a>b) && (a<c) (10>20) & & (10<30) 0
|| logical OR (a>b) | | (a<c) (10>20) ||(10<30) 1
! logical NOT ! (a>b) ! (10>20) 1

Program:
main ( )
{
int a= 10, b = 20, c= 30;
Output
printf (“ %d”, (a>b) && (a<c)); 0
printf (“ %d”, (a>b) | | (a<c)); 1
printf (“ %d”, ! (a>b)); 1
}
4. Assignment operators
 It is used to assign a value to a variable
Types
1) simple assignment 2)compound assignment

35
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Operator Description Example


= Simple a=10
assignment
+ =, - =, Compound a+=10  a=a+10
* =, / =, %= assignment a-=10  a=a-10

Program:
main ( )
{ int a= 10,; Output
printf (“ %d”, a); 10

printf (“ %d”, a+ =10); 20

}
5. Increment and decrement operator:
a) Increment operator (++):
 It is used to increment the value of a variable by 1
 2 types : i) pre increment
ii) post increment
 increment operator is placed before the operand in preincrement and the value is first
incremented and then operation is performed on it.
eg: z = ++a; a= a+1
z=a

 increment operator is placed after the operand in post increment and the value is incremented
after the operation is performed
eg: z = a++; z=a
a= a+1
Program main ( )
main ( ) {
{ int a= 10, z;
int a= 10, z; z= a++;
Output
z= ++a ; Output printf (“z= %d”, z); z=10
z=11
printf (“z= %d”, z); printf (“a=%d”, a); a = 11
a =11
printf (“ a=%d”, a); }
}

36
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
b) Decrement operator : (- -)
 It is used to decrement the values of a variable by 1
2 types : i) pre decrement
ii) post decrement
 decrement operator is placed before the operand in predecrement and the value is first
decremented and then operation is performed on it.
eg: z = - - a; a= a-1
z=a

 decrement operator is placed after the operand in post decrement and the value is
decremented after the operation is performed
eg: z = a--; z=a
a= a-1

Program:
main ( ) main ( )

{ {

int a= 10, z; int a= 10, z;

z= --a; z= a--;
Output
printf (“z= %d”, z);
Output printf (“z= %d”, z); z=10
z=9
printf (“ a=%d”, a); printf (“a=%d”, a); a=9
a =9
} }

6. Bitwise Operator
Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on operand)

Operator Description

& Bitwise AND


| Bitwise OR
^ Bitwise XOR
<< Left shift
>> Right shift
~ One‟s complement

37
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Bitwise AND Bitwise OR Bitwise XOR

a b a &b a b a|b a b a ^b
0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 0 1 1
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0

eg: let a= 12, b=10


a&b a|b

8 4 2 1 8 4 2 1
a =12 1 1 0 0 a =12 1 1 0 0
b =10 1 0 1 0 b =10 1 0 1 0
a &b 1 0 0 0 a|b 1 1 1 0
a&b = 8 a | b = 14

a^b

8 4 2 1
a =12 1 1 0 0
b =10 1 0 1 0
a ^b 0 1 1 0
a^b=6

Program
main ( )
{
int a= 12, b = 10; Output
printf (“ %d”, a&b); 8

printf (“ %d”, a| b); 14

printf (“ %d”, a ^ b); 6

}
Left Shift
 If the value of a variable is left shifted one time, then its value gets doubled
 eg: a = 10 then a<<1 = 20

38
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

32 16 8 4 2 1
a=10
1 0 1 0

a<<1 1 0 1 0 0 Fill it with zero

a<<1 = 20
Right shift
If the value of a variable is right shifted one time, then its value becomes half the original value
 eg: a = 10 then a>>1 = 5
8 4 2 1
a=10
1 0 1 0

a>>1 0 Discard it
1 0 1

a>>1 = 5
Ones complement
 It converts all ones to zeros and zeros to ones
 Eg: a = 5 then ~a=2 [only if 4 bits are considered]
8 4 2 1
a=5
1 0 1

~a
0 1 0

~a = 2
Program
main ( )
{
int a= 20, b = 10,c=10; Output
printf (“ %d”, a<<1); 40

printf (“ %d”, b>>1); 5

printf (“ %d”, ~c); 11

}
Signed
1‟s complement = - [ give no +1]
Eg : ~10 = - [10+1] = -11
~-10 = - [-10+1] = 9

39
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
unsigned
1‟s complement = [65535 – given no]
7. Conditional operator (? :)
 It is also called ternary operator
 Syntax:
exp1 ? exp2 : exp3
 if exp1 is true exp2 is evaluated, otherwise exp3 is evaluated
 it can also be represented in if – else form
if (exp1)
exp2;
else
exp3;
Program
main ( )
{ int z;
z = (5>3) ? 1:0; Output
printf (“%d”,z); 1

}
8) Special operations
Some of the special operations are comma, ampersand(&), size of operators.
a) Comma: ( , )
It is used as separator for variables
eg; a=10, b=20
b) Address:(&)
It is used to get the address of a variables.
c) Size of ( ) ;
It is used to get the size of a data type of a variable in bytes.
Program:
main ( )
{
int a=10;
float b=20 ;
printf (“ a= %d b=%f”, a,b );
printf (“ Address of a =%u “ , &a ) ;

40
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf (“ Address of b =%u” ,&b ) ;
printf (“Size of a = %d ” , sizeof (a) ) ;
printf ( “Size of b = %d ”, sizeof (b) ) ;
} a b
Out Put : 10 20.00
a=10 b=20.00 1234 5678
Address of a =1 2 3 4
Address of b = 5 6 7 8 Only for this example

Size of a = 2 bytes
Size of b = 4 bytes

EXPRESSION EVALUATION, PRECEDENCE AND ASSOCIATIVITY


 Expressions are evaluated by the „C‟ compiler based on precedence and associativity rules.
 If an expression contains different priority operators then precedence rules are considered.

Operator Precedence Chart

Operator Type Operator Associativity

Primary Expression
() [] . -> expr++ expr-- left-to-right
Operators

* & + - ! ~ ++expr --expr (typecast)


Unary Operators right-to-left
sizeof

* / %

+ -

Binary Operators >> << left-to-right

< > <= >=

== !=

41
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

&

&&

||

Ternary Operator ?: right-to-left

Assignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-left

Comma , left-to-right

Eg: C = 30 - 10 * 2

20
2

10
3

Here, 10*2 is evaluated first since „*‟ has more priority than „-„ and „=‟
 If an expression contains same priority then assoiciativity rules are considered i.e. left right
(or right to left)
eg: z= a*b/c
z = 40 * 20 / 10 Here „*‟ and „/‟ have same priority so, left to right
associativity is considered

800
2
z
80
3

42
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Eg: x =5 *4 + 8/2 x = 5 * 4 + 8 / 2

1 2

x = 24
Parenthesis has highest priority and comma has least priority among operators
Type Conversions
Converting one data type into another is the concept of type conversion
2 types
1. Implicit type conversion
2. Explicit type conversion
 Implicit type conversion is automatically done by the compiler by converting smaller data
type into a larger data type.
Eg: int i,x;
float f;
double d;
long int l;

x = l / i + x - f - d

long float

long float

float
`
Float

Double

int double

43
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Here, the above expression finally evaluates to a‟double‟ value
Explicit type conversion is done by the user by using (type) operator
Eg: int a,c;
float b;
c = (int) a + b

int float
float
int
Here, the resultant of „a+b‟ is converted into „int‟ explicitty and then assigned to „c‟
Program:
main ( )
{
Output
printf (“%d”, 5/2); 2
printf (“%f”, 5.5/2); 2.75
printf (“%f”, (float) 5/2); 2.5
}

Decision statements :
These are used to make a decision among the alternative paths
They are
1. simple – if statement
2. if – else statement
3. nested – if else statement
4. else – if ladder
5. switch statement

1. Simple – if statement
 „if‟ keyword is used to execute a set of statements when the logical condition is true
Syntax :
if (condition)
{
Statement (s)
}

44
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Flow chart
True False
Cond
ition?

Statement (s)

Program /* checking whether a number is greater than 50 */


main ( )
{
int a;
printf (“enter a number”);
scanf (“%d”, &a);
if (a>50)
printf (“%d is greater than 50”, a);
}
Output
1) enter a number 60 2) enter a number 20
60 is greater than 50 no output.

2. if else statement
 If –else statement takes care of true as well as false conditions
 „true block‟ is executed when the condition is true and „false block‟ (or) „else block‟ is
executed when the condition is false.
Syntax:
if (condition)
{
True block statement(s)
}
else

45
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
False block statement(s)
}

Flow chart
True False
Cond
ition?

True block False block


statement(s) statement (s)

Program
/* checking for even (or) odd number */
main ( )
{
int n;
printf (“enter a number”);
scanf (“%d”, &n);
if (n%2 ==0)
printf (“%d is even number”, n);
else
printf( “%d is odd number”, n);
}
Output
1) enter a number 10 2) enter a number 5
10 is even number 5 is odd number
3. Nested if - else statement
 A „nested if‟ is an if statement that is the object of either if (or) an else
 „if‟ is placed inside another if (or) else
Syntax:
if (condition1)
{
if (condition2)
stmt1;

46
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
else
stmt2;
}

else
{
if (condition3)
stmt3;
else
stmt4;
}
Flow chart
True Cond False
ition1

True Condi False True Cond False


tion2 ition3

Stmt1 Stmt2 Stmt3 Stmt4

Program /* largest of 3 numbers */


main ( )
{
int a,b,c;
printf (“enter 3 numbers”);
scanf (“%d%d%d”, &a, &b, &c);
if (a>b)
{ if (a>c)
printf (“%d is largest”, a);
else

47
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf (“%d is largest”, c);
}

else
{
if (b>c)
printf (“%d is largest”, b);
else
printf (“%d is largest”, c);
}
}
Output
enter 3 numbers = 10 20 30
30 is largest

4. Else – if ladder
 This is the most general way of writing a multi-way decision
Syntax
if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
-----
else if (condition n)
stmtn;
else
stmt x;

48
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
flow chart

True Condi False


tion1?

True Condi False


tion2?
Stmt1
------
Stmt2

True Condit False


ion n?

Stmt n Stmt x

Program /* finding roots of quadratic equation */


#include <math.h>
main ( )
{
int a,b,c,d;
float r1, r2
printf (“enter a,b,c values”);
scanf (“%d%d%d”, &a, &b, &c);
d= b*b – 4*a*c ;
if (d>0)
{
r1 = (-b+sqrt(d)) / (2*a);
r2 = (-b-sqrt(d)) / (2*a);
printf (“root1 = %f, root2 == %f”, r1, r2);
}
else if (d= = 0)
{
r1 = -b / (2*a);

49
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
r2 = -b/ (2*a);
printf (“root1 = %f, root2 = %f”, r1, r2);
}
else
printf ("roots are imaginary”);
}
Output
1) enter a,b, c values : 1 4 3
Root 1 = -1
Root 2 = -3
2) enter a,b, c values : 1 2 1
Root 1 = -1
Root 2 = -1
3) enter a,b, c values : 1 2 3
roots are imaginary
5. Switch statement
 It is used to select one among multiple decisions
 „switch‟ successively tests a value against a list of integer (or) character constant.
 When a match is found, the statement (or) statements associated with that value are executed.
Syntax
switch (expression)
{
case value1 : stmt1;
break;
case value2 : stmt2;
break;
------
default : stmt – x;
}

50
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Flow chart

Switch
(expressi
on)

Exp =value1 Stmt1

Exp =value2
Stmt2
|
|
default Stmt-x

Program
main ( )
{
int n;
printf (“enter a number”);
scanf (“%d”, &n);
switch (n)
{
case 0 : printf (“zero”)
break;
case 1 : printf („one”);
break;
default : printf („wrong choice”);
}
}

51
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Output
enter a number
1
one
Loop control statements
 These are used to repeat set of statements
 They are
1) for loop
2) while loop
3) do-while loop
1) for loop
Syntax
for (initialization ; condition ; increment / decrement)
{
body of the loop
}
Flow chart

False
Initialization Increment/
condition decrement

True

Body of the loop

 for statement contains 3 parts


i) initialization is usually an assignment statement that is used to set the loop control variable
ii) The condition is a relational expression that determines when the loop will exit.
iii) The increment/decrement part defines how the loop control variable will change each time
loop is repeated.
iv) loop continues to execute as long as the condition is true.
v) Once the condition is false, program continues with the next statement after for loop.

52
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program
main( )
{ Output
int k; 1

for (k = 1; k<=s; k++) 2

{ 3

printf (”%d”,k); 4

} 5

}
2) while loop
Syntax
while (condition)
{
body of the loop
}

Flow chart
initialization

Is False
expression?

True

Body of the loop

Incr/ dec

 Intialization is done before the loop


 Loop continues as long as the condition is true
 Incrementation and decrementation part is done within the loop

53
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program
main( )
{
int k; Output
k = 1; 1
while (k< = 5) 2
{
printf (”%d”,k); 3
k++; 4
}
} 5
3) do-while loop
Syntax
Initialization
do
{
body of the loop
inc/ dec
} while (condition);

Flow chart
initialization

Body of the loop

Incr/ dec

True Is
expression?

False

54
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program
main( )
{ Output
int k; 1

k = 1; 2

do 3

{ 4

printf (”%d”,k); 5

k++;
} while (k <= 5);
}
Nested for loops
 In nested for loops one (or) more for statements are included in the body of the loop
 The number of iterations in this type of structure will be equal to number of iterations in the
outer loop multiplied by the number of iterations in the inner loop
Program
main( )
{
int i,j; Output
for (i=1; i<=2; i++) 1
{ 2
for (j=1;j<=2; j++)
{ 2
printf (”%d”, i*j); 4
}
} 3
} 6
Execution i*j
i=1 j=1 1
j=2 2
i=2 j=1 2
j=2 4
i=3 j=1 3
j=2 6
Other related statements
1) break
2) continue
3) goto

55
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
1) break
 It is a keyword used to terminate the loop (or) exit from the block
 The control jumps to next statement after the loop (or) block
 „break is used with for, while, do-while and switch statement
 When break is used in nested loops then only the innermost loop is terminated
Syntax
{ Stmt1;
Stmt2;
break;
Stmt3;
Stmt4;
}

Program
main( )
{ int i; Output
for (i=1; i<=5; i++) 1

{ 2

printf (”%d”, i); 3

if (i= =3)
break;
}
}
2) continue
 It is a keyword used for continuing the next iteration of the loop
 It skips the statements after the continue statement
 It is used with for, while and do-while
Syntax
{
Stmt1;
Stmt2;
continue;
Stmt3;
Stmt4;
}

56
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program
main( ) Output
1
{
3
int i;
4
for (i=1; i<=5; i++)
5
{
if (i= =2)
continue,
printf(“%d”, i)
}
}

3) goto
 It is used to after the normal sequence of program execution by transferring the control to
some other part of program

Syntax Forward jump backward jump


goto label; label :stmt
---- ----
---- ----
---- ----
label : stmt goto label;

Program
main( ) Output
Hello
{
you
printf(‟Hello”);
goto l1;
printf(”How are”);
l1: printf(”you”);
}

57
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

58
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

59
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

FUNCTIONS
Def : A function is a self contained block that carries out a specific well defined task.
Advantages
1. Reusability i.e. a function may be used by many other programs.
2. The length of the source program can be reduced.
3. It is easy to locate and isolate a faulty function.
4. It facilitates top-down modular programming.

Top down design and structure charts


 “Top down design” is a problem solving method in which a complex problem is solved by
breaking up into sub problems.
 It proceeds from the original problem at the top level to the sub problems at each lower level
 “structure chart” is a documentation tool that shows the relationships among the sub
problems of a problem.

Main Program

Function1 Function 2 Function 3 Function 4

 The splitting of a problem into its related sub problems is analogous to the process of refining
an algorithm.
e.g. Performing arithmetic operations on 2 numbers
1. find sum
2. find difference
3. find product
4. find quotient
Refined algorithm for 1st step
1.1 take 2 numbers a, b
1.2 sum, c = a + b
1.3 print sum

60
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Structure chart
Arithmetic Operations
on 2numbers

Find Sum Find Difference Find Product Find Quotient

Input 2 Product = Print Product


Numbers a, b a*b

Types of functions
Functions are broadly classified into 2 types
They are
1) predefined functions
2) user defined functions
1) predefined (or) library functions
 These functions are already defined in the system libraries
 Programmer can reuse the existing code in the system libraries to write error free code.
 But to use the library functions, user must be aware of syntax of the function.

eg: 1) sqrt() function is available in math.h library and its usage is :


y= sqrt (x)
number must be positive
eg: y = sqrt (25)
then „y‟ = 5
2 printf ( ) function is available in stdio.h library
3) clrscr ( ) function is available in conio.h library
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
main ( )
{
int x,y;
clrscr ( );
printf (“enter a positive number”);

61
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
scanf (“ %d”, &x)
y = sqrt(x);
printf(“squareroot = %d”, y);
getch();
}
Output
Enter a positive number 25
Squareroot = 5
2) user defined functions
These functions must be defined by the programmer (or) user
Programmer has to write the coding for such functions and test them properly before using them
The syntax of the function is also given by the user and therefore need not include any header files.
Eg: main ( ), swap ( ), sum ( ) etc
Program
#include<stdio.h>
#include<conio.h>
main ( )
{
int sum (int, int);
int a, b, c;
clrscr ( );
printf (“enter 2 numbers”);
scanf (“ %d %d”, &a ,&b)
c = sum (a,b);
printf(“sum = %d”, c);
getch();
}
int sum (int a, int b)
{
int c;
c=a+b;
return c;
}

62
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Output
Enter 2 numbers 10 20
Sum = 30
Communications Among functions
Functions communicate among themselves using arguments and return value.
Farm of „C‟ function
return-datatype function name (argument list)
{
local variable declarations;
executable statements(s);
return (expression);
}
eg: void mul (int x, int y)
{
int p;
p=x*y;
printf(“product = %d”,p);
}
Return values and their types
 A function may (or) may not send back any value to the calling function
 If it does, it is done through the return statement
 A called function can only return one value per call
 The return types are void, int, float, char and double.
 If a function is not returning any value then its return type is „void‟
Function name
 A function must follow the same rules of formation as other variables name in „C‟
 A function name must not duplicate library routine names (or) predefined function names.
Argument list
 The argument list contains valid variable names separated by commas
 The argument variables receive values from the calling function, thus providing a means for
data communication from the calling function to the called function.
Calling a function
 A function can be called by simply using the function name in a statement

63
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Function definition
 When the compiler encounters a function call, the control is transferred to the function
definition.
 All the statements ,in the called function, are together called as function definition
Function header
 The first line in the function definition is called function header.
Actual parameter
 All the variables inside the function call are called actual parameters.
Formal parameters
 All the variables inside the function header are called formal parameters
Program
#include<stdio.h>
#include<conio.h>
main ( )
{
int mul (int, int); function prototype
int a,b,c;
clrscr( );
printf (“enter 2 numbers”);
scanf(“%d %d”, &a, &b);
c = mul (a,b); function call
printf(“product =%d”,c); Actual parameters
getch ( );
}
int mul (int a, int b) Formal parameters
{ function header
int c;
c = a *b; Function definition
return c;
}
Output
Enter 2 numbers: 10 20
Product = 200

64
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Categories of functions:
 Depending on whether arguments are present (or) not and whether a value is returned (or)
not, functions are categorized into:
1) functions without arguments and without return values
2) functions without arguments and with return values
3) Functions with arguments and without return values
4) Functions with arguments and with return values.

1) functions without arguments and without return values

Calling function Analysis Called function


main ( ) No arguments are passed fun ( )
{ {
--- ----
--- No values are sent back ----
fun ( ); }
}

eg:
main ( )
{
void sum ( );
clrscr ( );
sum ( );
getch ( );
}
void sum ( )
{
int a,b,c;
printf(“enter 2 numbers”); Output
Enter 2 numbers
scanf (“%d%d”, &a, &b);
10 20
c = a+b;
Sum=30
printf(“sum = %d”,c);
}

65
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2) Functions without arguments and with return values

Calling function Analysis Called function


main ( ) No arguments are passed fun ( )
{ {
int c; ----
--- ----
c= fun ( ); return c;
values are sent back
-----
----- }
}
eg:
main ( )
{
int sum ( );
int c;
clrscr ( );
c= sum ( );
printf(“sum = %d”,c);
getch ( );
}
int sum ( )
{
int a,b,c;
printf(“enter 2 numbers”); Output
enter 2 numbers
scanf (“%d%d”, &a, &b);
10 20
c = a+b;
Sum = 30
return c;
}
3) Functions with arguments and without return values

Calling function Analysis Called function


main ( ) Arguments are passed fun ( int a, int b)
{ {
--- ----
--- No values are sent back ----
fun ( a,b ); }
---
---
}

66
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
eg:
main ( )
{
void sum (int, int );
int a,b;
clrscr ( );
printf(“enter 2 numbers”);
scanf(“%d%d”, &a,&b);
sum (a,b);
getch ( );
}
void sum ( int a, int b) Output
{ enter 2 numbers

int c; 10 20

c= a+b; sum = 30

printf (“sum=%d”, c);


}
4) Functions with arguments and with return values.

Calling function Analysis Called function


main ( ) Arguments are passed fun ( int a, int b)
{ {
int c; ----
--- ----
---
value are sent back
c= fun ( a,b ); return c;
--- }
---
}
eg:
main ( )
{
int sum ( int,int);
int a,b,c;
clrscr ( );
printf(“enter 2 numbers”);
scanf(“%d%d”, &a,&b);
c= sum (a,b);

67
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf (“sum=%d”, c);
getch ( );
}
int sum ( int a, int b )
Output
{ enter 2 numbers
int c; 10 20
c= a+b; Sum = 30
return c;
}
Scope
 “scope” of a variable determines the part of the program where it is visible
2 types
1. local scope 2. global scope
1. local scope
 Local scope specifies that variables defined within the block are visible only in that block and
invisible outside the block.
2. global scope
 Global scope specifies that variables defined outside the block are visible upto end of the
program.
eg:
int c= 30; /* global area */
main ( )
{
int a = 10;
printf (“a=%d, c=%d” a,c);
fun ( );
} Local function area
fun ( )
{
printf (“c=%d”,c);
}
output
a =10, c = 30
c = 30

68
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Storage classes
There are 4 storage classes (or) storage class specifiers supported in „C‟ They are:
1) auto
2) extern
3) static
4) register
1. automatic variables / Local variables.
 Keyword : auto
 These are also called local variables
 Scope
 Scope of a local variable is available within the block in which they are declared.
 These variables are declared inside a block
 Default value: garbage value
eg:
main ( )
{
auto int i=1;
{
auto int i=2;
{
auto int i=3; Output
printf (“%d”,i) 3
} 2
printf(“%d”, i); 1
}
printf(“%d”, i);
}
2. global Variables / external variables
 Keyword : extern
 These variables are declared outside the block and so they are also called global variables
 Scope:
Scope of a global variable is available throughout the program.
 Default value: zero

69
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
eg:
extern int i =1; /* this „i‟ is available throughout program */
main ( )
{
int i = 3; /* this „i' available only in main */
printf (“%d”, i);
fun ( );
} Output
3
fun ( )
1
{
printf (“%d”, i);
}
3) Static variables
 Keyword : static
 Scope
Scope of a static variable is that it retains its value throughout the program and in between
function calls.
 Static variables are initialized only once.
 Default value: zero
eg:
main ( ) main ( )
{ {
inc ( ); inc ( );
inc ( ); inc ( );
inc ( ); inc ( );
} }
inc ( ) inc ( )
{ {
static int i =1; auto int i=1;
printf (“%d”, i); printf (“%d”, i);
i++; i++;
} }
Output Output
1 2 3 1 1 1

4. Register variables
 Keyword : register

70
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 Register variable values are stored in CPU registers rather than in memory where
normal variables are stored.
 Registers are temporary storage units in CPU
 They allow faster access time for register variables than normal variables
eg:
main ( )
{
register int i;
for (i=1; i< =5; i++)
printf (”%d ”,i);
}
Output
1 2 3 4 5
Scope rules
 Scope rules relate to the accessibility, period of existence and boundary of usage of variables.
1) Scope rules related to statement Blocks :
 Block is set of statement enclosed in curly braces
 Variables declared in a block are accessible and usable within that block and doesnot exist
outside it
eg: main ( )
{
{
„i' is available within this
int i = 1;
block only
printf (“%d”,i);
}
{
int j=2; „j' is available within this

printf(“%d”,j); block only

}
}
output
1 2
 Even if the variables are redeclared in their respective blocks and with the same name, they
are considered differently

71
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
main ( )
{
{
/* Both i‟s are declared in different
int i = 1;
blocks so, they are treated differently
printf (“%d”,i);
even though they have same name */
}
{
int i =2;
printf (“%d”,i);
}
}
Output
1 2
 redeclaration of variables within the blocks bearing the same names as those in the outer
block masks the outer block variables while executing the inner blocks.
eg:
main ( )
{
int i = 1;
/* inner block variable dominates
{
outer block variable with same name
int i = 2;
*/
printf (“%d”,i);
}
}
Output : 2
 Variables declared outside the inner blocks are accessible to the nested blocks, provided these
variable are not declared within the inner block
main ( )
{
int i = 1;
/* „i‟ is available within the inner
{
block also */
int j = 2;
printf (“%d”,j);
printf (“%d”,i);

72
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
}
}
Output
2 1
2. Scope rules related to functions
 Function is a self contained block that performs a particular task.
 Variables declared within the function body are called local variables
 These variables only exist inside the specific function that creates them. They are unknown to
other functions and to the main functions also
 The existence of local variables ends when the function completes its specific task and
returns to the calling point.
eg:
main ( )
{
int a=10, b = 20;
printf (“before swapping a=%d, b=%d”, a,b);
swap (a,b);
printf (“after swapping a=%d, b=%d”, a,b);
}
swap (int a, int b)
{
int c;
c=a;
a=b;
b=c;
}
Output:
Before swapping a=10, b=20
After swapping a = 10, b=20

 Variables declared outside the function body are called global variables.
 These variables are accessible by any of the functions

73
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
eg:
include<stdio.h>
int a=10, b = 20;
main()
{
printf (“before swapping a=%d, b=%d”, a,b);
swap ( );
printf (“after swapping a=%d, b=%d”, a,b);
}
swap ( )
{
int c;
c=a;
a=b;
b=c;
}
Output
Before swapping a = 10, b =20
After swapping a = 20, b = 10
Type Qualifiers
Type qualifiers add special attributes to existing datatypes.

Type qualifiers

Const volatile restrict

1. Const
There are 3 types of constants
a) Literal constants
b) Defined constants
c) Memory constants
a) Literal constants
 unnamed constants are used to specify data
eg:
a=b+5 Here „5‟ is literal constant

74
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
b) defined constants
 They use preprocessor command „define” with #
Eg: #define PI 3.1415
c) Memory constants
 It uses „C‟ type qualifier „const‟ to indicate that the data cannot be changed
 Syntax: const type identifier = value
 eg:
const float pi = 3.1415
 it is simply giving a literal name.
Program
#define PI 3.1415
main ( )
{
const float cpi = 3.14
printf (“literal constant = %f”,3.14);
printf (“defined constant = %f”, PI);
printf (“memory constant = %f”,cpi);
}
Output
literal constant = 3.14
defined constant = 3.1415
memory constant = 3.14
2. volatile
 „volatile‟ type qualifier is used to tell the compiler that a variable is shared
 That is, a variable may be referenced and changed by other programs (or) entities if it is
declared as volatile
Eg: volatile int x;
3. restrict
 This is used only with pointers
 It indicates that the pointer is only the initial way to access the deferenced data
 It provides more help to the compiler for optimization.
Eg;
int *ptr
int a= 0;

75
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
ptr = &a;
____
____
____
*ptr+=4;
Cannot be replaced with
____
____ *ptr+=9
____
*ptr+=5;

 Here the compiler cannot replace the two statements *ptr+=4 and *ptr+=5 by one statement
*ptr+=9, because it does not know if the variable „a‟ can be accessed directly (or) through
other pointers.
 Same program fragment using „restrict‟ qualifier is as follows
Eg:
restrict int *ptr
int a= 0;
ptr = &a;
____
____
____
*ptr+=4;
Can be replaced with
____
____ *ptr+=9

*ptr+=5;
____
____

 Here the compiler can replace the 2 statements by one statement, *ptr+=9 because it is sure
that variable cannot be accessed through any other resources.
Recursive Functions
 “recursion” is the process of defining something in terms of it self.
 “recursive function” is a function that calls itself again in the body of the function
Eg:
 A function fact ( ), which computes the factorial of an integer „N‟ ,which is the product of all
whole numbers from 1 to N

76
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 When fact ( ) is called with an argument of 1 (or) 0, the function returns 1. otherwise, it
returns the product of n*fact (n-1), this happens until „n‟ equals 1.
Fact (5) =5* fact (4)
=5*4*3* fact (3)
=5*4*3*2* fact (2)
=5*4*3*2*1 fact (1)
=5*4*3*2*1
= 120.
main ( )
{
int n,f;
int fact (int);
clrscr ( );
printf (“enter a number”);
scanf (“%d”, &n);
f= fact (n);
printf (factorial value = %d”,f);
}
int fact (int n)
{
int f;
if ( ( n==1) || (n==0))
return 1;
else
f= n*fact (n-1);
return f;
}
Output
Enter a number 5
Factorial value = 120
Preprocessor commands
 „preprocessor‟ is a program that processes the source code before it passes through the
compiler
 It operates under the control of preprocessor directives which begin with the symbol #

77
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
3 types
1) Macro substitution directives
2) File inclusion directives
3) compiler control directives
1) Macro substitution directives
 It replaces every occurence of the identifier by a predefined string.
Syntax for defining a macro
# define identifier string
Eg: #define PI 3.1415
#define f(x) x *x
#undef PI
Program Program
#define wait getch( ) #define wait getch( )
main ( ) main ( )
{ {
clrscr ( ); #undef wait;
printf (“Hello”); clrscr ( );
wait ; printf (“Hello”);
} wait ;
Output: }
Hello Output
Error since wait is undefined before using it
2. File inclusion directives:
 An external file containing functions (or) macro definitions can be included using #include
directive
Syntax
# include <filename> (or) #include “filename”
Eg:
#include <stdio.h>
Output
main ( )
Hello
{
printf (“hello”);
}
The definition of the function printf ( ) is present in <stdio.h>header file.

78
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
3. Compiler control directives
 C pre processor offers a feature known as conditional compilation, which can be used to
switch ON (or) OFF a particular line (or) group of lines in a program.
Eg: #if, #else, #endif etc.
#define LINE 1
main ( )
{ Output
#ifdef LINE This is line number one
printf (”this is line number one”);
#else
printf(„This is line number two”);
#endif
}

ARRAYS
 Array: An array is a group of related data items that share a common name
(or) Homogenous collection of data items that share a common name.
 A particular value in an array is identified using its “index number” or “subscript”
Advantage
 The ability to use a single name to represent a collection of items and to refer to an item by
specifying the item number enables the user to develop concise and efficient programs
Declaring for declaring array
Syntax : for declaring array:

datatype array_name [size];

Eg:
1. float height [50]
This declares „height‟ to be an array containing 50 float elements
2. int group[10]
 This declares the „group‟ as an array to contain a maximum of 10 integer constants
 Individual elements are identified using “ array subscripts”
 While complete set of values are referred to as an array, individual values are called
“elements”

79
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Eg: To represent a set of 5 numbers by an array, it can be declared as follows
int a[5];
 Then computer reserves 5 storage locations each of 2 bytes.
a[0]
a[1]
a[2]
a[3]
a[4]

 First element is identified by subscript „zero‟ i.e., a[0] represents first element of the array.
 If there are „n‟ elements in array then subscripts range from 0 to n-1
Initialization
To store values into an array it can be done as follows.
a[0] = 10; 10 a[0]
a[1] = 20; 20 a[1]
a[2] = 30; 30 a[2]
a[3] = 40; 40 a[3]
a[4] = 50; 50 a[4]

An array can also be initialized at the time of declaration as follows


int a[5] = { 10,20,30,40,50};
Types of arrays
Arrays are broadly classified into 3 types. They are
1) one – dimensional arrays
2) two – dimensional arrays
3) Multi – dimensional arrays

1. one – dimensional arrays


Syntax: datatype array name [size];
Eg: int a[5];
Initialization;
An array can be initialized in 2 ways.
a) compile time initialization
b) Runtime initialization

80
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program for compile time initialization and sequential access using for loop
main ( ) storing
{ {
int a[5] = {10,20,30,40,50}; Int a=
a[0] 10
int i; 10, z;
clrscr ( ); a[1] 20
z= a++;
printf (“elements of the array are”); a[2] 30
printf
for ( i=0; i<5; i++) a[3] 40
(“z= %d”, z);
printf (“%d, a[i]); a[4] 50
printf
getch ( ); (“a=%d”, a);
} }accessing
Output: Elements of the array are
{
10 20 30 40 50
Int a=
Program for runtime initialization and sequential access using for loop
10, z;
main ( )
z= a++;
{
printf
int a[5],i;
(“z= %d”, z);
clrscr ( );
printf
printf (“enter 5 elements”);
(“a=%d”, a);
for ( i=0; i<5; i++)
} Storing / assigning values to element of an
scanf(”%d”, &a[i]);
array
printf(“elements of the array are”);
for (i=0; i<5; i++)
Accessing the elements of the aray
printf(”%d ”, a[i]);
getch ( );
}
output
enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50
Note :
 The output of compile time initialized program will not change during different runs of the
program
 The output of run time initialized program will change for different runs because user is given a
chance of accepting different values during execution.

81
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2. Two – dimensional arrays
 These are used in situations where a table of values have to be stored (or) in matrices
applications
 Syntax :
datatype array_ name [rowsize] [column size];
 Eg: int a[5] [5];
 No of elements in array = rowsize *columnsize = 5*5 = 25
Initialization :
Program for compile time initialization and sequential access using nested for loop
main ( )
{
int a[3][3] = {10,20,30,40,50,60,70,80,90}; a[0] [0] a[0] [1] a[0] [2]
int i,j; 10 20 30
clrscr ( );
a[1] [0] a[1] [1] a[1] [2]
printf (“elements of the array are”);
40 50 60
for ( i=0; i<3; i++)
a[2] [0] a[2] [1] a[2] [2]
{
70 80 90
for (j=0;j<3; j++)
{
printf(“%d \t”, a[i] [j]);
}
printf(“\n”);
}
getch ( );
}
output
elements of the array are:
10 20 30
40 50 60
70 80 90
Program for runtime initialization and sequential access using nested for loop
main ( )
{
int a[3][3] ,i,j;

82
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
clrscr ( );
printf (“enter elements of array”);
for ( i=0; i<3; i++)
{
for (j=0;j<3; j++)
{
scanf(“%d ”, &a[i] [j]); a[0] [0] a[0] [1] a[0] [2]
} 10 20 30
} a[1] [0] a[1] [1] a[1] [2]
printf(“elements of the array are”); 40 50 60
for ( i=0; i<3; i++) a[2] [0] a[2] [1] a[2] [2]
{ 70 80 90
for (j=0;j<3; j++)
{
printf(“%d\t ”, a[i] [j]);
}
printf(“\n”)
}
getch( );
}
output
Enter elements of array : 1 2 3 4 5 6 7 8 9
Elements of the array are
1 2 3
4 5 6
7 8 9
3. Multi –dimensional arrays
 „C‟ allows arrays of 3 (or) more dimensions
 The exact limit is determined by compiler
Syntax:
 datatype arrayname [size1] [size2] ----- [sizen];
 eg: for 3 – dimensional array:
int a[3] [3] [3];
 No of elements = 3*3*3 = 27 elements

83
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program
main ( )
{
int a[2][2] [2] = {1,2,3,4,5,6,7,8};
int i,j,k;
clrscr ( );
printf (“elements of the array are”);
for ( i=0; i<2; i++)
{
for (j=0;j<2; j++)
{
for (k=0;k<2; k++)
{
printf(“%d ”, a[i] [j] [k]);
}
}
}
getch( );
}
Output : Elements of the array are :
1 2 3 4 5 6 7 8

Arrays and functions


There are 2 ways of passing arrays as arguments to functions. They are
1) sending entire array as argument to function
2) sending individual elements as argument to function.

1. sending entire array as argument to function


 To send entire array as argument, just send the array name in the function call.
 To receive the entire array, an array must be declared in the function header..
Eg:
main ( )
{
void display (int a[5]);

84
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int a[5], i;
clrscr( );
printf (“enter 5 elements”);
for (i=0; i<5; i++)
scanf(“%d”, &a[i]);
Sending entire array „a‟ using array name
display (a);
getch( );
}
Receiving entire array
void display (int a[5])
{
int i;
printf (“elements of the array are”);
for (i=0; i<5; i++)
printf(„%d ”, a[i]);
}
Output
Enter 5 elements
10 20 30 40 50
Elements of the array are
10 20 30 40 50

2. sending individual elements as argument to function.


 If individual elements are to be passed as arguments then array elements along with their
subscripts must be given in function call
 To receive the elements, simple variables are used in function definition
main ( )
{
void display (int, int);
int a[5], i;
clrscr( );
printf (“enter 5 elements”);
for (i=0; i<5; i++)
scanf(“%d”, &a[i]);
display (a [0], a[4]);

85
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
getch( );
}
void display (int a, int b)
{
print f (“first element = %d”,a);
printf (“last element = %d”,b);
}
Output
Enter 5 elements
10 20 30 40 50
First element = 10
Last element = 50

86
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

87
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

POINTERS
Pointer : Pointer is a variable that stores the address of another variable.
Features of Pointers
 Pointer saves the memory space
 Execution time with pointer is faster because data is manipulated with the address i.e. direct
access to memory location
 The memory is accessed efficiently with the pointer i.e. dynamically memory is allocated and
deallocated
 Pointers are used with data structures
Pointer declaration, initialization and accessing.
Consider the following statement :
int qty = 179;
The representation of the variable in memory is as follows

qty Variable

179 value

5000 Address

Declaring a pointer

int *p;

It means „p‟ is a pointer variable that holds the address of another integer variable.
Initialization of a pointer
 Address operator (&) is used to initialize a pointer variable.
Eg: int qty = 175;
int *p; Variable value Address
qty 175 5000
p= &qty;
p 5000 5048

88
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Accessing a variable through its pointer
 To access the value of the variable, indirection operator (*) is used.
eg : int qty = 175, *p,n;

p = &qty;

n = *p;

„*‟ can be treated as value at address


 The 2 statements are equivalent to the following statement
p = &qty;
n = *p; n =qty
Program
main ( )
{
int x,y;
int *p;
clrscr ( );
x= 10;
p = &x;
y= *p;
printf (“Value of x = %d”, x);
printf (“x is stored at address %u”, &x);
printf (“Value of x using pointer = %d”, *p);
printf (“address of x using pointer = %u”, p);
printf (“value of x in y = %d”, y);
*p = 25;
printf (“now x = %d”, x)
getch ( );
x y
} 10 25 10
Output
p 5000
Value of x = 10
x is stored at address = 5000
Address of x using pointer = 10
Address of x using pointer = 5000

89
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Value of x in y = 10
Now x = 25
Arithmetic operations using pointers
Like any other variables, pointer variables can be used in expressions. For eg. If p1 and p2 are
properly declared and initialized then the following statements are valid
a) *p1 + *p2
b) *p1 - *p2
c) *p1 * *p2
d) *p1 / *p2 Note : There must be a blank space between / and * otherwise it is
treated as beginning of comment line
e ) p1 + 4
f) p2 - 2
g) p1 - p2 Note: returns the no. of elements in between p1 and p2 if both of them point to same array

h) p1++
i) – – p2
j) sum + = *p2
j) p1 > p2
k) p1 = = p2
l) p1 ! = p2 Note : Comparisons can be used meaningfully in handling arrays and strings

The following statements are invalid


a) p1 + p2
b) p1 * p2
c) p1 / p2
d) p1 / 3
Program
main ( )
{
int a,b,x,y,z;
int *p1, *p2;
a =12;
b = 4;
p1= &a;

90
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
a b x y
p2 = &b; 12 4 42 14
1234 5678
x = *p1 * * p2 – 6;
y= 4 - *p2 / *p1+10;
printf (“Address of a = %u”, p1); p1 1234 5678 p2
printf (“Address of b = %u”, p2);
printf (“a= %d b =%d”, a,b);
printf (“x= %d y =%d”, x,y);
}
Output
Address of a = 1234
Address of b = 5678
a = 12 b= 4
x = 42 y= 14
Pointers and arrays
 Continuous memory locations are allocated for all the elements of the array by the compiler
 The base address is the location of the first element (index 0) of the array.
Eg : int a [5] = {10, 20,30,40,50};
The five elements are stored as follows
Elements a[0] a[1] a[2] a[3] a[4]
Value 10 20 30 40 50
Address 1000 1002 1004 1006 1008

base address
a= &a[0]=1000
if „p‟ is declared as integer pointer, then the array „a‟ can be pointed by the following assignment

p = a;

(or) p = &a[0];

91
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 Every value of „a‟ can be accessed by using p++ to move from one element to another. When
a pointer is incremented, its value is increased by the size of the datatype that it points to.
This length is called the “scale factor”
 The relationship between „p‟ and „a‟ is shown below
P = &a[0] = 1000
P+1 = &a[1] = 1002
P+2 = &a[2] = 1004
P+3 = &a[3] = 1006
P+4 = &a[4] = 1008
 Address of an element is calculated using its index and the scale factor of the datatype.
For eg:

Address of a[3] = base address + (3* scale factor of int)


= 1000 + (3*2)
= 1000 +6
= 1006

 instead of using array indexing, pointers can be used to access array elements.
 *(p+3) gives the value of a[3]
a[i] = *(p+i)
Program
main ( )
{
int a[5];
int *p,i;
clrscr ( );
printf (”Enter 5 lements”);
for (i=0; i<5; i++)
scanf (“%d”, &a[i]);
p = &a[0];
printf (“Elements of the array are”);
for (i=0; i<5; i++)
printf(“%d”, *(p+i));
getch( );
}

92
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Output
Enter 5 elements : 10 20 30 40 50
Elements of the array are : 10 20 30 40 50
Pointers and two dimensional arrays :
 Memory allocation for a 2-dimensional array is as follows:
int a[3] [3] = {1,2,3,4,5,6,7,8,9};
a[0] [0] a[0] [1] a[0] [2] a[1] [0] a[1] [1] a[1] [2] a[2] [0] a[2] [1] a[2] [2]
1 2 3 4 5 6 7 8 9
1234 1236 1238 1240 1242 1244 1246 1248 1250
st nd rd
1 row 2 row 3 row
base address = 1234 = &a[0] [0]

int *p; Assigning base address to


p = &a[0] [0]; a pointer
(or) p =a

 Pointer is used to access the elements of 2 – dimensional array as follows

a[i] [j] = *(p+i*columnsize+j)

a[1] [2] = *(1234 + 1*3+2)


= *(1234 + 3+2)
= *(1234 + 5*2) Scale factor
= * (1234+10)
= *(1244)
a[1] [2] = 6
Program
main ( )
{
int a[3] [3], i,j;
int *p;
clrscr ( );
printf (“Enter elements of 2D array”);
for (i=0; i<3; i++)
{

93
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
for (j=0; j<3; j++)
{
scanf (“%d”, &a[i] [j]);
}
}
p = &a[0] [0];
printf (“elements of 2d array are”);
for (i=0; i<3; i++)
{
For (j=0; j<3; j++)
printf (”%d \t”, *(p+i*3+j));
}
printf (“\n”);
}
getch ( );
}
output
enter elements of 2D array
1 2 3 4 5 6 7 8 9
Elements of 2D array are
1 2 3
4 5 6
7 8 9
Array of pointers
 It is collection of addresses (or) collection of pointers
Declaration
datatype *pointername [size];
eg: int *p[5]; It represents an array of pointers that can hold 5 integer element addresses
p[0] p[1] p[2] p[3] p[4]

Initialization
„&‟ is used for initialization
Eg : int a[3] = {10,20,30};
int *p[3], i;

94
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
p[i] = a+i; a[0] a[1] a[2]
a 10 20 30
1234 1236 1238

p[0] p[1] p[2]


p
1234 1236 1238

Accessing
Indirection operator (*) is used for accessing
Eg: for (i=0, i<3; i++)
printf (”%d”, *p[i]);
Program
main ( )
{
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf (elements of the array are”)
for (i=0; i<3; i++)
printf (”%d \t”, *p[i]);
getch();
}
Output elements at the array are : 10 20 30
Pointer to pointer:
 Pointer to pointer is a variable that holds the address of another pointer
Declaration
datatype ** pointer_name;
Eg : int **p; p is a pointer to pointer
Initialization :
„&‟ is used for initialization

95
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Eg: int a = 10;
int *p; a
int **q; 10
p = &a; 1234
q =&p;
P
1234
5000

q
5000

Accessing :
 Indirection operator (*) is used for accessing
Program
main ( )
{
int a = 10;
int *p;
int **q;
p = &a;
q = &p;
printf(“a =%d”,a);
printf(“a value through pointer = %d”, *p);
printf(“a value through pointer to pointer = %d”, **q);
}
Output
a=10
a value through pointer = 10
a value through pointer to pointer = 10
Void pointers :
 It is a pointer that can hold the address of any datatype variable (or) can point to any datatype
variable
Declaration
void *pointername;

96
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
eg : void *vp;
Accessing
 Type cast operator is used for accessing the value of a variable through its pointer.
Syntax:
* ( (type cast) void pointer)
Eg :
int i=10;
void *vp;
vp = &i;
printf (“%d”, * ((int*) vp));
type cast
Program
main ( )
{
int i =10;
float f = 5.34;
void *vp;
clrscr ( );
vp = &i;
printf (“i = %d”, * ((int*)vp));
vp = &f;
printf ( “f = %f”, * ((float*) vp));
getch ( );
}
Output
i = 10
f = 5.34
Memory allocation functions
Memory can be allocated in 2 ways :
Memory
allocation

Static Dynamic
(at compile time) (at run time)

97
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 If memory is allocated at compile time, it cannot be changed during execution. There will be
a problem of either insufficiency or else wastage of memory.
 The solution is to create memory dynamically i.e. as per the requirement of the user during
execution of program.
 The standard library functions used for dynamic memory management are:
1) malloc ( )
2) calloc ( )
3) realloc ( )
4) free ( )
1) malloc ( );
 This function is used for allocating a block of memory in bytes at runtime.
 It returns a void pointer, which points to the base address of allocated memory
Syntax :
void *malloc (size in bytes)
Eg:
1) int *ptr;
ptr = (int * ) malloc (1000);
2) int *ptr;
ptr = (int * ) malloc (n * sizeof (int));
Note : if the memory is not free, it returns NULL
2) Calloc ( ):
 This function is used for allocating continuous blocks of memory at run time.
 This is especially designed for arrays
 It returns a void pointer which points to the base address of the allocated memory
Syntax : void *calloc ( numbers of elements, size in bytes)
Eg: 1) int *ptr;
ptr = (int * ) calloc (500,2);
Here, 500 blocks of memory each of size 2 bytes will be allocated continuously. Total memory
allocated = 1000 bytes.
2) int *ptr;
500 x 2
ptr = (int * ) calloc (n, sizeof (int));
= 1000
bytes
ptr

98
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
3. realloc ( ) :
 It is used for reallocating already allocated memory
 It can either reduce (or) extend the allocated memory
 It returns a void pointer that points to the base address of reallocated memory
Syntax
Free void *realloc (pointer, newsize);
Eg:
int *ptr;
ptr = (int * ) malloc (1000);
---
---
---
ptr = (int * ) realloc (ptr, 500);
---
---
ptr = (int * ) realloc (ptr, 1500);
4. free ( ):
 This function frees ( or) deallocates previously allocated memory space..
 With dynamic runtime allocation, it is our responsibility to release the space when it is not
required for effective usage of memory.
Syntax
free (pointer);
Eg: int *ptr;
ptr = (int *) malloc (1000);
---
---
---
free (ptr);
Pointers and functions;
pass by value: Here values are sent as arguments
void main()
{
void swap(int,int);
int a,b;
clrscr();
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping a=%d b=%d”,a,b);
99
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
swap(a,b);
printf(“after swapping a=%d, b=%d”,a,b);
getch();
}
void swap(int a,int b)
{
int t; all these statements is equivalent to
t=a; a = (a+b) – (b =a);
a=b; or
b=t; a = a + b;
} b = a – b;
a = a – b;
o/p:
enter 2 numbers 10 20
Before swapping a=10 b=20
After swapping a=10 b=20

pass by reference: Here addresses are sent as arguments


void main()
{
void swap(int *,int *);
int a,b;
clrscr();
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping a=%d b=%d”,a,b);
swap(&a, &b);
printf(“after swapping a=%d, b=%d”,a,b);
getch();
}

void swap(int *a,int *b)


{

100
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int t;
t=*a;
*a=*b; *a = (*a + *b) – (*b = * a);
*b=t;
}
o/p:
enter 2 numbers 10 20
Before swapping a=10 b=20
After swapping a=20 b=10

Pointer to functions:
 It holds the base address of function definition in memory
Declaration
 datatype (*pointername) ( );
 The name of the function itself specifies the base address of the function. So, initialization is
done using function name.
 Eg: int (*p) ( );
p = display; if display ( ) is a function that is defined.
Program for calling a function using pointer to function
Program
main ( )
main ( )
{
{
int (*p) ( );
clrscr ( );
clrscr ( );
display ( );
p = display;
getch( );
*(p) ( );
}
getch ( );
display ( )
}
{
display ( )
printf (“Hello”);
{
}
printf(“Hello”);
}
Output
Hello

101
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Command line arguments :
 An executable program that performs a specific task for operating system is called as
command
 These commands are issued from the prompt of operating system.
 Some arguments are to be associated with the commands and hence these are called
“ command” line arguments. They are
1) argc ----- argument count
2) argv ----- argument vector
argc : it contains the total number of arguments passed from command prompt
argv : it is a pointer to an array of character strings which contains names of arguments. Each word
is an argument
for eg :
c: |> sample. Exe hello how are you
arguments
Here, argc = 5
argv[0] = sample.exe argv[3] = are
argv[1] = hello argv[4] = you
argv [2] = how
Program
main ( int argc, char *argv[ ])
{
int i;
clrscr( );
printf (“ no. of arguments given at command prompt = %d”, argc);
printf (“ arguments given at command prompt are \n”);
for ( i = 1; i <argc; i++)
printf (”%s\n ”, argv[i]);
getch( );
}
Output
Steps:
1) compile the program
2) Run the program
3) Go to command prompt and give the input

102
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
c:|> sample.exe hello how are you.
No. of arguments given at command prompt is = 5
arguments given at command prompt are :
hello
How
Are
You

103
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

STRINGS
Strings basics:
String : array of characters (or) collection of characters is called a string
Declaration :
char stringname [size];
eg: char a[50]; string of length 50 characters
Initialization
a) using single character constant:
char a[10] = { „H‟, „e‟, „l‟, „l‟, „o‟ ,„\0‟}
„H‟ „e‟ „l‟ „l‟ „o‟ „\0‟
b) using string constants :
char a[10] = “Hello”:;
„H‟ „e‟ „l‟ „l‟ „o‟ „\0‟
„\0‟ is called null character.
It marks the end of the string
„\0‟ is automatically placed by the compiler if a string constant is given as input.
User must take care of placing „\0‟ at the end if single character constants are given.
Accessing:
 There is a control string “%s” used for accessing the string till it encounters „\0‟
Program
main ( )
{
char a[10] = “Hello”;
clrscr ( );
printf ( “ given string is %s”,a)
getch ( );
}
I/o functions
Output : Given string is Hello
Input and output for strings

Input Output

scanf ( ) printf ( )
gets ( ) puts ( )

104
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
program : using printf ( ) and scanf ( ) for reading & writing strings.
main ( )
{
char a[30];
printf(“enter your name”);
scanf ( “%s”,a);
printf (“your name is %s”,a);
getch ( );
}
Output
1. Enter your name : Ramu 2. Enter your name : Ram kumar
Your name is Ramu Your name is Ram
Note :
1. „&‟ is not used for accepting string because name of the string itself specifies the base
address of the string
2. space is not accepted as a character by scanf( )
3. „\0‟ is automatically placed by the compiler at the end.

Program : Using gets ( ) and puts ( ) for reading and writing strings.
main ( )
{
char a[30];
printf ( “enter your name”);
gets (a);
printf(“Your name is”);
puts (a);
}
Out put
1. Enter your Name : Ramu 2) Enter your name : Ram kumar
Your name is Ramu Your name is Ram kumar
Note : Space is also accepted as a character by gets ( )

105
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
String Library functions
 There are some predefined functions designed for handling strings which are available in the
library “string.h”
They are :
1) strlen ( ) 6. strcmp ( )
2) strcpy ( ) 7. strncmp ( )
3) strncpy ( ) 8. strrev ( )
4) strcat ( ) 9.strstr()
5) strncat ( )
1). strlen ( )
 This function gives the length of the string i.e. the number of characters in a string.
Syntax:
int strlen (string name)
program
#include <string.h>
main ( )
{
char a[30] = “Hello”;
int l;
l = strlen (a);
printf (“length of the string = %d”, l);
getch ( );
}
Output
length of the string = 5
Note : “\0” will not be counted as a character.
2). strcpy ( )
 This function is used for copying source string into destination string
 The length of the destination string must be greater than (or) equal to that of the source string
Syntax: strcpy (Destination string, Source String);
Eg:
1) char a[50]; 2) char a[50];
strcpy (“Hello”,a); strcpy ( a,”hello”);
o/p: error o/p: a= “Hello”

106
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
program
#include <string.h>
main ( ) a
{
H E l l O \0
char a[50], b[50];
clrscr ( ) b
H E l l O \0
printf (“enter a source string”);
scanf(“%s”, a);
strcpy ( b,a);
printf (“copied string = %s”,b);
getch ( );
}
Output
Enter a source string : Hello
Copied string = Hello
3) strncpy ( )
 This function is used for copying „n‟ characters of source string into destination string
 The length of the destination string must be greater than (or) equal to that of the source string
Syntax:
strncpy (Destination string, Source String, n);

program
#include <string.h>
main ( ) a
{
H E l l o \o
char a[50], b[50];
clrscr ( ) b
H E l \o
printf (“enter a string”);
gets (a);
strncpy (b,a,3);
b[3] = „\0‟;
printf (“copied string = %s”,b);
getch ( );
}

107
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Output
Enter a string : Hello
Copied string = Hel
s1
It is also used for extracting substrings; J a n 1 0 2 0 1 0 \0
Eg: char result[10], s1[15] = “Jan 10 2010”;
strncpy (result, &s1[4], 2);
result[2] = „\0‟ result
1 0 \o
o/p :Result = 10

4) strcat ( ):
 This is used for combining or concatenating two strings.
 The length of the destination string must be greater than the source string
 The resultant concatenated string will be in the source string.
Syntax:
strcat (Destination String, Source string);
program
#include <string.h>
main()
{
char a[50] = “Hello”;
char b[20] = “Good Morning”;
clrscr ( );
strcat (a,b);
printf(“concatenated string = %s”, a);
getch ( );
}
Output
Concatenated string = Hello Good Morning
5) strncat ( ):
 This is used for combining or concatenating n characters of one string into another.
 The length of the destination string must be greater than the source string
 The resultant concatenated string will be in the source string.

Syntax:
strncat (Destination String, Source string,n);
108
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
program
#include <string.h>
main ( )
{
char a [30] = “Hello”;
char b [20] = “Good Morning”;
clrscr ( );
strncat (a,b,4);
a [9] = „\0‟;
printf(“concatenated string = %s”, a);
getch ( );
}
Output
Concatenated string = Hello Good.
String comparison
6) strcmp
 This function compares 2 strings
 It returns the ASCII difference of the first two non – matching characters in both the strings.
Syntax
int strcmp (string1, string2);
If the difference is equal to zero string1 = string2
If the difference is positive string1> string2
If the difference is negative string1 <string2
eg:
1) char a[10]= “there”
char b[10] = “their” t h e r e \0

strcmp (a,b);
t h e i r \0
Output: string1 >string2
„r‟ > „i‟

2) char a[10]= “their”


char b[10] = “there” t h e i r \0

strcmp (a,b);
t h e r e \0

109
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Output: string1 <string2
„i‟< „r‟
3) char a[10]= “there”
char b[10] = “there” t h e r e \0

strcmp (a,b);
t h e r e \0
Output: string1 =string2

4) char a[10]= “there”


char b[10] = “the” t h e r e \0

strcmp (a,b)
t h e \0
Output: string1 >string2
„r‟ > „\0‟
5) char a[10]= “the”
char b[10] = “there” t h e \0

strcmp (a,b);
t h e r e \0
Output: string1 <string2
„\0‟ < „r‟
Program
main ( )
{
char a[50] b [50];
int d;
clrscr( );
printf (“enter 2 strings”);
scanf (“%s %s”, a,b);
d = strcmp (a,b);
if (d==0)
printf(“%s is equal to %s”, a,b);
else if (d>0)
printf(“%s is greater than %s”,a,b);
else if (d<0)

110
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf(“%s is less than %s”, a,b);
getch ( );
}
7. strncmp ( )
 This function is used for comparing first „n‟ characters of 2 strings
Syntax :
strncmp ( string1, string2, n)
Eg: char a[10] = “the”;
char b[10] = “there”
strncmp (a,b,3);
Output : Both strings are equal
8. strrev( )
 The function is used for reversing a string
 The reversed string will be stored in the same string
Syntax : strrev (string)
Program
main ( )
{
char a[50] ;
clrscr( );
printf (“enter a string”);
gets (a);
strrev (a);
printf(“reversed string = %s”,a)
getch ( );
}
Output : enter a string Hello
Reverse string = olleH
9.strstr():
 It is used to search whether a substring is present in the main string or not.
 It returns pointer to first occurrence of s2 in s1
Syntax : strstr(mainsring,substring);
Program
void main()
{

111
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
char a[30],b[30];
char *found;

clrscr();

printf("Enter a string:\t");
gets(a);

printf("Enter the string to be searched for:\t");


gets(b);

found=strstr(a,b);

if(found)
printf("%s is found in %s in %d position",a,b,found-a);
else
printf("-1 since the string is not found");
getch();
}

Output:

Enter a string: how are you


Enter the string to be searched for: you
you is found in 8 position

Arrays of pointers: (to strings)


 It is an array whose elements are pointers to the base address of the string
 It is declared and initialized as follows
char *a[ ] = {“one”, “two”, “three”};
Here, a[0] is a pointer to the base address of the string “one”
a[1] is a pointer to the base address of the string “two”
a[2] is a pointer to the base address of the string “three”

o n e \0 t w o \0 t h r e e \0

1234 1238 1242

a [0] 1234
a [1] 1238
a [2] 1242 Array of pointers

112
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Advantage :
 Unlink the two dimensional array of characters. In (array of strings), in array of pointers to
strings there is no fixed memory size for storage.
 The strings occupy only as many bytes as required hence, there is no wastage of space.
Program
main ( )
{
char *a[5] = {“one”, “two”, “three”, “four”, “five”};
int i;
clrscr ( );
printf ( “the strings are”)
for (i=0; i<5; i++)
printf (“%s”, a[i]);
getch ( );
}
Output
The strings are : one two three four five

Character operations
Character : it can be a character (A-Z(or) a- z);
digit (0-9), a white space, special symbol
Declaration
char a= „A‟; using a character constant.
Character input / ouput functions
input functions ouput functions
scanf ( )
printf ( )
getchar ( )
putchar ( )
getch ( )
putch ( )
getche ( )
eg: char a;
scanf(“%c”, &a); printf (“%c”, &a);
a = getchar ( ); putchar (a);
a = getch ( ); putch (a);

113
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Character analysis and conversion functions
 There are some predefined functions available in “ctype.h” library for analyzing the character
input and converting them.
Analysis functions
Function Checks whether entered character is
1. isalpha ( ) An alphabet (or) not
2. isdigit ( ) A digit (or) not
3. isspace ( ) A space, a newline (or) tab
4. ispunct ( ) A special symbol (or) not
5. islower ( ) A lower case letter of alphabet
6. isupper ( ) An upper case letter of alphabet
7. isalphanumeric( ) An alphabet/digit or not

Converting functions
Function
tolower ( ) Converts an upper case alphabet to lower case

toupper ( ) Converts a lower case alphabet to upper case

Program
#include <ctype.h>
main ( )
{
char a = „D‟;
clrscr ( );
if ( isalpha (a))
printf ( “%c is an alphabet”,a);
else
printf (“%c is not an alphabet”,a);
getch ( );
}
Output
D is an alphabet
String to number and number to string conversion
There are 2 functions available for conversion. They are:

114
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
1) sscanf( ) - used for converting string to number
2) sprintf ( ) - used for converting number to string
1) string to number converstion
 sscanf ( ) – takes a string as an input and converts it into numbers

Syntax:
sscanf (string name, “ control string”, variable list)
for eg: a 02 01 2010 - i/p
%s

day month year


02 01 2010 - o/p
%d %d %d
Program
main ( )
{
char a[20] = “02 01 2010”;
int day, mon, yr;
clrscr( );
sscanf (a, “%d%d %d”, &day, &mon, &yr);
printf ( “Day =%d”, day);
printf ( “Month = %d”, mon);
printf ( “Year = %d”, yr);
getch ( );
}
Output
Day = 02
Month = 01
Year = 2010
2. Number to string conversion
 sprintf( ) takes different numeric values as input and converts it into a single string

115
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Syntax :
sprintf ( string name, “control string”, variable list)
for eg: 02 01 2010 - - i/p

%d %d %d

02/01/2010 - o/p

%s
Program
main ( )
{
char a[50];
int day = 02, mon = 01, yr = 2010;
crlscr( );
sprintf (a, “%d/%d/%d”, day, mon, yr);
printf ( “today‟s date =%s”,a);
getch ( );
}
Output
Today‟s date is 02/01/2010.

116
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

117
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
STRUCTURES AND UNIONS
Introduction :
 Structure : It is a collection of different datatype variables, grouped together under a single
name. (or) It is heterogenous collection of data items that share a common name
Features of structure
1. It is possible to copy the contents of all structure elements of different datatypes to another
structure variable of its type using assignment operator
2. To handle complex datatypes, it is possible to create structure within another structure, which
is called nested structures.
3. It is possible to pass entire structure, individual elements of structure and address of structure
to a function
4. It is possible to create structure pointers
Declaration and initialization of structures.
General form of structure declaration
struct tagname
{
datatype member1;
datatype member2;
datatype member n;
};
Here, struct - keyword
tagname - specifies name of structure
member1, member2 - - specifies the data items that make up structure.
Eg:
struct book
{
int pages;
char author [30];
float price;
};

Structure variables
There are 3 ways of declaring structure variables

118
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
1) struct book
{
int pages;
char author[30];
float price;
}b;
2) struct
Note : Tagname can be ignored if the
{
variable is declared of the time of defining
int pages;
structure
char author[30];
float price;
}b;
3) struct book
{
int pages;
char author[30];
float price;
};
struct book b;
Initialization and accessing of structures
 The link between a member and a structure variable is established using member operator
(or) dot operator
 Initialization can be done in the following ways
1. struct book
{
int pages;
char author[30];
float price;
} b = {100, “balu”, 325.75};
2. struct book
{
int pages;
char author[30];
float price;

119
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
};
struct book b = {100, “balu”, 325.75};
3. using member operator
struct book
{
int pages;
char author[30];
float price;
};
struct book b;
b. pages = 100;
strcpy (b.author, “balu”);
b.price = 325.75;
4. using scanf ( )
struct book
{
int pages;
char author[30];
float price;
};
struct book b;
scanf (“%d”, &b.pages);
scanf (“%s”, b.author);
scanf (“%f”, &b. price);
main ( )
{
struct book b;
clrscr ( );
printf ( “enter no of pages, author, price of book”);
scanf (“%d%s%f”, &b.pages, b.author, &b.price);
printf(“ Details of book are”);
printf(“pages =%d, author = %s, price = %f”, b.pages, b.author, b.price);
getch();
}

120
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Structure within structure (or) Nested structures
 Creating a structure inside another structure is called nested structure
 Consider the following example
struct emp
{
int eno;
char ename[30];
float sal;
float da;
float hra;
float ea;
}e;
 This is structure defines eno, ename, sal and 3 kinds of allowances. All the items related to
allowances can be grouped together and declared under a sub – structure as shown below.
stuct emp
{
int eno;
char ename[30];
float sal;
struct allowance
{
float da;
float hra;
float ea;
}a;
}e;
 The inner most member in a nested structure can be accessed by changing all the concerned
structure variables (from outer most to inner most) with the member using dot operator
Eg :
e.eno; e.ename e.sal;
e.a.da; e.a.hra; e.a.ea;

Program
struct emp

121
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
int eno;
char ename[30];
float sal;
struct allowance
{
float da;
float hra;
float ea;
}a;
}e;
main ( )
{
clrscr ( );
printf(“enter eno, ename, salary”);
scanf (“%d%s%f”, &e.eno, e.ename, &e.sal);
printf (“enter da, hra, ea, values”);
scanf (“%f%f%f‟‟, &e.a.da, &e.a.hra, &e.a.ea);
printf(“employee details are”)
printf (“number = %d”, e.eno);
printf (“name = %s”, e.ename);
printf(“salary = %f”, e.sal);
printf(“Dearness Allowance = %f”, e.a.da);
printf (“House Rent Allowance = %f”, e.a.hra);
printf(“City Allowance = %f”, e.a.ea);
getch ( )
}
Array of structures:
 The most common use of structure is array of structures
 To declare an array of structures, first the structure must be defined and then an array variable
of that type.
Eg: struct book b[10]; 10 elements in an array of structures of type „book‟
Program for accepting and printing details of 10 students

122
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
struct student
{
int sno;
char sname[30];
float marks;
};
main ( )
{
struct student s[10];
int i;
clrscr ( );
for (i=0; i<10; i++)
{
printf(“enter details of students%d”, i+1);
scanf (“%d%s%f”, & s[i]. sno, s[i]. sname, &s[i].marks);
}
for (i=0; i<10; i++)
{
printf (“the details of student %d are”, i+1);
printf (“Number = %d”, s[i]. sno);
printf (“name = %s”, s[i]. sname);
printf (“marks =%f”, s[i]. marks);
}
getch ( );
}
Pointer to structure:
 It holds the address of the entire structure .
 Mainly these are used to create complex data structures such as linked lists, trees, graphs and
so on.
 The members of the structure can be accessed using a special operator called arrow operator
( ).
Declaration
struct tagname *ptr;
eg; struct student *s;

123
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Accessing ;
ptr membername;
eg: ssno, ssname, smarks;
struct student
{
int sno;
char sname[30];
float marks;
};
main ( )
{
struct student s;
struct student *st;
clrscr ( );
printf(“enter sno, sname, marks”);
scanf (“%d%s%f”, & s.sno, s.sname, &s. marks);
st = &s;
printf (“details of the student are”);
printf (“Number = %d”, st sno);
printf (“name = %s”, stsname);
printf (“marks =%f”, st marks);
getch ( );
}
Structure and functions
 There are 3 ways by which the values of structure can be transferred from one function to
another.
1) passing individual members as arguments to function
 Each member is passed as an argument in the function call.
 They are collected independently in ordinary variables in function header.
Eg:
struct date
{
int day;
int mon;

124
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int yr;
};
main ( )
{
struct date d= {02,01,2010};
clrscr ( );
display (d.day, d.mon, d.yr);
getch ( );
}
display (int a, int b, int c)
{
printf(“day = %d”, a);
printf(“month = %d”,b);
printf(“year = %d”,c);
}
2. Passing entire structure as an argument to function
 Name of the structure variable is given as argument in function call
 It is collected in another structure variable in function header
Disadvantage : A copy of the entire structure is created again wasting memory
Program
struct date
{
int day;
int mon;
int yr;
};
main ( )
{
struct date d= {02,01,2010};
display (d);
getch ( );
}

display (struct date dt)

125
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
printf(“day = %d”, dt.day);
printf(“month = %d”,dt.mon);
printf(“Year = %d”,dt.yr);
}
3. Passing the address of structure as an argument to function
 The Address of the structure is passed as an argument to the function
 It is collected in a pointer to structure in function header
Advantages:
1. No wastage of memory as there is no need of creating a copy again
2. No need of returning the values back as the function can access indirectly the entire structure
and work on it.
Program
struct date
{
int day;
int mon;
int yr;
};
main ( )
{
struct date d= {02,01,2010};
display (&d);
getch ( );
}
display (struct date *dt)
{
printf(“day = %d”, dtday);
printf(“month = %d”,dtmon);
printf(“Year = %d”,dt yr);
}

126
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Union
Def : A union is a memory location that is shared by several variables of different data types.
Syntax:
union uniontag
{
datatype member 1;
datatype member 2;
----
----
datatype member n;
};
Eg:
union sample
{
int a;
float b;
char c;
};
Declaration of union variable
1) union sample
{
int a;
float b; 4bytes
char c; s
}s;
a
2) union b
{ c
int a;
float b;
char c;
}s;
3) union sample
{
int a;

127
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
float b;
char c;
};
union sample s;

 when a union is declared, the compiler automatically creates a variable large enough to hold
the largest variable type in the union.
 At any time only one variable can be referred.

Initialization and accessing


 To access a union member, the same syntax as that of the structure is used
 The dot operator is used for accessing members normally
 The arrow operator ( ) is used for accessing the members using pointer
program
union sample
{
int a;
float b;
char c;
}
main ( )
{
union sample s = {10, 20.5, „A‟};
clrscr( );
printf(“a=%d”,s.a);
printf(“b=%f”,s.b);
printf(“c=%c”,s.c);
getch ( );
}
Output
a = garbage value Only the variable that is stored at last will
b = garbage value retain its value

c=A

128
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Differences between structures and Unions
Structure Union
1. Definition 1. Definition
Structure is heterogenous collection of data items A union is a memory location that is shared by
grouped together under a single name several variables of different datatypes.

2. syntax; 2. syntax;
struct tagname union tagname
{ {
datatype member1; datatype member1;
datatype member2; datatype member2;
----- -----
----- -----
----- -----
}; };
3. Eg: 3. Eg:
struct sample union sample
{ {
int a; int a;
float b; float b;
char c; char c;
}; };
4. Keyword : struct 4. Keyword : union
5. Memory allocation 5. Memory allocation
a 2 bytes
4 bytes
b 4 bytes
1 byte
a
c
b
7 bytes
c
6. Memory allocated is the sum of sizes of all the 6. Memory allocated is the maximum size
datatypes in structure
allocated among all the datatypes in union
(Here, 7bytes)
(Here, 4bytes)

7. Memory is allocated for all the members of the 7. Only one member will be residing in the
structure differently memory at any particular instance
Union of structures
 A structure can be nested inside a union and it is called union of structures
 It is also possible to create a union inside a structure
Program
struct x
{
int a;
float b;

129
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
};
union z
{
struct x s;
};
main ( )
{
union z u;
clrscr ( );
u.s.a = 10;
u.s.b = 30.5;
printf(“a=%d”, u.s.a);
printf(“b=%f”, u.s.b);
getch ( );
}
Output
a= 10
b = 30.5
Typedef ;
 „C‟ allows to define new datatype names using the „typedef‟ keyword
 Using „typedef‟, user will not actually create a new datatype but define a new name for an
existing type.
Syntax :
typedef datatype newname;
eg :
typedef int num; int a;
num a;
 This statement tells the compiler to recognize „num‟ as another name for „int‟.
 „num‟ is used to create another variable „a‟ .
 „num a‟declares „a‟ as a variable of type „int‟.
Program
main ( )
{
typedef int hours;

130
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
hours h;
clrscr ( );
printf(“enter hours”);
scanf (“%d”, &h);
printf(“Minutes =%d”, h*60);
printf(“Seconds = %d”, h*60*60);
getch ( );
}
Output : Enter hours =1
Minutes = 60
Seconds = 360
Example for typedefining a structure
typedef employee
{
int eno;
char ename[30];
float sal;
} emp;
main ( )
{
emp e = {10, “ramu”, 5000};
clrscr( );
printf(“number = %d”, e.eno);
printf(“name = %d”, e.ename);
printf(“salary = %d”, e.sal);
getch ( );
}
Bit Fields
 These are used to change the order of allocation of memory from bytes to bits
 A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length
 There are occasions where data items require much less than 16 bits of space. In such cases
memory will be wasted. Bit fields can pack several data items in a word of memory
Syntax
datatype name : bit – length;

131
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 The datatype can be either int (or) unsigned int (or) signed int.
 Bit length specifies the number of bits
 The largest value that can be stored is 2n – 1, where „n‟ is bit length
NOTE :
1) Bit fields cannot be arrayed
2) scanf ( ) cannot be used to read values into bit fields
3) cannot use pointer to access the bit fields
4) Bit fields should be assigned values within the range of their size
Bit Length Range of values
1 0 to 1
2 0 to 3 (22-1)
3 0 to 7 (23-1)
n 0 to 2n-1
Eg:
1) struct pack
{
int count;
unsigned a : 2;
unsigned b : 3;
};
Here, count will be in 2 bytes. „a‟ and „b‟ will be packed into next 1 byte
2) struct pack
{
unsigned a : 2;
int count;
unsigned b : 3;
};
Here, „a‟ will be in 1 byte, „count‟ in 2 bytes and „b‟ in 1 bytes.
Note ;
1. Bit Fields are packed into words as they appear in the definition
2. All unsigned bit fields must be placed in order for effectively using the memory

Program
struct vehicle
{
132
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
unsigned type : 3; Note: Instead of 6 bytes only 1 byte of memory
unsigned fuel : 2; will be allocated
unsigned model : 3;
};
main ( )
{
struct vehicle v;
v.type = 4;
v. fuel = 2;
v. model = 5;
printf (“type of vehicle =%d”, v.type);
printf (“fuel =%d”, v.fuel);
printf (“model =%d”, v.model);
}
Enumerated Data type
 These are used by the programmers to create their own data types and define what values the
variables of these datatypes can hold.
Keyword : enum
Syntax :
enum tagname
{
identifier1, identifier2,…….,identifier n
};
eg :
enum week
{
mon,tue, wed, thu, fri, sat, sun
};
 Here, with identifier values are constant unsigned integers and start from 0.
 Mon refers 0, tue refers 1 and so on.

Program :
main ( )
{

133
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
enum week {mon, tue, wed, thu, fri, sat, sun};
clrscr ( );
printf (“Monday = %d”, mon);
printf (“Thursday = %d”, thu);
printf (“Sunday = %d”, sun);
}
Output : Monday = 0
Thursday =3
Sunday =6

 enum identifiers can also be assigned initial value.


Program
main ( )
{
enum week {mon=1, tue, wed, thu, fri, sat, sun};
clrscr ( );
printf (“Monday = %d”, mon);
printf (“Thursday = %d”, thu);
printf (“Sunday = %d”, sun);
}
Output : Monday = 1
Thursday =4
Sunday =7

134
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

135
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

FILES
Definition :It is collection of records (or) It is a place on hard disk where data is stored permanently.
Types of Files: (1)Text file
(2)Binary File
1. Text File : It contains alphabets and numbers which are easily understood by human beings.
2. Binary file : It contains 1‟s and 0‟s which are easily understood by computers.
 Based on the data that is accessed, files are classified in to
(1) Sequential files
(2) Random access files
(1) Sequential files: Data is stored and retained in a sequential manner.
(2) Random access Files : Data is stored and retrieved in a random way.
Operations on files : 1. Naming the file
2. Opening the file
3. Reading from the file
4. Writing into the file
5. Closing the file
Syntax for opening and naming file.
1) FILE *File pointer;
Eg : FILE * fp;
2) File pointer = fopen (“File name”, “mode”);
Eg : fp = fopen (“sample.txt”, “w”);

FILE *fp;
fp = fopen (“sample.txt”, “w”);
Modes of the opening the file :
r - File is opened for reading
w - File is opened for writing
a - File is opened for appending (adding)
r+ - File is opened for both reading & writing
w+ - File is opened for both writing & reading
a+ - File is opened for appending & reading
rt - text file is opened for reading
wt - text file is opened for writing
at - text file is opened for appending

136
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
r+t - text file is opened for reading & writing
w+t - text file is opened for both writing & reading
a+t - text file is opened for both appending & reading
rb - binary file is opened for reading
wb - binary file is opened for writing
ab - binary file is opened for appending
r+b - binary file is opened for both reading & writing
w+b - binary file is opened for both writing & reading
a+b - binary file is opened for both appending & reading.
1) Write mode of opening the file
FILE *fp;
fp =fopen (“sample.txt”, “w”);
a) If the file does not exist then a new file will be created
b) If the file exists then old content gets erased & current content will be stored.
2. Read mode of opening the file:
FILE *fp
fp =fopen (“sample.txt”, “r”);
a) If the file does not exists, then fopen function returns NULL value.
b) If the file exists then data is read from the file successfullly
3. Append mode of opening a file
FILE *fp;
fp =fopen (“sample.txt”, “a”);
a) If the file doesn‟t exists, then a new file will be created.
b) If the file exists, the current content will be appended to the old content
Mode Exist Not exist
r Read fp = “NULL”
Current New file will be created
w
content

New file will be created


a Old content
Current content

137
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
I/O STREAMS:
Stream : flow of data
scanf( )
Keyboard Input stream „C‟
Program
Monitor Output stream

printf ( )
I/0 functions:
1) high level I/o
 These are easily understood by human beings
 Advantage: portability.
2) Low level I/o
 These are easily understood by computer
 Advantages. Execution time is less
 Disadvantage: Non protability
High level I/o Functions
1) fprintf ( ) - to write data into a file
2) fscanf ( ) - To read data from a file
3) putc ( )/ fputc() - to write a character into a file
4) getc ( ) /fgetc() - to read a character from a file
5) putw ( ) - To write a number into a file
6) getw ( ) - To read number from a file
7) fputs ( ) - To write a string into a file
8) fgets ( ) - To read a string from a file
9)fread() - To read an entire record from a file
10)fwrite() - To write an entire record into a file

fprint ( ) & fscanf ( ) functions


1) fprint ( )
Syntax : fprintf (file pointer, “ control string”, variable list)
Eg: FILE *fp;
fprintf (fp, “%d%c”, a,b);

138
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2) fscanf ( )
Syntax : fscanf(file pointer, “control string”, & variable list);
Eg: FILE *fp;
fscanf (fp, “%d%c”, &a,&b);

Program for storing the details of an employee in a file and print the same

main ( )
{
FILE *fp;
int eno;
char ename [30];
float sal;
clrscr ( );
fp =fopen (“emp.txt”, “w”);
printf (“enter the details of eno, ename, sal”);
scanf (“%d%s%f”, &eno, ename, &sal);
fprintf (fp, “%d%s%f”, eno, ename, sal);
fclose (fp);
fp = fopen (“emp.txt”, “r”);
fscanf (fp, “%d%s%f”, &eno, ename, &sal);
printf (“employee no: = %d”, eno);
printf (“employee name = %s”, ename);
printf (“salary = %f”, sal);
fclose (fp);
getch( );
}
Program for storing the details of 60 employers in a file and print the same
main ( )
{
FILE *fp;
int eno, i;
char ename [80];
float sal;
clrscr ( );
fp = fopen (“emp1. txt”, “w”);

139
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
for (i=1; i<60; i++)
{
printf (“enter the eno, ename, sal of emp%d”, i);
scanf (“%d%s%f”, &eno, ename, &sal);
fprintf (fp, “%d %s %f”, eno, ename, sal);
}
fclose (fp);
fp = fopen (“emp1.txt”, “r”);
for (i=1; i<60; i++)
{
fscanf(fp, “%d %s %f”, &eno, ename, &sal);
printf (“details of employee %d are \n”, i);
printf (“eno = %d, ename = %s, sal = %f”, eno, ename, sal);
}
fclose (fp);
getch ( );
}

putc( ) and getc( ) functions:


1) putc ( ): It is used for writing a character into a file
Syntax :
putc (char ch, FILE *fp);
Eg : FILE *fp;
char ch;
putc(ch, fp);
2) get c ( ) : It is used to read a character from file
Syntax :
char getc (FILE *fp);
Eg: FILE *fp;
char ch;
ch = getc(fp);

140
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Keyboard getchar ( ) putc ( )


file
putchar ( )
Monitor getc ( )

Program :
main ( )
{
FILE *fp;
char ch;
clrscr ( );
fp = fopen (“characters.txt”, “w”);
printf (“enter text. press ctrl+z at the end”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp);
}
fclose (fp);
fp =open (“characters. txt”, “r”);
printf (“file content is \n”);
while ((ch = getc (fp))! = EOF)
{
putchar (ch);
}
fclose (fp);
getch ();
}
Output:
Enter text press ctrl+z at the end.
Hello how r u ^z
File Content is
Hello How r u
putw ( ) and getw ( ) functions:
1. putw( ) : It is used for writing a number into file.
Syntax: putw (int num, FILE *fp);
Eg: FILE *fp;

141
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int num;
putw(num, fp);
2. getw ( ): It is used for reading a number from a file
Syntax :
int getw (FILE *fp);
Eg : FILE *fp;
int num;
num = getw(fp);
File
Keyboard scanf (“%d”) putw ( )

Monitor printf (“%d”) getw ( )

Program for storing no‟s from 1 to 10 and print the same


main ( )
{
FILE *fp;
int i;
clrscr ( );
fp = fopen (“number. txt”, “w”);
for (i =1; i< = 10; i++)
{
putw (i, fp);
}
fclose (fp);
fp =fopen (“number. txt”, “r”);
printf (“file content is ”);
for (i =1; i< = 10; i++)
{
i= getw(fp);
printf (“%d”,i);
}
fclose (fp);
getch ( );
}

142
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program for copying the contents of one file into another file
main ( )
{
FILE *fp1, *fp2;
char ch;
clrscr ( );
fp1 = fopen (“file1.txt”, “w”);
printf (“enter text press ctrl+z at the end”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp1 =fopen (“file1. txt”, “r”);
fp2 =fopen (“file2. txt”, “w”);
while ((ch = getc (fp1))! = EOF)
{
putc(ch,fp2);
}
fclose (fp1);
fclose (fp2);
fp2 = fopen (“file2.txt”, “r”);
printf (“File2 contents are”);
while ((ch = getc(fp2))! = EOF)
putchar (ch);
fclose (fp2);
getch ();
}
Program for displaying the contents of a file
main ( )
{
FILE *fp;
char ch ;
clrscr ( );

143
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
fp = fopen (“file1.txt”,”r”);
if (fp = = NULL)
{
printf (“File does not exist”);
}
else
{
printf (“file content is”)
while ((ch = getc(fp))! = EOF)
putchar (ch);
}
fclose (fp);
getch ( );
}
Program to merge two files into a third file. (the contents of file1, file2 are placed in file3)
main ( )
{
FILE *fp1, *fp2, *fp3;
char ch;
clrscr ( );
fp1 = fopen (“file1.txt”, “w”);
printf (“enter text into file1”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp2 = fopen (“file2.txt”, “r”);
printf (“enter text into file2”);
while ((ch = getchar ( ))! = EOF)
putc(ch, fp2);
fclose (fp2);
fp1 =fopen (“file1. txt”, “r”);
fp2 =fopen (“file2. txt”, “r”);

144
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
fp3 =fopen (“file3. txt”, “w”);
while ((ch = getc (fp1))! = EOF)
putc(ch,fp3);
while ((ch = getc (fp2))! = EOF)
putc(ch,fp3);
fclose(fp1);
fclose (fp2);
fclose (fp3);
fp3 = fopen (“file3.tx”, “r”);
printf (“File3 contents is”);
while ((ch = getc(fp3))! = EOF)
purchar (ch);
fclose (fp3);
getch ();
}

fput c ( ) and fgetc ( ) functions :


1) fputc( ) : It is used for writing a character in to a file .
Syntax :
fputc (char ch, FILE *fp);
Eg : FILE *fp;
char ch;
fputc (ch.fp);
2. fgetc( ) : This is used for reading a character from a file
Syntax :
fputc (char ch, FILE *fp);
Eg : FILE *fp;
char ch;
ch = fgetc(fp);

fgets ( ) and fputs ( ) functions :


1) fgets ( ) : It is used for reading a string from a file
Syntax :
fgets (string variable, No. of characters, File pointer);

145
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Eg : FILE *fp;
char str [30];
fgets (str,30,fp);
2) fputs ( ) : It is used for writing a string into a file
Syntax :
fputs (string variable, file pointer);
Eg : FILE *fp;
char str[30];
fputs (str,fp);
File
Keyboard gets ( ) fputs ( )

puts ( )
Monitor fgets ( )

Program :
main ( )
{
FILE *fp;
char str [30];
int i,n;
clrscr ( );
printf (“enter no of strings”);
scanf (“%d”, & n);
fp = fopen („strings.txt”, “w”);
for (i=1; i<=n; i++)
{
printf (”enter string %d”,i);
gets (str);
fputs (str, fp);
}
fclose (fp);
fp = fopen (”strings.txt”, ”r”);
for (i=1; i<=n; i++)
{
fgets (str, 30, fp);

146
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf (”string %d =”, i);
puts (str);
}
fclose (fp);
getch ( );
}
fread ( ) and fwrite ( ) functions
1. fread ( ) : It is used for reading entire record at a time.
Syntax : fread( & structure variable, size of (structure variable), no of records, file pointer);
Eg : struct emp
{
int eno;
char ename [30];
float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);
2. fwrite ( ) : It is used for writing an entire record at a time.
Syntax : fwrite( & structure variable , size of structure variable, no of records, file pointer);
Eg : struct emp
{
int eno:
char ename [30];
float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);
program for storing the details of 60 students into a file and print the same using
fread ( ) and fwrite ( )
struct student
{
int sno;
char sname [30];
float marks;

147
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
};
main ( )
{
struct student s[60];
int i;
FILE *fp;
clrscr ( );
fp = fopen (“student1. txt”, “w”);
for (i=0; i<60; i++)
{
printf (“enter details of student %d”, i+1);
scanf (“%d%s%f”. &s[i].sno,s[i].sname, &s[i].marks);
fwrite (&s[i], sizeof (s[i]), 1, fp);
}
fclose (fp);
fp = fopen (“student1. txt”, “r”);
for (i=0; i<60; i++)
{
printf (“details of student %d are”, i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf(“student number = %d”, s[i]. sno.);
printf(“student name = %s”, s[i]. sname.);
printf(“marks = %f”, s[i]. marks);
}
fclose (fp)
getch( );
}
ERROR HANDLING IN FILES:-
 Some of the errors in files are
1. Trying to read beyond end of file
2. Device over flow
3. Trying to open an invalid file
4. Performing a invalid operation by opening a file in a different mode.

148
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Functions for error handling.
1) ferror ( )
2) perror ( )
3) feof ( )
1. ferror ( )
It is used for detecting an error while performing read / write operations.
Syntax :
int ferror (file pointer);
eg : FILE *fp;
if (ferror (fp))
printf (“error has occurred”);
it returns zero if success and a non- zero otherwise.
2. perror ( )
It is used for printing an error.
Syntax :
perror (string variable);
Eg : FILE *fp;
char str[30] = ”Error is”;
perror (str);
O/P : Error is : error 0

Program :
main ( )
{
FILE *fp;
char str[30] = “error is”;
int i = 20;
clrscr ( );
fp = fopen (“sample. txt”, “r”);
if (fp = = NULL)
{
printf (“file doesnot exist”);
}
else

149
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
fprintf (fp, “%d”, i);
if (ferror (fp))
{
perror (str);
printf (“error since file is opened for reading only”);
}
fclose (fp);
getch ( );
}
O/P: Error is : Error1 compiler generated.
Error since file is opened for reading by us.
3. feof ( )
It is used for checking whether end of the file has been reached (or) not.
Syntax :
int feof ( file pointer);
Eg : FILE *fp;
if (feof (fp))
printf (“reached end of the file”);
If returns a non zero if success and zero otherwise.
Program:
main ( )
{
FILE *fp;
int i,n;
clrscr ( );
fp = fopen (“number. txt”, “w”);
for (i=0; i<=100;i= i+10)
{
putw (i, fp);
}
fclose (fp);
fp = fopen (“number. txt”, “r”);
printf (“file content is”);

150
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
for (i=0; i<=100; i++)
{
n = getw (fp);
if (feof (fp))
{
printf (“reached end of file”);
break;
}
else
{
printf (“%d”, n);
}
}
fclose (fp);
getch ( );
}
Outpute : File content is
10 20 30 40 50
60 70 80 90 100
Reached end of the file.

Other file functions


Random accessing of files
1. ftell ( )
2. rewind ( )
3. fseek ( )
1. ftell ( ) : It returns the current postion of the file pointer
Syntax : int n = ftell (file pointer)
Eg : FILE *fp;
int n;
_____
_____
_____
n = ftell (fp);
Note : ftell ( ) is used for counting the no of characters entered into a file.

151
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2. rewind ( )
It makes the file pointer move to the beginning of the file.
Syntax: rewind (file pointer);
Eg : FILE *fp;
-----
-----
rewind (fp);
n = ftell (fp);
printf (“%d”, n);
o/p: 0 (always).
3. fseek ( )
It is used to make the file pointer point to a particular location in a file.
Syntax: fseek(file pointer,offset,position);
offset :
 The no of positions to be moved while reading or writing.
 If can be either negative (or) positive.
Positive - forward direction.
Negative – backward direction .
position :
 it can have 3 values.
0 – Beginning of the file
1 – Current position
2 – End of the file

Eg :
1. fseek (fp,0,2) - fp is moved 0 bytes forward from the end of the file.
2. fseek (fp, 0, 0) – fp is moved 0 bytes forward from beginning of the file
3. fseek (fp, m, 0) – fp is moved m bytes forward from the beginning of the file.
4. fseek (fp, -m, 2) – fp is moved m bytes backward from the end of the file.
Errors :
1. fseek (fp, -m, 0);
2. fseek(fp, +m, 2);
Write a program for printing some content in to the file and print the following ?
1. Number of characters entered into the file.
2. Reverse the characters entered into the file.

152
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
main ( )
{
FILE *fp;
char ch;
int n;
clrscr ( );
fp = fopen (“reverse. txt”, “w”);
printf (“enter text press ctrl+z of the end”);
while ((ch = getchar( ) ) ! EOF)
{
putc (ch, fp);
}
n = ftell (fp)
printf ( “No. of characters entered = %d”, n);
rewind (fp);
n = ftell (fp);
printf (“fp value after rewind = %d”,n);
fclose (fp);
fp = fopen (“reverse.txt”, “r”);
fseek (fp, -1, 2);
printf (“reversed content is”);
do
{
ch = getc (fp);
printf (“%c”, ch);
} while (!fseek (fp, -2, 1);
fclose (fp);
getch ( );
}
Output : Enter text press ctrl z at the end.
How are you ^z
No. of characters entered = 11
fp value after rewind =0
Reversed content is uoy era woh.

153
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Command line arguments
 Arguments given at command prompt.
 main ( ) takes 2 arguments.
1) int argc – argument count.
2) char *argv [ ] – argument vector.
Program :
main (int arg c, char * argv [])
{
int i;
clrscr ( );
printf (“no. of arguments = %d”, argc);
printf (“arguments given at cmd prompt are”);
for (i=0; i<argc; i++)
{
printf (“%s \t”, argv [i]);
}
getch ( );
}
Program : for reversing characters in a file given at command prompt
main ( int argc, char *argv [ ] )
{
FILE *fp;
char ch;
clrscr ( );
fp = fopen (argv[1], “w”);
printf (“enter text press ctrl+z at the end”);
while ((ch = getchar ( ))! = EOF)
putc (ch, fp);
fclose (fp);
fp = fopen (argv[1], “r”);
fseek ( fp, argv[2], 0);
do
{
ch = getc (fp);

154
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
putchar (ch);
} while (! fseek (fp, -2, 1));
fclose (fp);
getch ( );
}

155
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

156
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

157
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
SORTING AND SEARCHING
Sorting : It is the process of arranging elements either in ascending (or) descending order.
Types : C language provides 5 sorting techniques
1) Bubble sort (or) Exchange Sort
2) Selection sort
3) Insertion sort (or) Linear sort
4) Quick sort (or) Partition exchange sort
5) Merge Sort (or) External sort

1) Bubble sort
 It is the simplest sorting technique
 It is also called exchange sort
 Procedure:
1. compare the first element with the remaining elements in the list and exchange(swap) them if
they are not in order.
2. Repeat the same for other elements in the list until all the elements gets sorted
Consider the elements
30 50 40 10 20

0 1 2 3 4
10 30
30 50 40 10 20

1st pass : compare 1st element with remaining elements


a[0] > a[1] 30 >50 (F) no exchange
a[0] > a[2] 30 >40 (F) no exchange
a[0] > a[3] 30 >10 (T) exchange
a[0] > a[1] 10>20 (F) no exchange
10 50 40 30 20
2 Pass : Compare 2nd element with rem. elements
nd

0 1 2 3 4

20
30
40 50 40 30
10 50 40 30 20

158
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
a[1] > a[2] 50 >40 (T) exchange
a[1] > a[3] 40 >30 (T) exchange
a[1] > a[4] 30 >20 (T) exchange
10 20 50 40 30

3rd Pass : Compare 3rd element with remaining elements


0 1 2 3 4
30
40 50 40
10 20 50 40 30

a[2] > a[3] 50 >40 (T) exchange


a[2] > a[4] 40 >30 (T) exchange

10 20 30 50 40

4th Pass : Compare 4th element with remaining Elements


0 1 2 3 4
40 50
10 20 30 50 40

a[3] > a[4] 50 >40 (T) exchange


10 20 30 40 50

Note : if there are „n‟ elements in the list then (n-1) passes are required for getting the sorted list
of elements.

Procedure
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
if (a[i] > a[j])

159
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
t=a[i];
a[i] = a[j];
a[j] = t;
}
}
}
Program
main ( )
{
int a [50], i,j,n,t;
clrscr ( );
printf(“enter the No: of elements in the list”);
scanf(“%d”, &n);
printf(“enter the elements”);
for (i=0; i<n; i++)
{
scanf (“%d”, &a[i]);
}
printf(“Before bubble sorting the elements are”);
for (i=0; i<n; i++)
printf(“%d \t”, a[i]);
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
if (a[i] > a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}

160
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf (”after bubble sorting the elements are”)
for (i=0; i<n; i++)
printf(“%d\t”, a[i]);
getch ( );
}
O/p : Enter No : of elements in the list =5
Enter the elements 30,50,40,10,20
Before bubble sorting the elements are 30 50 40 10 20
After bubble sorting the elements are 10 20 30 40 50
2. Selection sorting
procedure :
1) Select the first smallest element among the list of elements and place it in the first position
2) repeat the same for remaining elements in the list until all the elements gets sorted
Eg: Consider the following list:
30 50 40 10 20

0 1 2 3 4
10 30
30 50 40 10 20
1st Pass:
Sm = a[0] = 30 Sm
a[1] < sm 50 <30 (F) 30
a[2] < sm 40 <30 (F) 20  exchange a[0] with sm value
a[3] < sm 10 <30 (T) 10
a[4] < sm 20<10 (F) 10
10 50 40 30 20
nd
2 pass

0 1 2 3 4

20 50
10 40 30
50 20

Sm = a[1] = 50 sm
a[2] < sm 40 <50 (T) 40
a[3] < sm 30 <40 (T) 30 exchange a[1] with sm value

161
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
a[4] < sm 20<30 (T) 20
10 20 40 30 50

3rd Pass:
30 40
10 20 40 30 50

Sm = a[2] = 40 Sm
a[3] < sm 30 <40 (T) 40
a[4] < sm 50<30 (F) 30 exchange a[2] with sm value
10 20 30 40 50
th
4 pass

10 20 30 40 50

Sm = a[3] = 40 Sm
a[4] < sm 50 <40 (F)  40 exchange a[3] with sm value
procedure
for (i=0; i<n-1; i++)
{
sm=i;
for (j=i+1; j<n; j++)
{
if (a[j] < a[sm])
sm=j;
}

t=a[i];
a[i] = a[sm];
a[sm] = t;
}
}

PROGRAM
main ( )
{
162
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int a [50], i,n,j,t,sm;
clrscr ( );
printf(“enter No: of elements in the list”);
scanf(“%d”, &n);
printf(“enter the elements”);
for (i=0; i<n; i++)
{
scanf (“%d”, &a[i]);
}
printf(“Before selection sorting the elements are”);
for (i=0; i<n; i++)
printf(“%d \t”, a[i]);
for (i=0; i<n-1; i++)
{ sm=i;
for (j=i+1; j<n; j++)
{
if (a[j] < a[sm])
sm = j;
}
t=a[i];
a[i]=a[sm];
a[sm]=t;
}
printf (”after selection sorting the elements are”)
for (i=0; i<n; i++)
printf(“%d\t”, a[i]);
getch ( );
}
3. Insertion sort (linear sort)
 It is based on playing of cards

procedure
1) select the 2nd element in the list and compare it with the previous element and place it in order
2) repeat the same for remaining elements in the list until all the elements gets sorted

163
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Drawback
 The major drawback of this method is that for a list of „n‟ elements the sorting technique
makes n+1 comparisions in the worst case
 But the method is stable and can be adopted for lists containing less number of elements

Eg: Consider the following elements:

30 50 40 10 20
num=a[1]
1st Pass: 50

30 50 40 10 20
a[1] < a[0] 50<30 (F) no shift

30 50 40 10 20

2nd pass num=a[2]


40
50
30 50 40 10 20

num < a[1] 40 < 50 (T)  shift


num < a[0] 40 < 30 (F)  No shift
30 40 50 10 20
rd
3 Pass:
num=a[3]
10

0 1 2 3 4
10 30 40 50
30 40 50 10 20

num = a[3] = 10
num < a[2] 10 <50 (T) Shift
num < a[1] 10 <40 (T) Shift
num < a[0] 10 <30 (T) Shift
10 30 40 50 20

164
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
4th pass
num=a[4]
20

0 1 2 3 4
20 30 40 50
10 30 40 50 20

0
num = a[4] = 20
num < a[3] 20 <50 (T) Shift
num < a[2] 20 <40 (T) Shift
num < a[1] 20 <30 (T) Shift
num < a[0] 20 <10 (F) No Shift

Procedure
for (i=0; i<n-1; i++)
{
num = a[i];
for (j=i-1; j>=0 && num<a[j]; j--)
{
a[j+1] = a[j];
}
a[j+1] = num;
}

Program
main ( )
{
int a [50], i,n,j,num;
clrscr ( );
printf(“enter No: of elements”);
scanf(“%d”, & n);
printf(“enter the elements”);
for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
printf(“Before insertion sorting the elements are”);

165
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
for (i=0; i<n; i++)
printf(“%d ”, a[i]);
for (i=1; i<n; i++)
{ num=a[i];
for (j=j-1; j>=0 && num<a[j];j--)
{
a[j+1] = a[j];
}
a[j+1] = num;
}
printf (”after insertion sorting elements are”)
for (i=0; i<n; i++)
printf(“%d\t”, a[i]);
getch ( );
}
4. Quick sort: (Partition exchange sort)
 It is the best sorting technique
 It uses divide and conquer policy
 It uses recursion
Procedure :
1) select the 1st element as the pivot element
2) Arrange the elements in such a way that all the elements to the left of pivot are less than pivot
and all the elements to the right of pivot are greater than pivot element
3) Apply the same procedure for left and right partitions
 The purpose of this method is to move pivot element in the correct position first.
 The method therefore reduces unnecessary interchanges and move an item a great distance in
one move.
The following are the steps for partitioning the array and keeping the pivot at correct place
1. Select first element of array A (or subarray) as pivot.
2. Initialize i and j to first and last elements of the array respectively.
3. Increment i, until A [i] > pivot; stop
4. Decrement j, until A [j] < pivot; stop
5. If i < j, Exchange A[i] and A [j]
6. Repeat steps 3, 4, and 5 until i > j, i.e., when i and j cross each other.

166
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
7. Exchange the pivot element with the element pointed to by j which is correct place for pivot.
Note that in step 5, the swapping keeps the larger element to the right and smaller element to
the left, relative to the pivot.
Program :
int a[50];
main ( )
{
int n,i, lb, ub;
void qsot (int a[50], int, int);
clrscr( );
printf(“enter the no: of elements”);
scanf (“%d”,&n);
printf(“enter the elements”);
for (i=0; i<n; i++)
scanf( “%d”, &a[i]);
printf(“Before quick sort the elements are”);
for (i=0; i<n; i++)
printf(“%d\t”, a[i]);
lb = 0;
ub = n-1;
qsort (a,lb,ub);
printf(“after quicksort the elements are”);
for (i=0; i<n; i++)
printf(“%d\t”, a[i]);
getch ( );
}
void qsort (int a[50], int lb, int ub)
{
int pivot, i,j,t,flag = 0;
if (lb<ub)
{
pivot = a[lb];
i = lb;
j = ub;

167
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
while (flag = = 0)
{
i++;
while (a[i] <pivot)
i++;
while (a[j] >pivot)
j- - ;
if (i<j)
{ swap a[i] and a[j]
t=a[i];
a[i] = a[j];
a[j] = t;
}
else
flag =1;
}
t = a[lb];
a[lb] = a[j]; swap a[i], pivot
a[j] = t;
qsort (a, lb, j-1);
qsort (a, j+1, ub);
}
}
5. MERGE SORT :
Sorting

Internal external
Sorting sorting

Eg: 1. Bubble sort Eg: 1) merge sort


2. Selection sort
3. insertion sort
4. Quick sort
 It is an external sorting technique
 It uses recursion

168
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Procedure :
 In merge sort there are 3 steps
1)Divide 2)conquer 3) Combine
 Divide the „n‟ elements into two sub sequences of „n/2‟ elements each
 Sort the two subsequences recursively using merge sort
 Merge the two sorted subsequences to produce the sorted array

Program :
int [50];
main ( )
{
int n,i low, high;
void msort (int a[50], int, int);
clrscr( );
printf(“enter the no: of elements”);
scanf (“%d”,&n”);
printf(“enter the elements”);
for (i=0; i<n; i++)
scanf( “%d”, &a[i]);
printf(“Before merge sort the elements are”);
for (i=0; i<n; i++)
printf(“%d\t”, a[i]);
low = 0;
high = n-1;
msort (a, low, high);
printf(“after merge sort the elements are”);
for (i=0; i<n; i++)
printf(“%d\t”, a[i]);
getch ( );
}
void msort (int a[50], int lb, int ub)
{
int mid;
void merge (int a[50], int low, int mid, int high);

169
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
if (low<high)
{
mid = (low + high)/2;
msort (a, low, mid);
msort (a, mid+1, high);
merge(a, low, mid, high);
}
}
void merge (int a[50], int low, int mid, int high)
{
int b[50], i,j,k;
i= low;
j = mid+1;
k = low;
while ((i<=mid) && (j<=high))
{
if(a[i] <a[j])
{
b[k] = a[i]
k++;
i++;
}
else
{
b[k] = a[j];
k++;
j++;
}
}
while (i < =mid)
{
b[k] = a[i];
k++;
i++;

170
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
}
while (j< =high)
{
b[k] = a[j];
k++;
j++;
}
for (i=0; k=high; i++)
a[i]=b[i];
}

Searching
 Finding a key element among list of elements
 If the given element is present in the list then the searching process is said to be successful
 If the given element is not present in the list then the searching process is said to be
unsuccessful

Types :
 C language provides two types of searching techniques. They are:
1) Linear search 2) Binary search
1) Linear Search
 Searching for the key element is done in a linear fashion
 It is the simplest searching technique
 It does not expect the list to be sorted.
 Limitation:
o It consumes more time and reduce the power of system

i/p : unsorted list of elements, key


o/p : success – if key is found
unsuccess – otherwise
eg: Key = 40
0 1 2 3 4
20 50 40 30 10

a[i] = = key

171
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
main ( )
{
int a[50], n, i, key, flag = 0;
clrscr( );
printf(“enter the no: of elements”);
scanf (“%d”,&n);
printf(“enter the elements”);
for (i=0; i<n; i++)
scanf( “%d”, &a[i]);
printf(“enter a key element”);
scanf (“%d”, &key)
for (i=0; i<n; i++)
{
if (a[i] = = key)
{
flag = 1;
break;
}
}
if (flag = = 1)
printf(“search is successful”);
else
printf(“search is unsuccessfull”);
getch ( );
}
2)Binary Search
 This method can be applied only to sorted list.
 The given list is divided into two equal parts.
 The given key is compared with the middle element of the list.
 3 situations may occur:
o If the middle element matches the key then the search will end successfully here
o If the middle element is greater than the key then the search will proceed in the
left partition

172
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
o If the middle element is lower than the key then the search will proceed int the
right partition.

i/p : unsorted list of elements, key 10 20 30 40 50


o/p : success – if key is found 0 1 2 3 4
unsuccess – otherwise low mid high
key = 20
0 1
mid = (low +high) /2 10 20

low high

20

Low high
Program :
main ( )
{
int a[50], n, i, key, flag = 0, low, mid, high;
clrscr( );
printf(“enter the no: of elements”);
scanf (“%d”,&n);
printf(“enter the elements”);
for (i=0; i<n; i++)
scanf( “%d”, &a[i]);
printf(“enter a key element”);
scanf (“%d”, &key);
low = 0;
high = n-1;
while (low< = high )
{
mid = (low + high) /2;
if (a[mid] = = key)
{
flag = 1;
break;
}

173
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
else
{
if (a[mid] > key)
high = mid -1;
else
low = mid+1;
}
}
if (flag = = 1)
printf (“search is successful”);
else
printf(“search is unsuccessful”);
getch ( );
}

Complexity of sorting techniques


Algorithm Worst Case Avg. case Best Case
Bubble sort O(n2) O(n2) O(n2)
Selection sort O(n2) O(n2) O(n2)
Insertion Sort O(n2) O(n2) O(n)
Quick sort O(n2) O(nlogn) O(nlogn)
Merge sort O(n logn) O(n logn) O(n logn)
Heap Sort O(n logn) O(n logn) O(n logn)

Complexity of searching techniques


Algorithm Worst Case Avg. case Best Case
Linear Search O(n) O(n) O(n)
Binary Search O(logn) O(logn) O(n)

174
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

175
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

DATA STRUCTURES
Data structure: It is collection of data organized in a structured way.
Data structure

Linear Non linear

1) Linear data structure


Data is organized in a linear fashion
Eg : arrays, structures, stacks, queues, linked lists
2) Non linear data structure.
Data is organized in a hierarchial way.
Eg : Trees, graphs, sets, tables

Stack :
 It is a linear data structure where data is inserted and removed only at one end.
 Representation
top

„top‟ will always point to the top most element in the stack
 Operations
1) Push – inserting an element into a stack
2) Pop – Deleting an element from a stack
LIFO – Last In First Out

4
3
2 Size = 5
1
0
1. Push (10) -1 top
4
3 top++
2 a [top] = 10
1
10 0  top

176
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2. Push (20)
4
3 top++
2 a [top] = 20
1 top
20
10 0

3. Push (30)
4
3 top++
2  top a [top] = 30
30
20 1
10 0

4. push (40)
5. push (50)
50 4  top
40 3
30 2
20 1
10 0
6. push (60)
stack over flow
7. pop ( )

4
40 Deleted element = 50
3  top
30 2 Item = a [top]
20 1
10 top --
0

8. pop() ,pop(),pop(), pop()


Deleted element = 40
Deleted element=30
Deleted element=20
Deleted element =10

9. Pop ( )
Stack under flow

177
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2 Conditions
1. stack over flow
Trying to insert an element into a full stack
2. stack under flow :
Trying to delete an element from an empty stack

Algorithms for Push ( ), Pop ( ) , Display ( )


Push ( )
1. Check for stack overflow
if (top = = n-1)
printf(“stack over flow”);
2.Otherwise, insert an element into the stack.
top ++
a[top] = item
Pop ( )
1. check for stack underflow
if ( top = = -1)
printf( “stack under flow”);
2. Otherwise, delete the element from the stack
item = a[top]
top --
Display ( )
1. if (top == -1)
printf (“stack is empty”);
2. Otherwise
for (i=0; i<top; i++)
printf (“%d”, a[i]);

Implementation of stack using arrays:


Program :
#include < stdio.h>
#include < conio.h>
int top = -1, n,a[100];

178
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
main ( )
{
int ch;
void pop ( );
void display ( );
clrscr ( );
printf (“enter the size of the stack”);
scanf (“%d”, &n);
printf(“stack implementation\n”);
printf (“1. push \n”);
printf (“2. Pop \n”);
printf (“3. exit \n”);
do
{
printf ( “enter ur choice”);
scanf (“%d”, &ch);
switch (ch)
{
case 1 : push ( );
display ( );
break;
case 2 : push ( );
display ( );
break;
case 3 : exit (
  
 while (ch>=1 | | ch<= 3);
getch ( );
}
void push ( )
{
int item;
if (top = = n-1)

179
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf ( “stack over flow”)
else
{
printf(“enter an element for insertion”)
scanf (“%d”, &item);
top ++;
a[top] = item;
}
}
void pop ( )
{
int item;
if (top = = -1);
printf ( “stack under flow”);
else
{
item = a[top];
top --;
printf(“deleted element = %d”, item);
}
}
void display ( )
{
int i;
if (top = = -1)
printf ( “stack is empty”);
else
{
printf(“contents of the stack are”);
for (i=0; i<top; i++)
printf (“%d \t”, a[i]);
}
}
Output : enter the size of the stack = 5 [given by user]

180
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Stack implementation
1. Push 2. Pop 3. exit
Enter ur choice : 1 [given by user]
Enter an element for insertion : 10
Contents of the stack : 10
Enter ur choice : 1
Enter an element for insertion : 2
Contents of the stack : 10 20
Enter ur choice : 2
Deleted element = 20
Contents of the stack are : 10
Enter ur choice : 2
Deleted element : 10
Contents of the stack are : stack is empty
Enter ur choice : 2
Stack underflow.
Enter ur choice : 1
Enter an element for insertion : 30
Contents of the stack are : 30
Enter ur choice : 3

QUEUE
It is a linear data structure where the insertion is done at rear end and the deletion is done at front end.

Front end Rear end


Order : FIFO – First In First Out
Operations :
1. Insert – inserting an element into a queue
2. delete – deleting an element from the queue
Conditions:
1) Queue over flow : Trying to insert an element into a full queue
2) Queue under flow : Trying to delete an element from an empty queue.

181
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Algorithms for insertion, deletion, display –
Insertion ( )
1. Check for queue overflow
if (r==n)
printf (“Queue overflow”)
2. Otherwise, insert on element in to the queue.
q[r] = item
r++
Deletion ( )
1. Check for Queue under flow
if (f==r)
printf (“Queue under flow”)
2. Otherwise delete an element from the queue
item = q[f]
f++

Display ( )
1. Check whether the queue is empty or not
if (f==r)
printf(“Queue is empty”)
2. Otherwise print all the elements from „f‟ to „r‟
for( i=f; i<r; i++)
printf (“%d”, q[i]);
Implementation of queue using arrays:
Program :
#include < stdio.h>
#include < conio.h>
int r = 0, f = 0, n, q[100];

main ( )
{
int ch;
void insert ( );
void del();

182
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
void display ( );
clrscr ( );
printf (“enter the size of the queue”);
scanf (“%d”, &n);
printf(“Queue implementation\n”);
printf (“1. Insert \n”);
printf (“2. Delete \n”);
printf (“3. exit \n”);
do
{
printf ( “enter ur choice”);
scanf (“%d”, &ch);
switch (ch)
{
case 1 : insert ( );
display ( );
break ( );
case 2 : del ( );
display ( );
break ( );
case 3 : exit (
  
 while (ch>=1 | | ch<=3);
getch ( );
}

void insert ( )
{
int item;
if (r= = n)
printf ( “Queue overflow”);
else
{
printf (“enter an element for insertion”);

183
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
scanf (“%d”, &item)
q[r] = item;
r++;
}
}
void del ( )
{
int item;
if(f==r)
printf (“Queue under flow”);
else
{
item = q[f];
f++;
printf (“deleted element = %d”, item);
}
}

void display ( )
{
int i;
if (f==r)
printf (“Queue is empty”);
else
{
printf (“elements of the queue are”);
for( i=f; i<r; i++)
printf (“%d \t”, q[i];
}
}
Application of stacks
1) Conversions of expressions
2) Evaluation of expressions

184
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Expression :
Legal combination of operands & operations.
Types :
1) infix expression : operator is in between the operands. Eg : A+B
2) Prefix expression : operator is before the operands. Eg : +AB
3) Postfix expression : Operator is after the operands Eg : AB+
Infix to postfix infix to prefix
A+ B*C A+ B*C
A+ BC * A+ *BC
ABC* + +A*BC
Convert A+B*C / D-E+F infix to postfix and prefix.
Infix to prefix infix to postfix
A +B*C / D-E+F A +B*C / D-E+F

A +*BC / D-E+F A +BC* / D-E+F

A + / *BCD -E+F A +BC*D /-E+F

+A /*BCD -E +F ABC *D /+ -E+F

-+A/*BCDE +F ABC *D/ +E- +F

+ - +A/*BCDEF ABC *D / +E –F+

Algorithm :
 Scan the input string from left to right
Step1 : If the input symbol is an operand print it on to the monitor
Step2 : If the input symbol is „(„ then push it on to the stack
Step3 : If the input the symbol is „)‟ pop out all the contents of the stack until you get „(„
Step4 : If the input symbol is an operator check with the priority of the operator on top of the stack
with the current input symbol.
b) If the top priority of top of the stack greater than or equal to the priority of the current
symbol, then pop out the content of the stack and put the current symbol in to the stack.
c) Otherwise push the operator on to the stack
Step5: If the input symbol is „\0‟ then pop the contents of the stack until it becomes empty

Conversion of infix to post fix using stacks:


Eg: (1) A+ (B*C)

185
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
i/p symbol Contents of the stack Output

A A

+ A

+
( A

(
+
B AB

+
* AB
*
(
+
C ABC
*
(
+
) ABC*

(
+
\0 ABC*+

2. A * B / (C-D) + E * (F-G)
i/p symbol Contents of the stack Output
A
A

* A

*
B AB

*
/ AB*

186
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

/
( AB*
(
/
C AB*C

(
/
_ AB*C
-
(
/

D AB*CD
-
(
/
) AB*CD-

/
+ AB*CD-/

+
E AB*CD-/E

+
* AB*CD-/E

*
+
( AB*CD-/E
(
*
+
F AB*CD-/EF
(
*
+
_ AB*CD-/EF
-
(
*
+

187
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
G AB*CD-/EFG
-
(
*
+
) AB*CD-/EFG-
*
+
\0 AB*CD-/EFG- * +

Program :
int top = -1, stack[100];
main ( )
{
int i;
char a[50], ch,x;
void push (char);
char pop( );
int priority (char);
clrscr ( );
printf(“enter an infix expression”);
gets (a);
for(i=0; a[i]! = „\0‟; i++)
{
ch = a[i];
if (ch>=‟a‟ && ch<=‟z‟)
printf(“%c”,ch );
else if (ch = = „(„ )
push (ch);
else if (ch==‟)‟ )
{
while ( (x=pop( ))! = „(„ )
printf (“%c”, x);
}
else

188
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
while (priority (stack[top]) > = priority (ch))
{
x = pop ( );
printf (“%c”, x);
}
push (ch);
}
}
while (top>=0)
{
x = pop ( );
printf (“%c”, x);
}
getch ( );
}
void push (char ch)
{
top++;
stack [top] = ch;
}
char pop ( )
{
char x ;
x = stack [top];
top--
return x;
}
int priority (char ch)
{
switch (ch)
{
case „/‟ :
case „*‟ : return 3;

189
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
case „+‟ :
case „-„ : return 2;
default : return 0;
}
}
Evaluation of postfix expression :
i/p symbol Contents of the stack Output
3 -

2 -

2
3
5 -
5
2
3
* -
5 10
2 Op2 = 5 3
3
Op1 = 2
2 * 5 = 10
+ -
10
3 Op2 = 10
13
Op1 = 3
3+10 = 13
\0 (Empty) 13
13

Evaluation of postfix expression :


Algorithm :
1. scan the input string from left to right
2. for each input symbol 
a) If it is a digit then push it on to the stack
b) if it is an operator then pop out the top most two contents from the stack and apply the operator on
them, push the result on to stack.
c) if the input symbol is „\0‟ empty the stack

190
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
i/p symbol Contents of the stack Output
-
3
3
5 -
5
3
* -
5
3 Op2 = 5 15
Op1 =3
3 * 5 = 15
4 -
4
15
/ -
4
15 Op2 = 4
3
Op1 = 15
15/4 = 3
2 -
2
3
- -
2
3 Op2 = 2
1
Op1 = 1
3- 2 = 1
\0 (Empty) 1
1

Program :
int top = -1, stack [100];
main ( )
{
char a[50], ch,x;
int i, op1, op2, res, x;
void push (int);
int pop( );
int eval (char, int, int);
clrscr ( );
printf(“enter a void postfix expression”);
gets (a);

191
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
for(i=0; a[i]! = „\0‟; i++)
{
ch = a[i];
if (ch>=‟0‟ && ch<=‟9‟)
push (ch – „0‟);
else
{
op2 = pop ( );
op1 = pop ( );
res = eval (ch, op1, op2);
push (res);
}
}
 x = pop ( );
printf(“evaluated value = %d”, x);
getch ( );
}
 void push (int n)
{
top++;
stack [top] = n;
}
 int pop ( )
{
int res ;
res = stack [top];
top--
return res;
}
 

int eval (char ch, int op1, int op2)


{
switch (ch)
{

192
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
case „+‟ : return (op1+op2);
case „-‟ : return (op1-op2);
case „*‟ : return (op1*op2);
case „/‟ : return (op1/op2);

}
}
O/p : enter a valid postfix expression
352 * +
Evaluated value = 13

LINKED LISTS
 Disadvantages of Arrays
1. Static memory allocation
2. Wastage of memory
3. insufficiency of memory
 Advantages of pointers
1. Dynamic memory allocation
2. Effective usage of memory
* Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly
Def : It is collection of nodes
Node : It has 2 parts
1. Data
2. Link
Representation of Data *Link

node
Representation of linked lists :

Node 1 Node 2 Node 3


10 20 30 Null

Types of Linked Lists :


1. Single / Singly linked lists
2. Double / Doubly linked lists
3. Circular single linked list
4. Circular double linked list

193
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
1)Single linked list :
Representation

Node 1 Node 2 Node 3


10 20 30 Null
 Node consists of 2 parts
Data Link
 The link field always point to the next node in the list
 The link field of the last node is null

2)Double linked list

Null 10 20 30 Null

 Node consists of 3 parts namely


Data part left link Right link
 The left link always points to the left node in the list and the right link always points to the
right node in the list.
 The left link of the first node and the right link of the last node must be Null

3)Circular single linked list

10 20 30

 Node consists of 2 parts


data part  link part
 link field always points to the next node in the list.
 The link part of the last node always points to the first node.

4. Circular double linked list :

Node 1 Node 2 Node 3

10 20 30

194
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
 Node consists of 3 parts
 data part  left link  Right link
 Left link always points to the left node in the list and the right link points to the right node
in the list.
 The left link of the first node points to last node & right link of the last node points to the
first node.
Single linked list :
Data Link
Creation of node :
struct node
{
int data; Self referential structure
struct node * link;
}
Self referential structure
A structure which refers to itself
A pointer to a structure is declared even before the completion of definition of the structure.

Creation of linked list :


struct node
{
int data;
struct node * link;
};
struct node1, node2, node3;
node1. data = 10
node2.data = 20
node3. data = 30
node1. link = node 2;
node2. link = node 3;
node3. link = NULL;

Creation of linked list using pointers


struct node
{

195
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int data;
struct node * link;
};
struct *node1, *node2, *node3;
node1 data = 10
node2data = 20
node3 data = 30
node1 link = node 2;
node2 link = node 3;
node3 link = NULL;

Operations on linked lists


1. Insertion 2. Deletion 3. Traversing
1. Insertion
Insert node 5 in between node 2 and node 3

Node 1 Node 2 Node 3 Node5


B-I 10 20 30 50 Null

Node 1 Node 2 Node 5 Node 3


A-I 10 20 50 30 Null

node 2 link = node 5;


node 5  link = node 3;
Insert node 5 at the beginning

Node 1 Node 2 Node 3


B-I 10 20 30

Node 5 Node 1 Node 2 Node 3


A-I 50 10 20 30 X

node 5 link = node1 ;

Insert node 5 at the end

Node -1 Node 2 Node 3


B-I 10 20 30 Null

196
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Node -1 Node 2 Node 3 Node 5


A-I 10 20 30 50 Null
node 3 link = node 5;
Insert node 5 at the end

Node 2 temp
B-I 10 20 30

Node 2 Node 5 temp


A-I 10 20 50 30 Null
temp = node 2 link;
node 2  link = node 5;
node 5  link = temp;
NOTE:
 We cannot insert node 5 before node 2 as the nodes are not named
 We can insert node 5 before 2 if its position is given

Deletion :
Delete node2

Node 1 Node 2 Node 3


B.D 10 20 30

Node 1 Node 3
A.D 10 30

node 1 link = node 3;


node 2  link = NULL;
free (node2);
Delete node1

Node 1 Node 2 Node 3


B.D 10 20 30

Node -2 Node 3
A.D 20 30
node 1 link = NULL;
free (node1);

197
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Delete node3

Node 1 Node 2 Node 3


B.D 10 20 30

Node 1 Node 2
A.D 10 20

node 2 link = NULLl;


free (node3);
Delete node after node1

Node 1 temp1 temp2


B.D 10 20 30

Node 1
A.D 10 30

temp 1 = node1 link;


temp2 = temp1 link;
node1 link = temp2;
temp1  link = NULL;
free (temp1);
(or)
Using only one temporary node
temp = node1 link;
node1 link = temp1 link
Temp1  link = NULL;
free (temp1);
3. Traversing

Start Start Start


10 20 30

o/p : 10 20 30

1) while (start link ! = NULL)


{

198
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf(“%d”, start data);
start= start link;
}
Or
2) do
{
printf(“%d”, start data);
start= start link ;
} while (start ! = NULL)

3) while (start ! = NULL)


{
printf(“%d”, start data);
start= start link;
}

Start Start Start Start


10 20 30 Null

Creation of a linked list dynamically

typedef struct list


{
int data;
struct list * link;
} node;
node * newnode;
printf( “enter an item”);
scanf(“%d”, &item);
while (item! = -999)
{
newnode = (node*) malloc (sizeof (node));
newnode  data = item;
newnode link = NULL;
if (start = = NULL)
{

199
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
start = newnode;
prev = newnode;
}
else
{
prev link = newnode;
prev = newnode;
}
printf(“enter an item”);
scanf (“%d”, &item);
}
Program for creation of linked list and display its content.
typedef struct list
{
int data;
struct list * link;
} node;
main ( )
{
node * start = NULL;
node *create (node *);
void display (node*);
clrscr ( );
printf (“Creation of linked list”);
start = create (start);
display (start);
getch ( );
}
node * create (node * start)
{
node * newnode, * prev;
int item;
printf (“enter an item ( type -999 at the end)”);
scanf(“%d”, &item);

200
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
while (item! = -999)
{
newnode = (node*) malloc (sizeof (node));
newnode  data = item;
newnode link = NULL;
if (start = = NULL)
{
start = newnode;
prev = newnode;
}
else
{
prev link = newnode;
prev = newnode;
}
printf(“enter an item .Type -999 at the end”);
scanf (“%d”, &item);
}
}
void display (node * start)
{
printf(“linked list is \n”)
printf (“START ”);
while (start! = NULL)
{
printf (“%d ” ,start data);
start = start  link;
}
printf (“NULL”);
}

O/P : Start 10 20 30 NULLl

201
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Insertion :

Start
10 20 30 40
&item : 50
& POS : 1

Start
50 10 20 30 40
if (pos = = 1 || start = = NULL)
{
newnode link = = start;
 start = new node;
}
Else POS : 2,3,4…..

Start Newnode temp


10 50 20 30 40
Else if(pos==2)
{
temp = start link;
start link = newnode; only for POS = 2
newnode link = temp;
}
Else
{ if POS = 4
Start
10 20 30 40
i = 2;
temp = start;
while ( i<pos) 50
{
temp = temp link;
i++;
}
newnode link = temp link
templink = newnode;
}

202
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Deletion
1. Deletion from empty list
2. 1st node deletion
3. Some other node deletion

Start
10 20 30 40
if (start = = NULL)
{
printf (“cannot delete. List is empty);
}
else if (start data = = item)
{
temp = start;
start = start link;
free(temp);
}
else
{
cur = start;
while (cur data! = item || cur ! = NULL)
{
prev = cur;
cur = cur link;
}
if (cur = = NULL)
{
printf(“item is not there in the list”)
}
printf(“Deleted item = %d”, cur data)
prev link = cur link;
free (cur);

Start prev Prev Cur


10 20 30 40


203
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program for single linked list :
typedef struct list
{
int data;
struct list * link;
} node;
main ( )
{
node * start = NULL;
int ch;
node *create (node *);
void display (node*);
node *insert (node *);
node *del (node *);
clrscr ( );
printf (“Creation of single linked list \n”)
start = create (start);
display (start);
printf(“menu \n”);
printf(“1. insert \n”);
printf(“2. delete \n”);
printf(“3. exit \n”);
do
{
printf(“enter ur choice \n”);
scanf( “%d”, &ch);
switch (ch)
{
case 1 : start = insert(start);
display (start);
break;
case 2 : start = del (start);
display (start);
break;

204
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
case 3 : exit (0);
}
} while (ch< = 3);
getch ( );
}
node* create ( node * start)
{
node * newnode, *prev;
int item;
printf (“enter an item. Type -999 at the end”);
scanf(“%d”, &item)
while (item! = -999)
{
newnode = (node*) malloc (sizeof (node));
newnode  data = item;
newnode link = NULL;
if (start = = NULL)
{
start = newnode;
prev = newnode;
}
else
{
prev link = newnode;
prev = newnode;
}
printf(“enter on item type -999 at the end”);
scanf (“%d”, &item);
}
}
node * insert (node * start)
{
node *newnode, *temp;
int item, pos, i;

205
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf(“enter an item for insertion \n”);
scanf (“%d” ,&item);
printf(“enter position of insertion”);
scanf (“%d” ,&pos);
newnode = (node*) malloc (sizeof(node));
newnode data = item;
newnode link = NULL;
if (pos = = 1 || start = = NULL)
{
newnode link = start;
start = newnode;
}
else
{
i = 2;
temp = start;
while ((i<pos) && (temp ! = NULL))
{
temp = temp link;
i++;
}
newnode link = temp link;
temp link = newnode;
}
return start;
}
node* del (node* start)
{
node *prev, *cur, *temp;
int item;
printf(“enter item to be deleted”);
scanf(“%d”, &item);
if (start = = NULL)
{

206
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf(“Cannot delete, since list is empty”);
}
else if (start data = = item)
{
temp = start;
start = start link;
free (temp);
}
else
{
cur = start;
while (cur data! = item) || cur! = NULL)
{
prev = cur;
cur = cur link;
}
if (cur == NULL)
{
printf(“deleted item = %d”, cur data);
prev link = cur link;
free (cur);
}
return start;
}

void display (node *start)


{
printf(“linked list is \n”);
printf(“START ”);
while (start! = NULL)
{
printf(“%d”, start data);
start = start link;

207
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
}
printf (“NULL”);
}

Stack using linked lists :
 Stack over flow and stack under flow can be avoided by allocating memory dynamically
Operations :
1. Push
2. Pop
1. Push
start
&item = 10 NULL
newnode = (node*) malloc (sizeof (node));
newnode data = item;
newnode link = NULL;
newnode link = start; start start
start = newnode; nn nn start
20 10 NULL

3 2
start start 1
POP nn nn start
if (start = = NULL) 20 10 NULL

printf(“Deletion is not possible.List is empty”)


else
{
temp = start;
start = start link;
free (temp);
}

Program
typedef struct list
{
int data;
struct list * link;
} node;

208
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
main ( )
{
node * start = NULL;
int ch;
node *push (node *);
node *pop (node *);
void display (node*);
clrscr ( );
printf(“menu”);
printf(“1. Push \n”);
printf(“2. Pop \n”);
printf(“3. exit \n”);
do
{
printf(“enter ur choice ”);
scanf( “%d”, &ch);
switch (ch)
{
case 1 : start = push(start);
display (start);
break;
case 2 : start = pop (start);
display (start);
break;
case 3 : exit (0);
}
} while (ch< = 3);
getch ( );
}
node* push ( node * start)
{
node * newnode;
int item;
printf (“enter an item for insertion”);

209
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
scanf(“%d”, &item);
newnode = (node*) malloc (sizeof (node));
newnode data = item;
newnode link = NULL;
newnode link = start;
 start = newnode;
return *start;
}
node* pop ( node * start)
{
node * temp;
if (start= = NULL)
{
printf(“Deletion is not possible, since stack is empty”);
}
else
{
printf(“Deleted item = “%d”, start data);
temp = start;
start = start link;
free (temp);
}
return start;
}
void display ( node * start)
{ printf( “stack is \n”);
printf(“ START ”);
while (start! = NULL)
{
printf(“%d”, start data);
start = startlink;
}
printf(“NULL”);
}

210
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Queue using linked list :
 Queue overflow and Queue under flow can be avoided by using linked list.

* Operations
Front Rear
1) insert Null NULL
2) Delete
f r r
* Order
nn nn nn
FIFO - Fist In First Out 10 20 30
1. Insertion
&item :
Newnode = (node*) mallac (sizeof (node));
newnode data = item;
newnode link = NULL;
if ((front = = NULL) || (rear = = NULL))
{
front= newnode;
rear = newnode;
}
else
{
rearlink = newnode;
  rear = newnode;
}

2. Deletion

10 20 30
Front rear

if ((front= = NULL))
printf(“Deletion is not possible, Queue is empty”);
else
{
temp = front;
front = front link;

211
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
free (temp);
}
3. Display
while (front! = NULL)
{
printf(“%d”, front data);
front = frontlink;
}
Program
typedef struct queue
{
int data;
struct queue * link;
} node;
main ( )
{
node * front = NULL, *rear = NULL;
int ch;
void insert (node**, node**);
node*del (node*);
void display (node*);
clrscr ( );
printf(“menu \n”);
printf(“1. insert \n”);
printf(“2. Delete \n”);
printf(“3. exit \n”);
do
{
printf(“enter ur choice ”);
scanf( “%d”, &ch);
switch (ch)
{
case 1 : insert (&front, &rear);
display (front);

212
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
break;
case 2 : del (front);
30
10 20
display (start);
break; F R
case 3 : exit (0);
}
} while (ch< = 3);
getch ( );
}
void insert (node** front, node ** rear) (since arguments are addresses ,pointers are used)
{
node * newnode;
int item;
printf(“enter an item for insertions”);
scanf(“%d”, &item);
newnode = (node*) mallac (sizeof (node));
newnode data = item;
newnode link = NULLl;
if (*front = = NULL || &rear = = NULL)
{
*front= newnode;
*rear = newnode;
}
else
{
*rearlink = newnode;
  *rear = newnode;
}
}
node* del ( node * start)
{
node * temp;
if (front= = NULL)
printf(“cannot delete. Since Queue is empty”);
else

213
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{
printf(“Deleted item = “%d”, front data);
temp = front;
front = front link;
free (temp);
}
return start;
}
void display ( node * front)
{
printf( “Queue using linked list is \n”);
printf(“ FRONT ”);
while (front! = NULL)
{
printf(“%d”, front data);
front = frontlink;
}
printf(“REAR”);
}

214
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

OBJECTIVE TYPE QUESTIONS


UNIT-I
1.Which of the following is not an input device
(a)plotter (b) scanner (c) keyboard (d) mouse

2.Which of the following is the correct order of operators for the evaluation for the expression
Z=x+y*z/4%2-1
(a) */%+-= (b) -%!+*= (c)/*%-+= (d) */%-+=

3 The parallelogram is used to represent ----- type of statements in flowcharts


(a) input/output (b) Functions (c)decision (d) processing

(4) Which of the following is not a translator program


(a)linker (b)assembler (c) interpreter (d) compiler

(5) Object code produced by which of the following phase


(a)preprocessing (b)linking (c) compilation (d)editing

(6)In flowchart ,decisions are represented by using __________ symbol


(a) diamond (b)circle (c) square (d)rectangle

(7)____________acts as an interface between the computer hardware and user of the computer
(a)o.s (b)hardware (c) software (d) none of the above

(8) The hardware along with the read-only software that resides on this hardware is combinely called
as ____________________

(9) The order of evaluation can be changed by using _______________ in an expression?

(10)Who is father of computer

(11)Computer is an ______________ device

BITS
1)A Computer consists of --- units.
a)3 b) 4 c) 5 d) 6
2)Keyboard is an example of ------ unit.
a) Memory b) Input c) Output d) ALU
3) ALU stands for -------
a) Arithmetic Logic Unit b) Arithmetic Lower Unit c) Add Logical Unit
d) None of the above
4) RAM is considered as a ----------
a) Volatile Memory b) Non volatile Memory c) Permanent
d) None of the above
5) ------ contains the a program during the manufacturing itself.
a) RAM b) ROM c) Both a and b d) None of the above

6) ------- unit is used to store information.


a) Input b) Output c) Control d) Memory

215
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
7) In Stored program concept ---- and --- are stored in the same memory.
a) Data and Instruction b) Data and Operands c) Instruction and operation code d) None
of the above

8) Microprocessor is the heart of ------ computer.


a) Digital b) Analog c) Both a and b d) None of the above

Answers: 1) c 2) b 3) a 4) a 5) b 6) d 7) a 8) a

9) ---- and ---- are examples of input device.

10) Printout of a program is considered as ------.

11). Payroll program stored on CD is considered as ----.

12) Dot matrix printer is an example of --------.

13). Laser printer is an example of -----.

14) The speed of Dot matrix printer is expressed as ----

15) The speed of Laser printer is expressed as ----

Answers:: 9)Keyboard, Mouse 10) Hardcopy 11)Softcopy 12)Impact printer


13)Non-impact 14)Characters per second (CPS) 15)Pages per Minute (PPM)

1. RAM is a --------memory.
2. Floppy disk storage capacity is -----.
3. Concentric circles in a floppy disk is known as -----
4. ROM is also known as -----.
5. ROM is a ----- memory.
6. Hard disk is ---- than primary memory.
7. CD-ROM storage capacity is ---- .
8. Information stored in a CD is accessed through ----
Answers
1. Volatile
2. 1.44 MB
3. tracks
4. firmware
5. Nonvolatile
6. Bigger
7. 700 MB
8. light

216
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

1. Machine language is expressed in terms of ----------------------.


2. Assembly language is written with the help of ------------------
3. High level language is similar to ------------------------
4. Compiler converts ---------------- language into --------------------- language.
5. Assembler converts ---------------- language into ------------------ language.
6. Interpreter converts high level language into machine language ---- by ----.
7. edit is an example of -------------------.-
8. Ms-word is an example of --------------------
9. To display files in the MS-DOS , ------------------------- command is used.

Answers :
1)0 and 1. 2) Mnemonics 3) English 4)High, machine 5) Assembly , machine
6) line , line 7) editor 8) word processor 9)DIR

217
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
UNIT-I I
Predict the output or error(s) for the following:
1. main()
{

int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
Answer:
00131
2. main()
{

int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
Answer :
three
3. main()
{

printf("%x",-1<<4);
}
Answer:
fff0
4. main()
{

int c=- -2;


printf("c=%d",c);
}
Answer:
c=2;
5. main()
{
int i=10;
i=!i>14;
Printf ("i=%d",i);
}
Answer: i=0

218
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
6. main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
7. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545

8. main()
{
printf("%p",main);
}
Answer:
Some address will be printed

9. main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer:
400..300

10. void main()


{
int i=5;
printf("%d",i++ + ++i);
}
Answer:
Output Cannot be predicted exactly.

11. void main()


{
int i=5;
printf("%d",i+++++i);
}
Answer:
Compiler Error

12. #include<stdio.h>
main()
{
int i=1,j=2;

219
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
Answer:
Compiler Error: Constant expression required in function main.
13. main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer:
1
14. main()
{
int i=0;

for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer:
1
15. main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.
16. main()

{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
17. main()

{
char not;
not=!2;
printf("%d",not);
}
Answer:
0

220
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
18. main()

{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}
Answer:
1==1 is TRUE

19. main()

{
int y;
scanf("%d",&y); // input given is 2000
if( (y%4==0 && y%100 != 0) || y%100 == 0 )
printf("%d is a leap year");
else
printf("%d is not a leap year");
}
Answer:
2000 is a leap year
20. main()

{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
Answer:
i = -1, -i = 1

21. #include<stdio.h>
main()
{
const int i=4;
float j;
j = ++i;
printf("%d %f", i,++j);
}
Answer:
Compiler error
22. main()
{

int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:
11

221
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
23. main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Answer:
0..0
24. int i;

main(){
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
}
// If the inputs are 0,1,2,3 find the o/p
Answer:
4--0
3--1
2--2

25. main(){
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Answer:
hello
26. void main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}
Answer:
0 65535

27. main()
{

float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer:
I hate U

222
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
28. a<<1 is equivalent to
a) multiplying by 2 b) dividing by 2 c) adding 2 d)none of the above Ans. (a)
29. The operation of a stair case switch best explains the
a) or operation b) and operation c)exclusive nor operation d)exclusive or operation
30. Which of the following is/are syntactically correct? Ans. (d)
a) for(); b) for(;); c) for(,); d) for(;;);
31. The expression 4+6/3*2-2+7%3 evaluates to Ans. (d)
a) 3 b) 4 c) 6 d) 7
32. Any C program
a) must contain at least one function b) need not contain any function c) needs input data
d) none of the above Ans. (d)
33. Using goto inside for loop is equivalent to using
a) continue b) break c) return d)none of the above Ans. (d)
34. The program fragment
int a=5, b=2;
printf(“%d”,a+++++b);
a) prints 7 b)prints 8 c) prints 9 d)none of the above
35. printf(“ab” , “cd”,”ef”); prints
a) ab abcdef c) abcdef, followed by garbage value d) none of the above
36. Consider the following program segment. i=6720; j=4;
while((i%j)==0)
{
i=i/j;
j=j+1;
}
On termination j will have the value
a) 4 b) 8 c) 9 d) 6720

223
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
1. Which of the following language is predecessor to C Programming Language?
A B BCPL C++
2. C programming language was developed by
Dennis Ritchie Ken Thompson Bill Gates Peter Norton

3. C was developed in the year ___


1970 1972 1976 1980

4. C is a ___ language
High Level Low Level Middle Level Machine Level

5. C language is available for which of the following Operating Systems?


DOS Windows Unix All of these

6. Which of the following symbol is used to denote a pre-processor statement?


! # ~ ;

7. Which of the following is a Scalar Data type


Float Union Array Pointer

8. Which of the following are tokens in C?


Keywords Variables Constants All of the above

9. What is the valid range of numbers for int type of data?


0 to 256 -32768 to +32767 -65536 to +65536 No specific range

10. Which symbol is used as a statement terminator in C?


! # ~ ;
11. Which escape character can be used to begin a new line in C?
\a \b \m \n

224
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
12. Which escape character can be used to beep from speaker in C?
\a \b \m \n

13. Character constants should be enclosed between ___


Single quotes Double quotes Both a and b None of these

14. String constants should be enclosed between ___


Single quotes Double quotes Both a and b None of these

15. Which of the following is invalid?


„‟ ““ „a‟ „abc‟

16. The maximum length of a variable in C is ___


8 16 32 64

17. What will be the maximum size of a float variable?


1 byte 2 bytes 4 bytes 8 bytes

18. What will be the maximum size of a double variable?


1 byte 4 bytes 8 bytes 16 bytes

19. A declaration float a,b; occupies ___ of memory


1 byte 4 bytes 8 bytes 16 bytes

20. The size of a String variable is


1 byte 8 bytes 16 bytes None of these

225
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Operators in C Programming Language


1. Which of the following is an example of compounded assignment statement?
a=5 a += 5 a=b=c a=b

2. The operator && is an example for ___ operator.


Assignment Increment Logical Rational

3. The operator & is used for


Bitwise AND Bitwise OR Logical AND Logical OR

4. The operator / can be applied to


integer values float values double values All of these

5. The equality operator is represented by


:= .EQ. = ==

6. Operators have hierarchy. It is used to know which operator


operates on large
is most important is used first is faster
numbers

7. The bitwise AND operator is used for


Masking Comparison Division Shifting bits

8. The bitwise OR operator is used to


set the desired bits set the desired bits
divide numbers multiply numbers
to 1 to 0

9. Which of the following operator has the highest precedence?


* == => +
10. The associativity of ! operator is
(a) for Arithmetic (a) for Relational and
Right to Left Left to Right
and (b) for Relational (b) for Arithmetic

226
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
11. Which operator has the lowest priority?
++ % + ||

12. Which operator has the highest priority?


++ % + ||

13. Operators have precedence. A Precedence determines which operator is


takes no arguments
faster takes less memory evaluated first
14. Integer Division results in
Rounding the truncating the An Error is
Floating value
fractional part fractional part generated

15. Which of the following is a ternary operator?


? * sizeof ^

16. What will be the output of the expression 11 ^ 5?


5 6 11 None of these

17. The type cast operator is


(type) cast() // ""

18. Explicit type conversion is known as


Casting Conversion Disjunction Separation

19. The operator + in a+=4 means


a=a+4 a+4=a a=4 a=4+4

20. p++ executes faster than p+1 because


p++ is a single
p uses registers ++ is faster than + None of these
instruction

227
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

UNIT-III
Predict the output or error(s) for the following:

1. main()
{

char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmmm
aaaa
nnnn

2. main()
{

extern int i;
i=20;
printf("%d",i);
}

Answer:
Linker Error : Undefined symbol '_i'
3. #define int char
main()
{

int i=65;
printf("sizeof(i)=%d",sizeof(i));
}
Answer:
sizeof(i)=1
4. #define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64

5. #include <stdio.h>
#define a 10
main()
{

228
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
#define a 50
printf("%d",a);
}
Answer:
50

6. #define clrscr() 100


main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
7. main()
{
clrscr();
}
clrscr();

Answer:
No output/error
8. main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer:
Compiler error: Undefined label 'here' in function main
9. #define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));

}
Answer:
100

229
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
10. main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer:
100
11. main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer:

Compiler error: Type mismatch in redeclaration of show.


12. int i,j;

for(i=0;i<=10;i++)
{
j+=5;
assert(i<5);
}
Answer:
Runtime error: Abnormal program termination.
assert failed (i<5), <file name>,<line number>
13. #define FALSE -1

#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}
Answer:
TRUE
14. #define max 5

#define int arr1[max]


main()
{
typedef char arr2[max];
arr1 list={0,1,2,3,4};
arr2 name="name";

230
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf("%d %s",list[0],name);
}
Answer:
Compiler error (in the line arr1 list = {0,1,2,3,4})
15. int i=10;

main()
{
extern int i;
{
int i=20;
{
const volatile unsigned i=30;
printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}
Answer:
30,20,10
16. #include<stdio.h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d..%d",*p,*q);
}
Answer:
garbagevalue..1

17. #include<stdio.h>
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}
Answer:
hello 5

18. main()
{
int i=_l_abc(10);

printf("%d\n",--i);
}
int _l_abc(int i)
{

231
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
return(i++);
}
Answer:
9
19. main()
{
char c=' ',x,convert(z);
getc(c);
if((c>='a') && (c<='z'))
x=convert(c);
printf("%c",x);
}
convert(z)
{
return z-32;
}
Answer:
Compiler error

20. main()
{
int i;
i = abc();
printf("%d",i);
}
abc()
{
_AX = 1000;
}
Answer:
1000
21. What are the following notations of defining functions known as?
i. int abc(int a,float b)

{
/* some code */
}
ii. int abc(a,b)
int a; float b;
{
/* some code*/
}
Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation
22. void main()
{
static int i=5;
if(--i){
main();
printf("%d ",i);

232
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
}
}
Answer:
0000

23. void main()


{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
Answer:
Here value is 7

24. void main()


{
char a[]="12345\0";
int i=strlen(a);
printf("here in 3 %d\n",++i);
}
Answer:
here in 3 6

25. void main()


{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}
Answer:
Ok here

26. main()

{
clrscr();
}
clrscr();
Answer:
No output/error
27. main()

{
static int var = 5;

233
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
printf("%d ",var--);
if(var)
main();
}
Answer:
54321

28. C preprocessor
a) tales care of conditional compilation b) tales care of macros c) tales care of include files d)
acts before compilations
29. A preprocessor command
a) need not start on a new line b) need not start on the first column c) has # as the first
character d) comes before the first executable statement
30. The following program output is
main()
{
int a=4;
change(a);
printf(“%d”,a);
}
change(int a)
{ printf(“%d”,++a); } a)5 5 b)4 5 c) 5 4 d)4 4
31. The output of the following program is
main()
{
static int x[]={1, 2, 3, 4, 5, 6, 7, 8};
int i;
for(i=2;i<6;i++)
x[x[i]]=x[i];
for(i=0; i<8;i++)
printf(“%d”,x[i]);
}
a) 1 2 3 3 5 5 7 8 b)1 2 3 4 5 6 7 8 c) 8 7 6 5 4 3 2 1 d)1 2 3 5 4 6 7 8

32. The order in which actual parameters are evaluated in a function call
a) is from the left b)is from the right c) is compiler dependent d)none of the above
33. The default parameter passing mechanism is
a) call by value b) call by reference c) call by value result d) none
34. C does no automatic array bound checking. This is
a) true b) false c) C‟s asset d) C‟s shortcoming
35. If a two dimensional array is used as a formal parameter, then
a) both the subscripts may be left empty b) the first( row) subscript may be left empty
c)the first subscript must be left empty d) both the subscripts must be left empty
36. If storage class is missing in the array definition, by default it will be taken to be
a) automatic b) external c) static
d) either automatic or external depending on the place of occurrence
37. Consider the declaration static char hello[]=“hello”; The output of printf(“%s\n”,hello); will
be the same as that of
a) puts( “hello”); b) puts(hello); c) printf(“%s\n”, “hello”); d) puts(“hello\n”);

234
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
38. The array name can be pointer to
a) another array b) another variable c) to that array only d) none
39. Array of pointers to table of strings saves
a) time b) memory c) CPU utilization d)none of the above
40. The following program
main()
{
inc(); inc(); inc();
}
inc()
{
static int x;
printf(“%d”,++x);
} prints
a)0 1 2 b) 1 2 3 c) 3 consecutive, but unpredictable numbers d) 1 1 1

UNIT-IV
Predict the output or error(s) for the following:

1. main()
{

int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++) {
printf(" %d ",*c);
++q; }
for(j=0;j<5;j++){
printf(" %d ",*p);
++p; }
}

Answer:
2222223465

2. main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer:
ibj!gsjfoet

3. void main()
{
char far *farther,*farthest;

printf("%d..%d",sizeof(farther),sizeof(farthest));

235
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

}
Answer:
4..2
4. main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
Answer:
H
5. main()
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}
Answer:
Compiler error: Lvalue required in function main
6. #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
M
7. main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(“%u %u %u %d \n”,a,*a,**a,***a);
printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
}
Answer: 100, 100, 100, 2
114, 104, 102, 3
8. main( )
{
int a[ ] = {10,20,30,40,50},j,*p;
for(j=0; j<5; j++)
{
printf(“%d” ,*a);

236
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
a++;
}
p = a;
for(j=0; j<5; j++)
{
printf(“%d ” ,*p);
p++;
}
}
Answer:
Compiler error: lvalue required.

9. main( )
{
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*++ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
}
Answer:
111
222
333
344

10. pointers are of


a) integer data type b) character data type c) unsigned integer data type d) none of these
11. main( )
{
void *vp;
char ch = „g‟, *cp = “goofy”;
int j = 20;
vp = &ch;
printf(“%c”, *(char *)vp);
vp = &j;
printf(“%d”,*(int *)vp);
vp = cp;
printf(“%s”,(char *)vp + 3);
}
Answer:
g20fy

237
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
12. main ( )
{
static char *s[ ] = {“black”, “white”, “yellow”, “violet”};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(“%s”,*--*++p + 3);
}
Answer:
ck

13. main()
{
int i, n;
char *x = “girl”;
n = strlen(x);
*x = x[n];
for(i=0; i<n; ++i)
{
printf(“%s\n”,x);
x++;
}
}
Answer:
(blank space)
irl
rl
l
14. main()

{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}
Answer:
Compiler error (at line number 4): size of v is Unknown.

15. main()

{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}
Answer:
2 55

238
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
16. main()

{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}
Answer:
10
17. void main()
{

int const * p=5;


printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
18. main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}
Answer:
0001...0002...0004
19. main(int argc, char **argv)
{
printf("enter the character");
getchar();
sum(argv[1],argv[2]);
}
sum(num1,num2)
int num1,num2;
{
return num1+num2;
}
Answer:
Compiler error.
20. # include <stdio.h>
int one_d[]={1,2,3};
main()
{
int *ptr;

239
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
ptr=one_d;
ptr+=3;
printf("%d",*ptr);
}
Answer:
garbage value

21. # include<stdio.h>
aaa() { printf("hi"); }

bbb(){ printf("hello"); }
ccc(){ printf("bye"); }
main()
{
int (*ptr[3])();
ptr[0]=aaa; ptr[1]=bbb;
ptr[2]=ccc; ptr[2]();
}
Answer:
bye

22. In the following pgm add a stmt in the function fun such that the address of
'a' gets stored in 'j'.
main(){
int * j;
void fun(int **);
fun(&j);
}
void fun(int **k) {
int a =0;
/* add a stmt here*/
}
Answer:

*k = &a
23. main()
{
char *p;
p="%d\n";

p++;
p++;
printf(p-2,300);
}
Answer:
300
24. func(a,b)
int a,b;
{
return( a= (a==b) );
}

240
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
main()
{
int process(),func();
printf("The value of process is %d !\n ",process(func,3,6));
}
process(pf,val1,val2)
int (*pf) ();
int val1,val2;
{
return((*pf) (val1,val2));
}
Answer:
The value if process is 0 !

25. main()
{

char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}

Answer:
12

26. main()

char string[]="Hello World";


display(string);
}
void display(char *string)
{
printf("%s",string);
}
Answer:
Compiler Error : Type mismatch in redeclaration of function display

27. #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
77

241
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
28. #include<stdio.h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer:
SomeGarbageValue---1

29. puts(argv[0])prints
a) the name of the source code file b) the number of command line arguments c) argv
d)the name of the executable code file
30. The address operator &, cannot act on
a) R-values b) arithmetic expressions c) members of a structure d) local variables
31. The argument used to print the number of command line arguments is
a)printf(“%d”,argv); b) printf(“%d”,argv[0]); c) printf(“%d”,argc); d) none
32. In command line arguments main() function takes ____ number of arguments
a) 1 b) 2 c)3 d)4

242
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Unit – V
Predict the output or error(s) for the following:

1 #include<stdio.h>
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s; printf("%d",s->x);
printf("%s",s->name);
}
Answer: Compiler Error

2. #include<stdio.h> main()
{
struct xx
{
int x;
struct yy
{
char s; struct xx *p;
};
struct yy *q;
};
}
Answer: Compiler Error

3. enum colors{ BLACK,BLUE,GREEN}


main()
{
printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);
}
Answer: 0..1..2

4. #include<stdio.h> main()
{
struct xx
{
int x=3;
char name[]="hello"; };
struct xx *s=malloc(sizeof(struct xx)); printf("%d",s->x); printf("%s",s- >name);
}
Answer: Compiler Error

5. struct aaa{
struct aaa *prev; int i;
struct aaa *next; };

243
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
main()
{
struct aaa abc,def,ghi,jkl; int x=100; abc.i=0;abc.prev=&jkl;
abc.next=&def;
def.i=1;def.prev=&abc;def.next=&ghi; ghi.i=2;ghi.prev=&def; ghi.next=&jkl;
jkl.i=3;jkl.prev=&ghi;jkl.next=&abc; x=abc.next->next->prev->next->i;
printf("%d",x);
}
Answer: 2

6. struct point
{
int x; int y; };
struct point origin,*pp; main()
{
pp=&origin;
printf("origin is(%d%d)\n",(*pp).x,(*pp).y); printf("origin is
(%d%d)\n",pp->x,pp->y);
}

Answer: origin is(0,0) origin is(0,0)

7. What is the output for the program given below

typedef enum errorType{warning, error, exception,}error;


main()
{
error g1; g1=1;
printf("%d",g1);
}
Answer: Compiler error: Multiple declaration for error

8.typedef struct error{int warning, error, exception;}error; main()


{
error g1; g1.error =1;
printf("%d",g1.error);
}

Answer: 1

9. main()
{
struct student
{
char name[30]; struct date dob;
}stud;
struct date
{
int day,month,year;
};
scanf("%s%d%d%d",stud.rollno,&student.dob.day,&student.dob.month,&student.dob.year);
244
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
}
Answer: Compiler Error: Undefined structure date

10. Is the following code legal?


struct a
{
int x;
struct a *b;
}
Answer: Yes.

11. #include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer: Compiler Error

12.Structures may contains


a) multiple data items b)single data items c) a only d) a&b Ans: a

13.The size of structure and union is same when they contain


a)single member b) any number of members c) a & b d) none Ans : a

14. The operator used to find the size of any variable


a) sizeof b) Sizeof c) sizeOf d) all the above Ans: a

15. The operator that is used to access the members of the structure using pointer variable
a) . b) -> c) * d) none of the above Ans : b

16. The operator used to access the member of the structure


a) . b) -> c) * d) none of the above Ans : a

17. The operator -> is same as the combinations of the operators


a) * and . b) & and . c) * and & d) none of the above Ans :

18. Bit fields are used to


a) save time b) save memory
c) change order of allocation of memory d) none of the above

19. Union can store _________ number of values at a time


a) all its members b) only 1 b) 2 d) cannot hold value

245
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Unit – VI
Predict the output or error(s) for the following:

1. what will be the position of the file marker?


a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);

Answer :
a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position of the file.

2. #include<stdio.h> main()
{
FILE *ptr; char i;
ptr=fopen("zzz.c","r");
while((i=fgetch(ptr))!=EOF)
printf("%c",i);
}
Answer: contents of zzz.c followed by an infinite loop

3. There were 10 records stored in “somefile.dat” but the following program printed 11 names.
What went wrong?
void main()
{
struct student
{
char name[30], rollno[6]; }stud;
FILE *fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
{
fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
}
}
Explanation: fread reads 10 records and prints the names successfully. It will
return EOF only when fread tries to read another record and fails reading EOF
(and returning EOF). So it prints the last record again. After this only the
condition feof(fp) becomes false, hence comes out of the while loop.

4. #define assert(cond) if(!(cond)) \


(fprintf(stderr, "assertion failed: %s, file %s, line %d
\n",#cond,\ __FILE__,__LINE__), abort())

void main()
{
int i = 10; if(i==0)
assert(i < 100); else
printf("This statement becomes else for if in assert macro");
}
Answer: No output

246
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

5 .What is the problem with the following code segment?


while ((fgets(receiving array,50,file_ptr)) != EOF);

Answer: fgets returns a pointer

6. If a file is opened in r+ mode then


a)reading is possible b)writing is possible
c) it will be created if it does not exist d)appending is possible

7. If a file is opened in w+ mode then


a)reading is possible b)writing is possible
c) it will be created if it does not exist d)appending is possible

8. If a file is opened in r mode then


a)reading is possible b)writing is possible
c) it will be created if it does not exist d)appending is possible

9. If a file is opened in a mode then


a)reading is possible b)writing is possible
c) it will be created if it does not exist d)appending is possible

10. ftell
a) is a function b) gives the current file position indicator
c)can be used to find the size of a file d) none of the above

11.The fseek function


a) needs 2 arguments b)makes rewind function unnecessary
c)takes 3 arguments d)none of the above

12. rewind function takes __ number of arguments


a) 1 b) 2 c)3 d) 0

13. fseek(fptr,0,0) is equivalent to


a) ftell b) rewind c)a & b d) none of the above

14. .ferror function is used to find


a) logical b) file opening c)data d)all the above

15. The contents of the file are lost if it is opened in _______ mode
a) a b)w c) w+ d) a+

16. The contents of the file are safe if it is opened in _________ mode
a) a b)r c) a+b d)all the above

17. The valid binary modes of operation are


a) ab b)rb+ c) wb+ d)ab+

18. rewind function is used to


a) reset the file pointer b) point it to the end of the file
c) stay at current position d)none of the above

247
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
19. feof function checks for
a) file opening error b) data error c) end of file d) file closing error

20. The value returned by fopen() function when the file is not opened
a) 0 b) garbage value c) NULL d) none of the above

21. The fcloseall() function performs


a) closing of all the files b) closes all the files that are opened by that program
c)closes only specified files d) none of the above

22.The function that is not used for random access to files is


a)rewind b)ftell c)fseek d)fprintf

248
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Unit -VII
1The time complexity of binary search in average case is
a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

2..The time complexity of bubble sort in best case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

3.The time complexity of selection sort in best case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

4..The time complexity of insertion sort in best case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

5. The time complexity of quick sort in best case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

6.The time complexity of heap sort in best case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

7.Binary search is effective only when the elements are in


a) ascending order b) descending order c) a& b d) jumbled order

8.. In worst case quick sort behaves like


a) insertion b)heap c) selection ) bubble

9..The time complexity of bubble sort in worst case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

10.The time complexity of selection sort in worst case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

11 .The time complexity of insertion sort in worst case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

12..The time complexity of quick sort in worst case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

13.. The time complexity of heap sort in worst case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

14.The time complexity of merge sort in worst case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

15.Quick sort is an application of


a) greedy method b) partition exchange sort
c) partition sort d)divide and conquer

16.Merge sort is an application of


a)greedy method b) partition exchange sort
c) partition sort d)divide and conquer

249
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
17.The space complexity of Quick sort in average case is
a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

18. .The space complexity of bubble sort in average case is


a) O(n) b) O(n2) c) O(nlogn) d) O(logn)

250
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

UNIT - VIII

1. .Linked list uses __________ type of memory allocation


a) static b)random c)dynamic d)compile time

2. .Binary tree can be implemented using


a)arrays b) double linked list c) a& b d) b only

3.In a complete binary tree, if the parent is at nth position then the children will be at a)n+1, n+2
b)2n,2n-1 c)2n,2n+1 d)2n+1,2n-1

4.The number of non leaf nodes in a complete binary tree of height 5 is a) 16 b)32 c) 31 d)15

5..The number of leaf nodes in a complete binary tree of height 5 is a) 16 b)32 c) 31


d)15
6.The number of nodes in a complete binary tree of height 5 is
a) 16 b)32 c) 31 d)15
7. The number of edges in a minimum cost spanning tree of n nodes is
a) n b)n+1 c)n-1 d)2n
8. Travelling sales man problem is an application of
a) spanning trees b) binary tree c) greedy method d)divide and conquer
9. The number of extra pointers required to reverse a singly linked list is
a)1 b)2 c) 3 d)4
10.The number of extra pointers required to reverse a double linked list is
a)1 b) 2 c) 3 d)4

11.The functions used for memory allocation


a) malloc b)calloc c)a&b d) none of the above

251
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

Predict the output or error(s) for the following:

1.main()
{
main();
}
Answer:
Runtime error : Stack overflow.
2.The prefix equivalent for the postfix ab+cd+* is
a)a+b*c+d b)+ab*+cd c)*+ab+cd d)*++abcd
3.The postfix equivalent for the prefix *++abcd is
a)ab+c+d* b)abcd++* c)ab+cd+* d)ab+c*d+
4.The infix equivalent to the postfix expression abc+d-*e%f/ is
a) a+b*c-d%f/f b) a*(b+c-d)%e/f c)a*b+c-d%e/f d)a*(b-c+d)%e/f
5.Evaluate the expression 2*3/5+6-4
a) 1 b) 2 c)3 d) 4
6.The value of the prefix expression +/*2-5 6 4 3 is
a) 1 b) 2 c)3 d) 4
7. The value of the postfix expression 1 4 +3 / 2 * 6 4 % - is
a) 1 b)-1 c)0 d)4
8.Towers of Hanoi is an application of
a) stack b) queue c) linked list d) dequeue
9.The data structure used in railway reservation is
a) stacks b) queues c)priority queues d) binary tree
10.The data structure applicable for a fully packed bus is
a) stacks b) queues c)priority queues d) binary tree
11. The recursive functions are evaluated using
a) stacks b) queues c)priority queues d) binary tree
12.The nested loops are evaluated using
a) stacks b) queues c)structures d) binary tree
13.The data structure used in resource sharing systems is
a) stacks b) queues c)arrays d) binary tree
14.Which of the following is not a linear data structure
a) stacks b) queues c)linked list d) binary tree
15.In evaluation of postfix expression the data structure used is
a) stacks b) queues c)arrays d) binary tree

252
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
OBJECTIVE TYPE QUESTIONS

Which of the following is correct output?

1. void main(){

int x=100;

if(!!x)

printf(“x=%d”,!x);

else printf(“x=%d”,x);

a. 0

b. 2

c. 1.5

d. 100

2. void main(){

float a=0.5, b=0.9;

if(a&&b>0.9)

printf(“it is ur style”);

else

printf(“it is my style”);

a. it is ur style

b. it is our style

c. it is my style

d. no output

3. void main( ){

int x=10, y=20;

253
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
if(!(!x) && x)
printf(“x=%d”,x);
else
printf(“y=%d”,y);
}
a. 10
b. 20
c. 1
d. 0

4. void main(){

char ch=291;

printf(“%d%d%c”,32770,ch,ch);

a. 291

b. -32766 35#

c. 32770chch

d. 32770

5. void main (){

int a,b;

a = -3- -3;

b = -3 - - (-3 );

printf(“a=%d b= %d”,a,b);

a. a=0 b=-6

b. a=-3 b=+3

c. a=-6 b=+6

d. a=6 b=0
254
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
6. void main(){

int x;

x= -3 + 4 – 7 * 8 / 5 % 10;

printf(“x = %d”,x);

a. 23

b. 6

c. 7

d. 0

7. void main(){

int x=3, y=4, z=4;

printf(“ans = %d”, (z>=y>=x?100:200));}

a. 100

b. 300

c. 200

d. No Output

8. void main( ){

int a=30, b=40, x;

x=(a!=10) && (b=50);

printf(“x= %d”,x);

a. 10

b. 50

c. 1

d. 0

255
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
9. void main( ){

float x=12.25, y=13.65;

if(x=y)

printf(“x and y are equal”);

else

printf(“x and y are not equal”);

a. x and y are not equal

b. x and y are equal

c. No output

d. None of thea bove

10. void main (){

int i=1, j=1;

for(;j;printf(“%d%d\t”,i,j))

j=i++ <= 5;

a. 21 31 41 51 61 70

b. 21 30 41 50 61 70

c. 20 30 40 50 60 70

d. 21 31 41 51 61 71

11. void main( ) {

int i=3, j=2, k=1, d;

d = ij&k, printf(“d = %d\t”,d);

d=ij&~k;

printf(“d = %d”,d);

256
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
a. d = 3 d=3

b. d=2 d=2

c. d=3 d=2

d. none of the above

12. void main( ) {

int i=2;

printf(“i-- = %d”, i--);

a. i-- = 2

b. i-- = 3

c. i-- = 1

d. none of the above.

13. void main( ) {

float y=0.9;

long double z= 0.9;

if(y = = z)

printf(“hello world”);

else

printf(“hai world”); }

a. hello world

b. hai world

c. no output

d. none of the above

14. void main( ){

static int c=5;

printf(“%d\t”,c--);

257
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
if(c)

main( );

a. 5 4 3 2 1

b. 1 2 3 4 5

c. 5 4 3 3 3

d. none of the above

15. int i;

void main( ){

int j;

for(;;){

if(j=fun(i))

printf(“%d”,j);

else

break;

}
}
fun(x){

int x;

static int v=2;

v--;

return (v-x);

a. 1

b. 5

c. 0

d. None of the above

258
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
16. What will be the output of the following program in UNIX OS with CC compiler and TC
compiler?

void main() {

int i=5;

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

a. 41.

b. 42

c. 51

d. 62

17. void main() {

if (!(1&&0)) {

printf("OK I am done.");

else {

printf("OK I am gone.");

}}

a. OK I am done

b. OK I am gone

c. None of the above

18.

void main() {

char *a = "Hello ";

char *b = "World";

clrscr();

printf("%s", strcpy(a,b));

259
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
}

a. World.

b. Hello

c. Hello World

d. World Hello

19.

int z,x=5,y=-10,a=4,b=2;

z = x++ - --y * b / a;

What number will z in the sample code above contain?

a. 5

b. 6

c. 10

d. 11

e. 12 [Ans]

20. With every use of a memory allocation function, what function should be used to release
allocated memory which is no longer needed?

a. unalloc()

b. dropmem()

c. dealloc()

d. release()

e. free() [Ans]

21.

void *ptr;

myStruct myArray[10];

ptr = myArray;

Which of the following is the correct way to increment the variable "ptr"?

260
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
A. ptr = ptr + sizeof(myStruct); [Ans]

B. ++(int*)ptr;

C. ptr = ptr + sizeof(myArray);

D. increment(ptr);

E. ptr = ptr + sizeof(ptr);

22.

char* myFunc (char *ptr) {

ptr += 3;

return (ptr);

int main() {

char *x, *y;

x = "HELLO";

y = myFunc (x);

printf ("y = %s \n", y);

return 0;

What will print when the sample code above is executed?

A. y = HELLO

B. y = ELLO

C. y = LLO

D. y = LO [Ans]

E. x = O

23.

struct node *nPtr, *sPtr; /* pointers for a linked list. */

for (nPtr=sPtr; nPtr; nPtr=nPtr->next)

261
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
{

free(nPtr);

The sample code above releases memory from a linked list. Which of the choices below accurately
describes how it will work?

A. It will work correctly since the for loop covers the entire list.

B. It may fail since each node "nPtr" is freed before its next address can be accessed.

C. In the for loop, the assignment "nPtr=nPtr->next" should be changed to "nPtr=nPtr.next".

D. This is invalid syntax for freeing memory.

E. The loop will never end.

24. What function will read a specified number of elements from a file?

A. fileread()

B. getline()

C. readfile()

D. fread()

E. gets()

25. "My salary was increased by 15%!"

Select the statement which will EXACTLY reproduce the line of text above.

A. printf("\"My salary was increased by 15/%\!\"\n");

B. printf("My salary was increased by 15%!\n");

C. printf("My salary was increased by 15'%'!\n");

D. printf("\"My salary was increased by 15%%!\"\n");[Ans]

E. printf("\"My salary was increased by 15'%'!\"\n");

26. What is a difference between a declaration and a definition of a variable?

A. Both can occur multiple times, but a declaration must occur first.

B. There is no difference between them.

262
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
C. A definition occurs once, but a declaration may occur many times.

D. A declaration occurs once, but a definition may occur many times. [Ans]

E. Both can occur multiple times, but a definition must occur first.

27. int testarray[3][2][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

What value does testarray[2][1][0] in the sample code above contain?

A. 3

B. 5

C. 7

D. 9

E. 11[Ans]

28. int a=10,b;

b=a++ + ++a;

printf("%d,%d,%d,%d",b,a++,a,++a);

what will be the output when following code is executed

A. 12,10,11,13

B. 22,10,11,13

C. 22,11,11,11

D. 12,11,11,11

E. 22,13,13,13[Ans]

29. int x[] = { 1, 4, 8, 5, 1, 4 };

int *ptr, y;

ptr = x + 4;

y = ptr - x;

What does y in the sample code above equal?

A. -3

B. 0

263
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
C. 4[Ans]

D. 4 + sizeof( int )

E. 4 * sizeof( int

30. void myFunc (int x)

if (x > 0)

myFunc(--x);

printf("%d, ", x);

int main()

myFunc(5);

return 0;

What will the above sample code produce when executed?

A. 1, 2, 3, 4, 5, 5,

B. 4, 3, 2, 1, 0, 0,

C. 5, 4, 3, 2, 1, 0,

D. 0, 0, 1, 2, 3, 4, [Ans]

E. 0, 1, 2, 3, 4, 5,

31. 11 ^ 5

What does the operation shown above produce?

A. 1

B. 6

C. 8

D. 14 [Ans]

264
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
E. 15

32. #define MAX_NUM 15

Referring to the sample above, what is MAX_NUM?

A. MAX_NUM is an integer variable.

B. MAX_NUM is a linker constant.

C. MAX_NUM is a precompiler constant.

D. MAX_NUM is a preprocessor macro. [Ans]

E. MAX_NUM is an integer constant.

33. Which one of the following will turn off buffering for stdout?

A. setbuf( stdout, FALSE );

B. setvbuf( stdout, NULL );

C. setbuf( stdout, NULL );

D. setvbuf( stdout, _IONBF );

E. setbuf( stdout, _IONBF );

34. What is a proper method of opening a file for writing as binary file?

A. FILE *f = fwrite( "test.bin", "b" );

B. FILE *f = fopenb( "test.bin", "w" );

C. FILE *f = fopen( "test.bin", "wb" );

D. FILE *f = fwriteb( "test.bin" );

E. FILE *f = fopen( "test.bin", "bw" );

35. Which one of the following functions is the correct choice for moving blocks of binary data that
are of arbitrary size and position in memory?

A. memcpy()

B. memset()

C. strncpy()

D. strcpy()

265
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
E. memmove()[Ans]

36. int x = 2 * 3 + 4 * 5;

What value will x contain in the sample code above?

A. 22

B. 26[Ans]

C. 46

D. 50

E. 70

37. void * array_dup (a, number, size)

const void * a;

size_t number;

size_t size;

void * clone;

size_t bytes;

assert(a != NULL);

bytes = number * size;

clone = alloca(bytes);

if (!clone)

return clone;

memcpy(clone, a, bytes);

return clone;

The function array_dup(), defined above, contains an error. Which one of the following correctly
analyzes it?

A. If the arguments to memcpy() refer to overlapping regions, the destination buffer will be subject
to memory corruption.

266
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
B. array_dup() declares its first parameter to be a pointer, when the actual argument will be an array.

C. The memory obtained from alloca() is not valid in the context of the caller. Moreover, alloca() is
nonstandard.

D. size_t is not a Standard C defined type, and may not be known to the compiler.

E. The definition of array_dup() is unusual. Functions cannot be defined using this syntax.

38. int var1;

If a variable has been declared with file scope, as above, can it safely be accessed globally from
another file?

A. Yes; it can be referenced through the register specifier.

B. No; it would have to have been initially declared as a static variable.

C. No; it would need to have been initially declared using the global keyword.[Ans]

D. Yes; it can be referenced through the publish specifier.

E. Yes; it can be referenced through the extern specifier.

39. time_t t;

Which one of the following statements will properly initialize the variable t with the current time
from the sample above?

A. t = clock();[Ans]

B. time( &t );

C. t = ctime();

D. t = localtime();

E. None of the above

40. Which one of the following provides conceptual support for function calls?

A. The system stack[Ans]

B. The data segment

C. The processor's registers

D. The text segment

E. The heap

267
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
QUESTIONS WITH ANSWERS

Question 1. What is the difference between #include <file> and #include ?file?

Answer:
When writing your C program, you can include files in two ways. The first way is to surround the
file you
want to include with the angled brackets < and >. This method of inclusion tells the preprocessor to
look for the file in the predefined default location. This predefined default location is often an
INCLUDE environment variable that denotes the path to your include files. For instance, given the
INCLUDE variable

INCLUDE=C:COMPILERINCLUDE;S:SOURCEHEADERS;

using the #include <file> version of file inclusion, the compiler first checks the
C:COMPILERINCLUDE
directory for the specified file. If the file is not found there, the compiler then checks the
S:SOURCEHEADERS directory. If the file is still not found, the preprocessor checks the current
directory.

The second way to include files is to surround the file you want to include with double quotation
marks. This method of inclusion tells the preprocessor to look for the file in the current directory
first, then look for it in the predefined locations you have set up. Using the #include ?file? version of
file inclusion and applying it to the preceding example, the preprocessor first checks the current
directory for the specified file. If the file is not found in the current directory, the
C:COMPILERINCLUDE directory is searched. If the file is still not found, the preprocessor checks
the S:SOURCEHEADERS directory.
The #include <file> method of file inclusion is often used to include standard headers such as stdio.h
or
stdlib.h. This is because these headers are rarely (if ever) modified, and they should always be read
from your compiler?s standard include file directory.

The #include ?file? method of file inclusion is often used to include nonstandard header files that you
have created for use in your program. This is because these headers are often modified in the current
directory, and you will want the preprocessor to use your newly modified version of the header
rather than the older, unmodified version.

Question 2 :
if "condition"
printf("Hello");
else
printf("World")
what should be the condition,
so the output will be HelloWorld
Answers:
1.
if(!printf("hello"))
printf("hello");
else
printf("world");

268
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
2.
#include<stdio.h>
main()
{
if(printf("hello")!=0)
printf("world");
else
printf("world");
}

Question3 :
Can we execute printf statement without using semicolon?
Answers:
By using if, for, do while, while loop we execute printf statement without using semicolon.
example shown below...
main()
{
if(printf("hello"))
}
We cannot Execute printf statement alone without using semicolon. Every program statement in a C
language must end with a semicolon(;). It will show the error "Statement Missing ;"

Question4 :
Why should I prototype a function?
Answers:
A function prototype tells the compiler what kind of arguments a function is looking to receive and
what kind of return value a function is going to give back. This approach helps the compiler ensure
that calls to a function are made correctly and that no erroneous type conversions are taking place.

Question5 :
What is a static function?
A static function is a function whose scope is limited to the current source file. Scope refers to the
visibility of a function or variable. If the function or variable is visible outside of the current source
file, it is said to have global, or external, scope. If the function or variable is not visible outside of the
current source file, it is said to have local, or static, scope.

Question6 :
Write the equivalent expression for x%8?
Answers: x&7

Question7 :
What is the purpose of main( ) function?
Answers:
The function main( ) invokes other functions within it.It is the first function to be called when the
program starts execution.

Question8 :
How to print a statement without using printf() in C?
Answers:using getchar()
main()
{

269
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int i;
char c;
for(i=0;i!=' ';i++)
{
c=getchar();
putchar(c,n);
}
getch();
}

Question9 :
What is a pragma?
Answers:The #pragma preprocessor directive allows each compiler to implement compiler-specific
features that can be turned on and off with the #pragma statement. For instance, your compiler might
support a feature called loop optimization. This feature can be invoked as a command-line option or
as a #pragma directive.

To implement this option using the #pragma directive, you would put the following line into your
code:

#pragma loop_opt(on)

Conversely, you can turn off loop optimization by inserting the following line into your code:

#pragma loop_opt(off)

Question10 :
What is a C-preprocessor?
Answers:
C-preprocessor is also called as header files like #include<stdio.h>,<conio.h>,etc.
These are used for including various functions and files in our programs.

Question11 :
How to perform addition,subtraction of 2 numbers without using addition and subtraction
operators?
Answers:

main()
{
int a,b,c;
printf("enter 2 nos");
scanf("%d%d",&a,&b);
for(i=1;a>0;i++)
a=a-1;
for(j=i;b>0;j++)
b=b-1;
printf("addition of %d+%d:%d",a,b,(j-1));
}

270
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
1. FOR ADDING TWO NUMBERS

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,i;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
c=b;
for(i=1; i<=a; i++)
{
b++
;
}
printf("Sum of %d and %d id : %d ",a,c,b);
getch();
}

===================================
FOR SUBTRACTION
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,i;
clrscr();
printf("Enter A : ");
scanf("%d",&a);
printf("Enter B : ");
scanf("%d",&b);
c=a;
for(i=1; i<=b; i++)
{
a--
;
}
printf("Subtraction of %d and %d id : %d ",c,b,a);
getch();
}

Question12:
Nesting of loops in C may continue upto how many levels?
Answers:
we can do nesting of loops in C upto 15 times and also depends on compilers.

271
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Question13 :
why n++ executes faster than n+1?
Answers:
The expression n++ requires a single machine instruction such as INR to carry out the increment
operation whereas, n+1 requires more instructions to carry out this operation.

Question 14:
What is the difference between declaring a variable and defining a variable?
Answers:
Declaring a variable means describing its type to the compiler but not allocating any space for it.
Defining a variable means declaring it and also allocating space to hold the variable. You can also
initialize a variable at the time it is defined.

Question 15:
What is an lvalue?
Answers: example to demonstrate lvalue
#define CONSTANT_VAR 10
int var=1;
int* pntr_int=5;
CONSTANT_VAR = 15;

The variable var is an integer, which is a storable location in memory. Therefore, the statement var =
1 qualifies var to be an lvalue. Notice the second assignment statement, *pntr_int = 5. By using the *
modifier to reference the area of memory that pntr_int points to, *pntr_int is qualified as an lvalue.

In contrast, observe the CONSTANT variable:

In this statements, the left side of the statement evaluates to a constant value that cannot be changed
because constants do not represent storable locations in memory. Therefore, this assignment
statements do not contain lvalues and will be flagged by your compiler as errors.

272
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

VIVA QUESTIONS
1) What is a Computer?
2) What is CPU?
3) What is ALU?
4) What is CU?
5) What is RAM?
6) What is ROM?
7) What are the input and output devices?
8) What is the need for cache memory?
9) Differentiate between main memory and second memory.
10) What is hardware?
11) Mention the different types of hardware components?
12) What are the different types of keyboards?
13) Differentiate between serial and parallel keyboard.
14) How do you classify printers?
15) Differentiate between serial and parallel printer.
16) What is meant by softcopy output?
17) What is meant by hardcopy output?
18) What are the different types of mouse?
19) What is programming?
20) What is software?
21) What are the different types of software?
22) What are the different types of programming languages?
23) Differentiate between interpreter and compiler.
24) Differentiate between loader and linker.
25) Differentiate between Application software and System software.
26) What is an operating system?
27) Differentiate between compiler and assembler.
28) What is translator?
29) What is meant by interpretation?
30) What is meant by source program?
31) What is meant by object program?
32) Give examples for High Level Languages.
33) Give examples for Assembly Level Languages.
34) Give examples for Specific purpose HLL.
273
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
35) Differentiate between internal & external DOS commands.
36) How do you classify the computers based on the size & capability?
37) How do you classify the computers based on principle of working?
38) What is computer network?
39) What are the different types of DOS?
40) What is DOS?
41) Who developed B language?
42) Who developed C language?
43) How do you make comments in C program?
44) How the name C is derived?
45) What is preprocessor statement?
46) Differentiate between constant and variable.
47) What is data type?
48) Name the basic data types of C.
49) Differentiate between string constant and character constant.
50) What is the range of integer, char, float for a 16-bit computer?
51) What is a statement?
52) What is a keyword?
53) Differentiate between keywords and identifiers.
54) What is the need for an escape sequences?
55) What is a symbolic constant?
56) How do you classify C operators?
57) What is the use of modulus operator?
58) What is meant by mixed mode operation?
59) What are bitwise operators?
60) What is unary operator?
61) What is binary operator?
62) What is typecasting?
63) What is a conditional / ternary operator?
64) What is need for type conversion?
65) Differentiate between && and &.
66) Differentiate between pre-increment/decrement & post-increment/decrement.
67) Differentiate between Unformatted and formatted i/o statements.
68) How do you classify the control statements?

274
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
69) Differentiate between while and do-while loop.
70) Differentiate between break and continue.
71) When do you prefer for loop statement?
72) What is looping?
73) What is an array?
74) Give the classification of arrays?
75) Differentiate between an array and an ordinary variable.
76) Array variable is also called as ______.
77) What are character arrays?
78) When do you use two-dimensional character array?
79) Name the different string handling functions?
80) What is meant by modularization?
81) Differentiate between standard functions & user-defined functions?
82) Differentiate between arguments and parameters.
83) Differentiate between local and global variables.
84) Name the different methods of parameter passing?
85) How does the function definition differ from function declaration?
86) What is recursive function?
87) What is meant by scope of a variable?
88) What is a structure?
89) Differentiate between array and structure.
90) What are embedded structures?
91) How do you access the member of a structure?
92) What is union?
93) Differentiate between union and structure.
94) What is a pointer?
95) Differentiate between address operator and dereferencing operator.
96) How do you declare a pointer variable
97) What is difference between structure and union?
98) What is use of structure?
99) What is use of union?
100) What is function recursion?
101) What is nesting of function call?
102) What is pointer?

275
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
103) What is array in C?
104) What is array of array?
105) Write a printf statement without using any semi colon.
106) What is array of pointer?
107) What is array of function?
108) What is array of structure?
109) What is difference between pass by value and pass by reference?
110) What is use of stack?
111) What is use of void?
112) What is FILE pointer?
113) What is difference between array and link list?
114) What is difference between array of character and string?
115) How can you open a file in C?
116) How can you write in a file in C?
117) How can you calculate size of union?
118) How can you calculate size of a function?
119) How can you calculate size of structure?
120) How will initialize the member of union?
121) Why we can initialize only first member of union?
122) What is difference between structure and array?
123) What is self referential structure?
124) How can you access the member of structure variables?
125) How can you access the member of union variables?
126) What is nested structure?

276
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

JNTU PREVIOUS
OBJECTIVE / BIT PAPERS

277
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

278
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

COMPUTER PROGRAMMING & DATA STRUCTURES


KEYS
I. Choose the correct alternative:
1. A 2. A 3. C 4. A 5. D
6. C 7. A 8. C 9. B 10. C

II. Fill in the blanks:


16
11. 2 - 1 or 65535 12. Firmware
13. Logical AND (&&) 14. Parenthesis or ()
15. Infinite 16. First statement of main ()
17. for loop 18. do..while
19. Rhombus or Diamond 20. Operating System (OS)

279
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

280
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

COMPUTER PROGRAMMING AND DATA STRUCTURES


Keys
I. Choose the correct alternative:
1) B 2) C 3) C 4) A 5) B
6) D 7) C 8) C 9) A 10) C

II Fill in the blanks:


11) strrev() 12) formal parameters
13) gets 14) address
15) self referential 16) sequential or contiguous
17) malloc 18) structure
19) recurision 20) file

281
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

282
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

COMPUTER PROGRAMMING AND DATA STRUCTURES


KEYS
I Choose the correct alternative
1. C 2. B 3. D 4. A 5. B
6. D 7. C 8. D 9. B 10. A

II Fill in the blanks


11. front 12. Binary Search
13. Data Structure 14. Link or pointer
15. Circular List 16. O(n)
2
17. O(n ) 18. feof()
19. the beginning of the file 20. binary

283
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD
I B.Tech. I Mid Examinations, December - 2010
COMPUTER PROGRAMMING AND DATA STRUCTURES
Objective Exam

Answer All Questions. All Questions Carry Equal Marks. Time: 20 Min. Marks: 10.

I. Choose the correct alternative:

1. What type of errors are checked during compilation [ ]


(a) logical errors (b) divide by zero error (c) run - time errors (d) syntax error

2. Which one of the following numeric value is used to represent base of the binary number
a) 8 b)10 c)2 d)16

3. What will be the binary value of B [ ]


a) 1001 b)1011 c)1100 d)1101

4. Which of the following is not a translator program [ ]


a) Linker b) Assembler c) Compiler d) Interpreter

5. The program fragment [ ]


int a=5, b=2;
a) prints 7 b) prints 8 c) prints 9 d) none of the above

6. What will be sum of the binary numbers 1111 and 1 1 00 1 [ ]


a) 101000 b) 100010 c) 11110 d) 111100

7. Which one of the folio wing is known as the language of the computer [ ]
a) Programming Language b) High Level Language
c) Machine Language d) Assembly language

8. Consider the following program segment. i=6720; j=4; [ ]


while((i%j)=0)
On termination j will have the value [ ]
a) 4 b)8 c)9 d) 6720

9. Which of the folio wing is/are syntactically correct [ ]


a)for(); b) for(;); c) forQ; d)for(;;);

284
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
10. #include<stdio.h>
main()
{
inti=lj=2;
switch(i)
{
easel: printf("GOOD");
break;
casej: printf("BAD"); [ ]
break;
a) GOOD b)BAD c) GOOD BAD d) Compiler Error

II Fill in the Blanks


11. ALU stands for___________
12. __________ translates the high level language source code into low-level language
13. The size of long double variable is ___________
14. The _______ of an operator gives the order in which expressions involving operators of the
same precedence are evaluated.
15. The output of the assembler in the form of sequence of 0's and 1's is called _______
16. The process of repeating a group of statements in an algorithm is known as _______
17. The # symbol is known as _______
18. are identifiers reserved by the C language for special use _______
19. The_______ of an operator gives the order in which operators are applied in expressions
20. _______ is very similar to the while loop except that the test occurs at the end of the loop
body

285
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD
I B.Tech. II Mid Examinations, March - 2011
COMPUTER PROGRAMMING AND DATA STRUCTURES
Objective Exam
Answer All Questions. All Questions Carry Equal Marks. Time: 20 Min. Marks: 10.

I. Choose the correct alternative


1. struct a [ ]
{intl;
float j;
};
Which of the following syntax is correct to declare a structure variable
A. struct union a; B. union struct a; C. union a t; D. struct a t;

2. Which of the following is used with printf () function for printing the Address of a variable
[ ]
A. %d B. %u C. %f D. %c

3. structj int I; [ ]
flaot j;} s; sizeof (s) will be
A. 4 bytes B. 2 bytes C. 6 bytes D. 0 bytes

4. The process of calling a function using pointers to pass the address of variables is known as
[ ]
A. call by argument B. call by parameter C. call by value D. call by
reference

5. main() [ ]
{int a=5,b,*c;c=&a;b=*c;
printf("\n value of a=%d & b=%d",a,b,)}
A. a=3,b=3 B. a=4,b=4 C. a=6,b=6 D. a=5,b=5

6. main() [ ]
{
char *strl="abcd";
char str2[ ]="abcd";
printf ("%d%d%d", sizeof(str 1 ),sizeof(str2),sizeof("abcd"));
}
A. 2 5 5 B. 5 5 2 C. Compiler error D. 5 2 5

7. A block of memory is allocated using the function [ ]


A. falloc( ) B. dalloc( ) C. malloc( ) D. calloc( )

8. In union all members use [ ]

A. no location B. same location C. different location D. no storage

9. Which of the folio wing storage classes is used to allocate memory in cpu registers [ ]
A. auto B. register C. static D. extern

286
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
10. If we declare an array like int a[4] = {1, 2, 3, 4, 5} then [ ]
A. results in compilation error B. valid but skip the last value 5.
C. valid but skip the first value 1 D. Initializes all values of array with 0

II Fill in the blanks


11. The standard library function strcmp ("JNTUH", "JNTUK") returns

12. The general format of realloc function is __________

13. Structure elements can be accessed through a pointer to a structure using the operator _

14. Self referential structure means _________________

15. A program obtaining its memory while it is running is called as ___________ .

16. The name of the array refers to __________ address

17. In command line arguments program the first argument of the main function Indicates

18. In enum wd={SUN, MON, TUE=5, WED, THU, FRI, SAT}, The value Assigned to enum
constant
FRI is__________

19. Pointers _______ the execution speed (increased/decrease)

20. Pre Processing statements are started with _______ symbol

287
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

288
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

COMPUTER PROGRAMMING AND DATA STRUCTURES


KEYS
I Choose the correct alternative:
1. A 2. B 3. C 4. B 5. A
6. D 7. A 8. C 9. D 10. B

II Fill in the blanks


11. Internal 12. Singly linked
13. Two 14. Opened
15. Waste 16. O(n log n)
17. Time 18. Doubly linked list
19. Open 20. space

289
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

290
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

COMPUTER PROGRAMMING AND DATA STRUCTURES


KEYS
I Choose the correct alternative
1. D 2. B 3. B 4. D 5. C
6. D 7. C 8. B 9. A 10. C

II Fill in the blanks


11. Iteration 12. Central Processing Unit
13. Hardware 14. Dennis Ritchie
15. ALT+F9 16. 2
17. false 18. switch
19. goto 20. American National Standards Institute

291
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD
I B.Tech. II Mid-Term Examinations, February - 2012
COMPUTER PROGRAMMING AND DATA STRUCTURES
Objective Exam
Answer All Questions. All Questions Carry Equal Marks.Time: 20 Min. Marks: 10.

I Choose the correct alternative:

1. Which one of the following indicates that the function returns nothing [ ]
(A)main() (B)Void() (C) functionQ (D)A11

2. Which one of the following cannot be de-referenced [ ]


(A) typedef * (B) int * (C) void * (D) All

3. What is the Standard Header File for the function'absQ' [ ]


(A)ctype.h (B) stdlib.h (C)math.h (D)None

4. Given data: char stringl [] = "first";then stringl [ 3 ]=? [ ]


(A) r (B) s (C) i (D) None

5. Function prototype scope is Used for identifiers in [ ]


(A) parameter list (B) Blocks (C) Arrays (D)A11

6. The value of a pointer is the address of the corresponding object or function [ ]


(A) special value&function (B) address&object (C) address&constant (D) None

7. If Strings are used as 'int strcmp(char const *sl, char const *s2);'then how will you get
return
value less than zero [ ]
(A) if si and s2 are equal; (B) if si precedes s2 in lexicographical order;
(C) if si follows s2 (D) None

8. Communicating information between functions is possible from [ ]


(A) modules (B) Parameters (C) variables (D) None

9. What is the Standard Header File for the function 'tolowerQ' [ ]


(A) stdlib.h (B)string.h (C) ctype.h (D) stdio.h

10. Where do you get more Performance [ ]


(A) Iteration (B) Recursion (C)BothA&B (D)None

292
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

II. Fill in the Blanks


11. Find out pow(2.5,3) = _____________

12. An unspecified return-value-type is always assumed by the compiler to be _____

13. Names in different enumerations must always be _________

14. ______________ programming evolved in the 1970s

15. All ____________ functions return data type double

16. A _______ pointer points to a heap-dynamic variable that has been de-allocated.

17. _____________ header files Create file with functions

18. Often, typedefis used in combination with ______________ to declare a synonym (or an

alias) for a structure

19. Program exits prematurely is caused by ______ error

20. C is used to insert common definitions into source files

COMPUTER PROGRAMMING AND DATA STRUCTURES


KEYS
I Choose the correct alternative
1. B 2. C 3. B 4. B 5. A
6. B 7. B 8. B 9. C 10. A

II Fill in the blanks


11. 15.625 12. int
13. distinct 14. structured
15. math 16. dangling
17. custom 18. struct
19. fatal 20. preprocessor

293
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

294
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

COMPUTER PROGRAMMING AND DATA STRUCTURES


KEYS
I. Choose the correct alternative
1. D 2. B 3. A 4. C 5. C
6. C 7. B 8. A 9. A 10. B

II Fill in the blanks


11. random-access 12. secondary storage
13. ferror () 14. restricted
15. New 16. binary
17. Queue 18. linked list
19. deterministic 20. Bubble

295
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

296
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

JNTU PREVIOUS
EXTERNAL QUESTION PAPERS

297
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

298
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

299
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

300
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

301
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

302
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

303
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

304
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

305
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

306
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

307
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

308
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

309
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

310
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

311
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

312
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

313
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

314
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

315
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

316
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

317
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

318
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

319
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL

320

You might also like