??C Programming (PPS)
??C Programming (PPS)
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
1
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
SYLLABUS
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
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
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
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
Computer Computer
Hardware Software
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
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
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
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
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
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 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.
Arrows are used for connecting the symbols and show the flow of execution
21
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Symbols used in flowchart:
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
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
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
29
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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
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.
33
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program:
main ( )
{
int a= 20, b = 10; Output
printf (“ %d”, a+b); 30
}
2).Relational operators :
These are used for comparing two expressions.
} 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
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
Program:
main ( )
{ int a= 10,; Output
printf (“ %d”, a); 10
}
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 ( )
{ {
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
37
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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
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
}
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 = 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
}
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
Primary Expression
() [] . -> expr++ expr-- left-to-right
Operators
* / %
+ -
== !=
41
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
&
&&
||
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)
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?
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
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
Stmt n Stmt x
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 =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
52
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Program
main( )
{ Output
int k; 1
{ 3
printf (”%d”,k); 4
} 5
}
2) while loop
Syntax
while (condition)
{
body of the loop
}
Flow chart
initialization
Is False
expression?
True
Incr/ dec
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
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
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
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.
Main Program
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
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.
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.
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
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
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
}
}
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
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:
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]
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
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
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;
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
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:
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]
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
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
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‟
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
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);
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:
o n e \0 t w o \0 t h r e e \0
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
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
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: ssno, ssname, smarks;
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”, stsname);
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 ( );
}
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”, dtday);
printf(“month = %d”,dtmon);
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.
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
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
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
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 ( );
}
140
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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 ( )
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 ();
}
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.
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
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
10 20 30 50 40
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
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
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
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
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.
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 ( );
}
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
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
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
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.
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
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
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
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;
}
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 :
193
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
1)Single linked list :
Representation
Null 10 20 30 Null
10 20 30
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.
195
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
int data;
struct node * link;
};
struct *node1, *node2, *node3;
node1 data = 10
node2data = 20
node3 data = 30
node1 link = node 2;
node2 link = node 3;
node3 link = NULL;
196
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Node 2 temp
B-I 10 20 30
Deletion :
Delete node2
Node 1 Node 3
A.D 10 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
A.D 10 20
Node 1
A.D 10 30
o/p : 10 20 30
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)
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”);
}
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…..
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);
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;
}
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
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 = startlink;
}
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
{
rearlink = 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 = frontlink;
}
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
{
*rearlink = 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 = frontlink;
}
printf(“REAR”);
}
214
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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) */%-+=
(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 ____________________
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
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
Answers: 1) c 2) b 3) a 4) a 5) b 6) d 7) a 8) a
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
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()
{
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
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
4. C is a ___ language
High Level Low Level Middle Level Machine Level
224
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
12. Which escape character can be used to beep from speaker in C?
\a \b \m \n
225
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
226
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
11. Which operator has the lowest priority?
++ % + ||
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
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:
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
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
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
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()
{
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()
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
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: 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
11. #include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer: Compiler Error
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
245
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
Unit – VI
Predict the output or error(s) for the following:
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.
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
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
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
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
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)
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)
250
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
UNIT - VIII
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
251
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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
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(){
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( ){
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
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(){
a. 100
b. 300
c. 200
d. No Output
8. void main( ){
printf(“x= %d”,x);
a. 10
b. 50
c. 1
d. 0
255
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
9. void main( ){
if(x=y)
else
c. No output
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
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
int i=2;
a. i-- = 2
b. i-- = 3
c. i-- = 1
float y=0.9;
if(y = = z)
printf(“hello world”);
else
printf(“hai world”); }
a. hello world
b. hai world
c. no output
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
15. int i;
void main( ){
int j;
for(;;){
if(j=fun(i))
printf(“%d”,j);
else
break;
}
}
fun(x){
int x;
v--;
return (v-x);
a. 1
b. 5
c. 0
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;
a. 41.
b. 42
c. 51
d. 62
if (!(1&&0)) {
printf("OK I am done.");
else {
printf("OK I am gone.");
}}
a. OK I am done
b. OK I am gone
18.
void main() {
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;
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;
D. increment(ptr);
22.
ptr += 3;
return (ptr);
int main() {
x = "HELLO";
y = myFunc (x);
return 0;
A. y = HELLO
B. y = ELLO
C. y = LLO
D. y = LO [Ans]
E. x = O
23.
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.
24. What function will read a specified number of elements from a file?
A. fileread()
B. getline()
C. readfile()
D. fread()
E. gets()
Select the statement which will EXACTLY reproduce the line of text above.
A. Both can occur multiple times, but a declaration must occur first.
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.
A. 3
B. 5
C. 7
D. 9
E. 11[Ans]
b=a++ + ++a;
printf("%d,%d,%d,%d",b,a++,a,++a);
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]
int *ptr, y;
ptr = x + 4;
y = ptr - x;
A. -3
B. 0
263
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
C. 4[Ans]
D. 4 + sizeof( int )
E. 4 * sizeof( int
if (x > 0)
myFunc(--x);
int main()
myFunc(5);
return 0;
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
A. 1
B. 6
C. 8
D. 14 [Ans]
264
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
E. 15
33. Which one of the following will turn off buffering for stdout?
34. What is a proper method of opening a file for writing as binary file?
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;
A. 22
B. 26[Ans]
C. 46
D. 50
E. 70
const void * a;
size_t number;
size_t size;
void * clone;
size_t bytes;
assert(a != NULL);
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.
If a variable has been declared with file scope, as above, can it safely be accessed globally from
another file?
C. No; it would need to have been initially declared using the global keyword.[Ans]
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();
40. Which one of the following provides conceptual support for function calls?
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 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
279
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
280
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
281
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
282
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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.
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
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
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
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.
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
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
13. Structure elements can be accessed through a pointer to a structure using the operator _
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__________
287
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
288
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
289
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
290
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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.
1. Which one of the following indicates that the function returns nothing [ ]
(A)main() (B)Void() (C) functionQ (D)A11
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
292
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
16. A _______ pointer points to a heap-dynamic variable that has been de-allocated.
18. Often, typedefis used in combination with ______________ to declare a synonym (or an
293
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
294
C PROGRAMMING & DATA STRUCTURES
COURSE - MATERIAL
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