Professional Documents
Culture Documents
Cnotesby
Cnotesby
C LANGUAGE CONTENTS
CHAPTER - I
Basic structure of C program
C tokens
Data types and sizes
Declaration of variables
Assigning values
Operators
Type conversions,
Expressions and evaluation
Input-Output statements
CHAPTER - II
If and switch statement,
While
Do-While
For statement
.CHAPTER – III
One dimensional & two dimensional arrays
Strings and String handling functions
Functions, Recursive functions, Storage classes, and Scope rules
CHAPTER - IV
Pointers, Pointers and Arrays, Pointers and function arguments,
Pointers to functions.
Structures
Unions
CHAPTER – V
Console & File I/O
prepared by :M V B REDDY
Subject: C and Data Structures
UNIT-I
Introduction
Now a days computers are playing very vital role in each and every
field of problem solving. The communication medium between a computer and a human
being is a typical 'language' i.e.. Humans are able to communicate with the computer
system in some form of language. There are basically three types of languages viz..
Machine Understandable Language. Assembly Level Language and High Level
Language. There are number of high level languages developed in the past three decades
like FORTRAN, Pascal and Basic, C Language etc. Clearly, no other language has had so
much of influence in the computing as 'C'-language. Evolution of 'C'- as a programming
language has made application development very easy.
ALGORITHM
An algorithm is a method of representing the step-by-step procedure for solving a
problem. An algorithm is useful for finding the right answer to a problem or to a difficult
problem by breaking the problem into simple cases.
An algorithm must possess the following properties:
i) Finiteness : An algorithm should terminate in a finite number of steps.
ii) Definiteness : Each step of the algorithm must be precisely stated.
iii) Effectiveness : Each step must be effective, in the sense that it should be easily
convertible into program statement and can be performed exactly in a finite amount
of time.
iv) Generality : The algorithm should be complete in itself so that it can be used to
solve all problems of a given type for any input data.
v) Input/Output : Each algorithm must take zero, one or more quantities as input data
and yield one or more output values.
Flow chart
Flow chart is diagrammatic representation of an algorithm. It is built using
different types of boxes of symbols. The operation to be performed is written in the box.
prepared by :M V B REDDY
Subject: C and Data Structures
All symbols are interconnected by arrows to indicate the flow of information and
processing.
Following are the standard symbols used in drawing flowcharts. (see in next page)
Oval Terminal Start/stop/begin/end
symbol
Parallelogram Input/Output Making data available
for processing (input) or
recording of the
processed
information(output)
Rectangle Process Any processing to be
performed. An
assignment operation
normally represented by
this symbol
Diamond Decision Decision or switching
type of operations that
determines which of the
alternative paths is to be
followed.
Circle Connecter Used for connecting
different parts of flow
chart.
Arrow Flow Joins two symbols and
also represents
executions flow.
Bracket with broken Annotation Descriptive comments
line or explanations
Double sided Predefined Modules or subroutines
rectangle process given elsewhere
prepared by :M V B REDDY
Subject: C and Data Structures
Introduction to C:
1) It is a robust language, whose rich set of built-in functions and operators can
be used to write any complex program.
2) Programs written in C are efficient and fast. This is due to its variety of data
types and powerful operators.
3) C’s code is very portable, in the sense that it is easy to adapt software written
for one type of computer or operating system to another type.
4) C has very small key words (only 32). Its strength lies in its built-in functions.
These built-in functions can be used for developing programs.
5) C language is well suited for structured programming, thus requiring the user
to think of a problem in terms of functions (or) blocks. A proper collection of
these functions would make a complete program. This modular structure
makes program debugging, testing and maintenance easier.
6) Another important feature of C is its ability to extend itself.
Basically a C program is a collection of functions that are supported by the
C library. We can add our own functions to the C library. With the availability of
a large number of functions, the programming task becomes simple.
prepared by :M V B REDDY
Subject: C and Data Structures
Before discussing any features of C, we shall look at some sample C program and
analyze and understand how they work.
main()
{
Printf(“welcome to GITAM”)
}
Explanation:
i) main():
i) The ‘main()’ is a special function used by the C system to tell the computer
where
the program starts.
ii) Every program must have exactly one main function.
iii) Opening brace ‘{‘ and closing brace ‘}’ are the delimiters of any function.
iv) All the statements between these two braces are called as function body.
v) The lines beginning with /* and ending with */ are known as comment lines.
These lines are not executable statements and therefore anything between /* and */ is
ignored by the compiler.
ii) printf() function:
printf is a predefined, standard C function for printing output. ‘Predefined’ means
that it is a function that has already been written and compiled, and linked together with
our program at the time of linking.
The printf function causes everything between the starting and the ending
quotation marks to be printed out. In the above example, the out put will be
welcome to RGMCET
Every statement in C should end with a semicolon(;) mark.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
that the construction crews actually begin work. Programming requires this same pains
taking processes, with the end result standing or falling by the amount of care and
attention invested in the planning stage.
5. Selecting test data:
How can one ensure that once a program is eventually working the results it
produces are ‘correct’? The answer is simple commonsense. Try the program out on
some data to which the answers have been worked out in advance. If they match, the
program should be all right. Selecting effective test data is a serious exercise and the
more significant the program, the more care needs to the taken in the selection.
6. The actual coding (Implementation):
At this stage, one can begin to code the detailed program designs into program
instructions of a given language. If all the previous steps have been completed with due
diligence, this coding should be almost ‘automatic’. The chances are high that a fairly
successful program will result first time around. Although it may still contain bugs, these
should be fewer and relatively easy to identify and correct.
7. Testing:
The program can be tested with the test data, results checked and any errors
amended. When all is correct the program can be released and set to work on live data.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
7. ‘C’ programs can be run on any of the different computer with little or no
alteration.
8. ‘C’ is widely available commercial ‘C’ compilers are available on most personal
computers, mini and main frames.
9. ‘C’ language allows reference to a memory location with the help of pointer
which holds the address of the memory location.
10. ‘C’ language allows dynamic allocation of memory i.e. a program can request the
operating system to allocate/release memory.
11. ‘C’ language allows manipulations of data at the lowest level i.e. bit level
manipulation. This feature is extensively useful in writing system software
programs.
12. ‘C’ is a case sensitive language.
Basic structure of C program:
A ‘C’ program can be viewed as a group of building blocks called functions. A
function is a sub-routine that may include one or more statements designed to perform a
specific task. To write a ‘C’ program we first create functions and then put them together.
A ‘C’ program may contain a one or more sections as given below.
prepared by :M V B REDDY
Subject: C and Data Structures
Function n
1) The documentations section consists of comment lines giving the name of the
program ,the author and other details which the programmer would like to use later.
these comments beginning with the two Characters \* and ending with the characters*\.
2) The link section provides to the compiler to link functions from the system library
prepared by :M V B REDDY
Subject: C and Data Structures
/*Simple C Program */
main()
{
/*prints the string */
printf(“welcome to C world\n”);
}
The first and fourth lines are commented lines. These are used in a program to
enhance its readability and understanding .the line beginning with \* and ending
with*\ are known as comment lines. Comment lines are not executable statements
and anything between \*and *\is ignored by the compiler. These comment lines
can be inserted wherever we want, it cannot be nested i.e. cannot have comments
inside comments.
The second line informs the system that the name of the program is main() and
the execution begins at this line. The main () is a special function by the C system
to tell the computer where the program starts. Every program must have exactly
one main function. If we use more than one main function cannot know where the
program begins.
The opening brace “{“ in the third line marks the beginning of the function
main and the closing brace”}” in the last line indicates the end of the function .
the statements between these two braces
The function body contains two statements, one of them is printf line is an
executable statement. It is a predefined standard C function. The printf function to
be printed out everything which appears in between quotations marks, here the
output will be ”welcome to C world”.
prepared by :M V B REDDY
Subject: C and Data Structures
C Tokens
The smallest individual units are called tokens. C programs are written using
these tokens and the syntax of the language. The C has six types of tokens as shown
below:
1. key word
2. identifiers
3. constants
4. operators
5. strings
Character set:
The characters that can be used to form the words, numbers and expressions
depend upon the computer on which the program is run. The characters in C are grouped
into four categories.
1. letters
2. digits
3. special characters
4. white spaces
prepared by :M V B REDDY
Subject: C and Data Structures
With these characters are combined to form data types, constants, variables and
key words
1) Key words and identifiers:
In ‘C’ every word is classified into either a key word or an identifier. All key
word have fixed meaning cannot be changed. Keywords serve as a basic building block
for program statements. All the keywords must be written in lower case.
Keywords are the tokens used in C program which have predefined meaning and
these meanings cannot be changed by the programmer. There are 32 keywords. They are
also called as Reserved words. We cannot use them for any other purpose.
Standard key words:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for Signed void
default goto sizeof volatile
do if static while
2) Identifiers:
Identifiers refer to the names of the variable, function and arrays. These are user
defined names and consists of sequence of letters and digits.
Rules for giving name to an identifier:
1. Identifiers can consist of letters and digits, must begin with in the alphabets or
underscore, should not contain white space.
2. Both upper case and lower case are permitted although an upper is not equal to
the corresponding lower case letter.
3. It cannot be a keyword.
4. An identifier can be of any length while most compilers of ‘C’ recognize only the
first eight characters.
prepared by :M V B REDDY
Subject: C and Data Structures
Constants
Numeric Character
For example in the equations 5x+2y=45 since 5, 2 and 45 cannot change , these are
called constants, where as the quantity X&Y can vary or change hence these are called
variables .
prepared by :M V B REDDY
Subject: C and Data Structures
Numeric constants:
i) Integer constants: It refers to a sequence of digits, it has to fallow the below rules:
1. Integer constants must have at least one digit
2. It must not have a decimal point
3. It could be either positive or negative
4. If no sign precedes an integer constant it is assumed to be positive
5. No commas, blank space are allowed.
6. The allowable range for integer constants is -32768 to +32767 (16-bit machine)
integer constants can be specified in decimal, octal, or hexa decimal notation.
i) A decimal integer constant:
It consists of sequence of one or more decimal digit 0 through 9 preceded by an
optional – (or) + sign.The first digit of the sequence cannot be 0 unless the decimal
integer constant is 0.
Ex: 0 276 3412 31467 -7123
Note: Embedded spaces, commas, and non-digit characters are not permitted between
digits.
Ex: 12 727
23,879 are illegal numbers.
$1772
ii) An Octal Integer constant: It consists of any combination of digits from the set 0
through 7,with a leading 0.
Ex: 012
07134
07777
iii) A hexa Decimal integer constants:
It consists of the digit 0, followed by one of the letter x (or) X, followed by a
sequence of one more hexadecimal digits 0 through 9 or letter a through f (or) A through
F represent the numbers 10 through 15.
Ex: 0X1F
0XABC
0X9a2F
prepared by :M V B REDDY
Subject: C and Data Structures
0XFFFF
Note: we rarely use octal and hexa decimal numbers in programming.
Real Constant: A real constant are sequence of digits with a decimal point(fractional
part) like 45.382.Such numbers are called real(or floating point) constants.
The scientific notation is often used to express numbers that are either very small
or very large.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
Variables: A variable is a data name which can be used to store a data value and a
variable may take different values at different times, during execution.
For example, in the equation 5X+2Y = 45 since 5,2 and 45 cannot change, these
are called constants, where as the quantities X &Y can vary or change hence these are
called variables.
Rules for constructing variable names:
1. A variable name is any combination of alphabets, digits and the
underscore character. ANSI standard recognizes a length of 31 characters.
However, the length should not be normally more than 8 characters, since
only the first 8 characters are treated as significant by many compilers.
2. The first character in the variable name must be an alphabet.
3. No commas or blank spaces allowed.
4. No special symbol other than an underscore can be used
Ex: bas_pay , net_salary , month etc.
5. Uppercase and lowercase are significant. That is, the variable Amount is
not the same as amount or AMOUNT.
6. Variables name should not be a keyword.
prepared by :M V B REDDY
Subject: C and Data Structures
Data types:
Each data type has predetermined memory requirement and an associated range
of legal values. Every programming language has its own data types. Storage
representations and machine instructions to handle constants differ from machine to
machine.
ANSI C supports four classes of data types.
1. primary (or fundamental) data types
2. user defined data types
3. derived data types
4. Empty data set.
int short int long int int short int long int
Integers:
C provides three different types of integers they are int, short int and long int. the
difference between these three integers is the number of bytes. The variables of these
types occupy and subsequently the range of values. A short int occupies 2 bytes, an int
occupies 2 bytes and the long int occupies 4 bytes.
prepared by :M V B REDDY
Subject: C and Data Structures
Float:
Like integers floats are divided into three types. They are float, double and long
double. The difference between these three floats are the number of bytes, the variable of
these types occupy and subsequently the range of values. A float occupies 4 bytes, a
double occupies 8 bytes and the long double occupies 10 bytes.
Type Description Size Range
Float Single precession 4 3.4E-38 to 3.4E+38
Double Double precession 8 1.7E-308 to
1.7E+308
Long double Extended precession 10 3.4E-4932 to
3.4E+4932
Characters:
A char is a data type which can store an element of machine character set. A
single character can be defined as a character (char) type data. Characters are usually
stored in 8 bits (1 byte) of internal storage. The character set is usually the ASCII. These
are two types, they are signed and unsigned characters. The differences between these
two types are the range of values. Both will occupy one byte.
prepared by :M V B REDDY
Subject: C and Data Structures
Declaration of variables:
This instruction is used to declare the type of variable used in the program. Any
variable used in the program must be declared before using it in any statement. The type
declaration statement is usually written at the beginning of the C program.
Syntax:
Data_type var1,var2 … var n;
Ex: int I, count;
Float price, salary;
Char c;
Scope of variables: scope of variables implies to the availability with in a program.
Variables have two types of scopes: local and global.
A variable with a global scope is accessible to all statements in a program but the
one with local scope in restricted to be accessed by only certain selected statements in the
program, in which it is defined.
Global variables are declared outside all functions where as local variables are
defined inside a function.
where type refers to an existing data type and identifier refers to the new name given to
the data type.
prepared by :M V B REDDY
Subject: C and Data Structures
Ex:
typedef int sno;
typedef float salary;
Here sno symbolizes int and salary symbolizes float. These can be used to declare
variables as follows.
sno c1,c2;
salary e1,e2;
Note: The main advantage of typedef is that we can create meaningful data type names
for increasing the readability of the program.
Another user defined data type is enumerated data type provided by ANSI .
The identifier is a user defined enumerated data type which can be used to declare
variables that can have one of the values enclosed within the braces. After that we can
declare variables to be of this new type.
prepared by :M V B REDDY
Subject: C and Data Structures
There are some derived data types which are supported by C such as arrays,
functions, structures, and pointers. Derived data types will be explained later.
It is also known as void data types. It indicates that no other data types has been
used with the given identifier.
prepared by :M V B REDDY
Subject: C and Data Structures
Arithmetic operators: the arithmetic operators that we come across in ‘C’ language are
+, -, *, /and %. All of these operators are called ‘binary’ operators as they operate on two
operands at a time. Each operand can be an int or float or char.
Arithmetic operators
Operator Meaning
+ Addition or unary plus
- Subtraction or unary
minus
* Multiplication
/ Division
% Modulo division.
Ex:
int x, y, z;
z=x+y;
prepared by :M V B REDDY
Subject: C and Data Structures
z=x-y;
z=x*y;
z=x/y;
If both operands are integers, then the expression called an integer expression
and the operation is called integer arithmetic. Integer arithmetic always yields an integer
value.
If both operands are real, then the expression is called a real expression and the
operation is called real arithmetic. A real operand may be either in decimal or
exponential notation. Real arithmetic always yields a real value. The modulus (%)
operator cannot be used for real operands.
If one of the operand is real and other is integer then the expression is called
mixed-mode arithmetic expression. Here only the real operation is performed and the
result is always in real form.
Assignment Operators:
Values can be assigned to variables using the assignment operator ‘=’ as
fallows:
Variable_name=constant;
Ex: balance=1278;
Yes=’x’;
C permits multiple assignments in one line. For example,
balance=1278;Yes=’x’; are valid statements.
An assignment statement implies that the value of the variable on the left of the
‘equal sign’ is set equal to the value of the quantity (or the expression) on the right.
The statement year=year+1; means that the ‘new value’ of year is equal to the
‘old value’ of year plus 1.
It is also possible to assign a value to a variable at the time the variable is
declared. This takes the below form:
data type var_name=constant;
prepared by :M V B REDDY
Subject: C and Data Structures
Operator Meaning
a = a+1 or Adds one to a and
a+=1 Assigns the value to a
a = a -1 or Decrements a by 1
a-=1 And assigns it to a
a = a /(b+5) Divides a by b+5 and
or
a / = (b+5) Assigns result to a
a = a *(b+5) Multiplies b+5 with a
or
a * = b+5 And assigns result to
a
prepared by :M V B REDDY
Subject: C and Data Structures
Relational operators
Operator Meaning
< is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Unary operator:
C includes a class of operator that act upon a single operand to produce a new
value. Such operators are known as Unary operators. Unary operators usually preceded
their single operand. Most commonly used unary operators are
1.Unary minus operator
2.Increment and Decrement operators.
Unary minus:
Where a minus sign precedes numerical constants, variables or an expression.
Where as the unary minus operation is different from the arithmetic operator, which do
Dot Subtraction. Thus a negative number is actually an expression consisting of unary
minus operator.
Ex:
x=-y;
Increment and Decrement operators:
prepared by :M V B REDDY
Subject: C and Data Structures
The increment (++) and Decrement (--) operators are add one and subtract one.
These are unary operators since they operate on only one operand. The operand has to be
a variable. The increment or decrement of the value either before or after the value of the
variable is used. If the operator appears before the variable, it is called a prefix operator.
If the operator appears after the variable, it is called a postfix operator.
Operator Meaning
a ++ Post increment
++a Pre increment
a-- Post decrement
--a Pre decrement
a++ and ++a is the same when the statements are independent like
a=5; a=5;
a++; ++a;
In the both cases a value will be 6.
When the prefix ++ (or--) is used in an expression, the variable is incremented (or
decremented) first and then the expression is evaluated using with the new value of the
variable. Where as the postfix ++ (or --) is used in an expression, the expression is
evaluated first using with the original values of the variables and then the variable is
incremented (or decremented) by one.
prepared by :M V B REDDY
Subject: C and Data Structures
Logical operators:
Logical operators are used to combine two or more relations. The logical
operators are called Boolean operators. Because the tests between values are reduced to
either true or false, with zero being false and one being true.
Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Operands Results
Exp 1 Exp 2 Exp 1 && Exp Exp 1 || Exp 2
2
prepared by :M V B REDDY
Subject: C and Data Structures
0 0 0 0
0 Non zero 0 1
Non zero 0 0 1
Non zero Non zero 1 1
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
~ Ones complement
& 0 1
0 0 0
1 0 1
prepared by :M V B REDDY
Subject: C and Data Structures
Ex:
X=0000 0111(=7)
Y=0000 1000(=8)
Z=X&Y=0000 0000(=0)
| 0 1
0 0 1
1 1 1
Ex:
X=0000 0111(=7)
Y=0000 1000(=8)
Z=X|Y=0000 1111(=15)
One’s complement:
For a binary number if we take one’s complement all zero’s become 1 and
one’s become 0’s.
Ex:
X=0001;
~X=1110;
prepared by :M V B REDDY
Subject: C and Data Structures
The conditional operator pair “? and :” are sometimes called ternary operator
since they take three operands, and it is condensed form of an if-then-else C statement.
The general form is:
exp 1? exp 2: exp 3;
The operator ?: works as fallows: exp1 is evaluated first. If it is nonzero(true), then the
expression exp2 is evaluated. If exp1 is false, exp3 is evaluated. Note that only one of the
expression is evaluated.
Ex:
y=(x>5? 3:4) is equivalent to if(x>5)
then
y=3;
else
y=4;
Special operators:
i) Comma operator:
The comma (,) operator permits two different expressions to appear in
situation where only one expression would ordinarily be used. The expressions are
separated by comma operator.
Ex:
c= (a=10, b=20,a+b);
Here firstly value 10 is assigned to a followed by this 20 is assigned to b and then
the result of a+b is assigned to c.
Size of operator:
The size of operator returns the number of bytes the operand occupies in
memory. The operand may be a variable, a constant or a data type qualifier.
Ex:
sizeof(int) is going to return 2
Address of operator:
prepared by :M V B REDDY
Subject: C and Data Structures
The address of operator (&) returns the address of the variable. The operand
may be a variable, a constant.
Ex:
m=&n;
Here address of n is assigned to m. This m is not a ordinary variable, it is a variable
which holds the address of the other variable (i.e., pointer variable).
Precedence of operators:
While executing an arithmetic statements which has two or more
operators, we may have some problem about how exactly does it get executed. To answer
these questions one has to understand the precedence of operators. The order of priority
in which the operations are performed in an expression is called precedence. The
precedence of all operators is shown below.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
Expressions:
An expression is a combination of variables, constants and operators arranged
as per the syntax of the language.
Ex:
Evaluations of Expressions:
Expressions are evaluated using an assignment statement of the form
Variable=expression;
The expressions are evaluated first and the result then replaces the previous value
of the variable on the left hand side. All variables used in the expression must be assigned
values before evaluation is attempted.
Examples of evaluation statement are:
x=b/c*a;
y=a-b/c+d;
z=a+b-c;
Rules for Expression Evaluation:
First parenthesized sub expressions from left to right be evaluated.
If parentheses are nested, the evaluation begins with the innermost sub-
expression.
When parentheses are used, the expressions within parentheses assume
highest priority.
The precedence rule is applied for evaluating sub-expressions.
The associativity rule is applied when two or more operators of the same
precedence level appear in a sub-expression.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
The final result of an expression is converted to the type of variable on the left of
the assignment operator before assigning the value to it.
However, the fallowing changes are introduced during the final assignment:
i) float to int causes truncation of the fractional part.
ii) double to float causes rounding of digits.
iii) long int to int causes dropping of the excess higher order bits.
Casting a value:
We have just discussed how C performs type conversions automatically.
However, there are instances when we want to force a type conversion in a way that is
different from the automatic type conversion.
Input/Output Operators:
‘C’ language has no provision for either receiving data from any of the input
devices such as keyboard etc., or for sending data to the output devices like VDU. Hence
‘C’ manages this with then help of standard library functions. A program using these
functions must include the standard header file <stdio.h> in if using the directive.
#include<stdio.h>
Types of I/O:
The input/Output functions are classified into three categories.
1. Console I/O functions: Functions to receive input from keyboard and write
output to VDU.
2. Disk I/O functions: Functions to perform I/O operations on a floppy or Hard
Disk.
3. Port I/O functions: Functions to perform I/O operations on various ports (serial
and parallel).
An input/output functions can be accessed from any where within a program by
simply writing the function name followed by a list of arguments enclosed in parentheses.
prepared by :M V B REDDY
Subject: C and Data Structures
#include<stdio.h>
main()
{
char ch;
printf(“Hit any key!:”);
getch(); /*character input with echo*/
printf(“Hit any key!:”);
getche (); /*character will be echoed on the screen*/
}
getchar ();
It is very similar to the getche () and getch () functions echoing the character you
type on the screen, but requires enter key to hit following the character you typed.
prepared by :M V B REDDY
Subject: C and Data Structures
#include<stdio.h>
main()
{
char ch;
printf(“Hit any key!:”);
ch=getchar();
putch(ch);
}
#include<stdio.h>
main()
{
char name[100];
puts(“Enter a string”);
gets(name);
puts(name);
}
prepared by :M V B REDDY
Subject: C and Data Structures
Input : scanf()
Output : printf()
The above two functions are used to supply input from keyboard in a fixed
format and obtain output in a specified format on the screen.
printf function:
Output data can be written from the computer on to a standard output device
using the library function printf. This function can be used to output any combination of
numerical values, single character and strings.
The general format is:
printf (“control string”, arg1, arg2, arg3………);
Where the control string refers to a string contains formatting information. When
printf is called it opens the format string and reads a character at a time. If the character
reads % or \ it does not print it but reads the character which is immediately followed by
that % and \ have a special meaning to printf.
Format descriptors:
%d for int and short int
%ld for long int
%u for unsigned int and unsigned short int
%lu for long unsigned int
%f for float
%lf for double
%Lf for long double
%c for char
%s for string
%o for octal
%x for hexa decimal
prepared by :M V B REDDY
Subject: C and Data Structures
Escape Sequences:
\n new line
\t horizontal tab
\v vertical tabulator
\a to beep the speaker
\’ single quote
\” double quotes
\? Question mark
\\ back slash
\0 NULL
prepared by :M V B REDDY
Subject: C and Data Structures
printf(“i(%%o)=%o\n”,i);
printf(“i(%%x)=%x\n”,i);
printf(“i(%%#o)=%#o\n”,i);
printf(“i(%%#x)=%#x\n”,i);
printf(“i(%%6d)=%6d\n”,-i);
}
Output:
i = 3214
i(%3d) = 3214
i(%7d) = bbb3214
i(%-7d) = 3214bbb
i(%010d) = 0000003214
i(%.10d) = 0000003214
i(%o) = 6216
i(%x) = e8e
i(%#o) = 06216
i(%#x) = 0xe8e
i(%6d) = b-3214
prepared by :M V B REDDY
Subject: C and Data Structures
The following example program illustrates the output of an real number in different
formats
prepared by :M V B REDDY
Subject: C and Data Structures
i(%6.8f)=2500.32104492
i(%2.2f)=2500.32
i(%10.2e)=2.50e+03
i(%09.2f)=002500.32
i(%9.2f)=2500.32
i(%012.2f)=000002500.32
i(%12.2f)=2500.32
i(%8.2f)=2500.32
i(%#10.0f)=2500
i(%e)=2.500321e+03
i(%*.*f82)=2500.32
prepared by :M V B REDDY
Subject: C and Data Structures
printf(“name=%*s\n”,2,name);
printf(“name=%20.10s\n”,name);
printf(“name=%-20.10s\n”,name);
printf(“name==.5s\n”,name);
}
Output:
ch=S
ch=bbS
ch=bbbbbS
name=SHREETECH Computers
name=SHREETECH Computers
name=SHREETECH Computers
name=bbbbbbbbbbSHREETECH
name=SHREETECHbbbbbbbbbb
name=SHREE
Scanf function:
This function can be used to read any combination of numerical values, single
character and string.
The general format is:
scanf(“control string”,arg1,arg2,arg3,………..);
Here the scanf function gets the value from user and store the value in the address
of the variable ‘n’, which is represented as &n. Hence, when we use ‘&’ symbol we
prepared by :M V B REDDY
Subject: C and Data Structures
refers to the address of the variable. scanf() has got its own limitations. Though both
scanf() & gets are used for inputting a string, scanf() will not allow to input a string with
blank spaces.
CONTROL STATEMENTS
1. Non-iterative statements:
The following are the non-iterative statements
a) Simple if statements
b) If else statement
c) Nested if-else statement
d) else-if statement
e) Ternary operator
f) Switch statement.
Non-iterative statements:
i) Simple If statements:
The if statements is used to specify conditional execution of program statements, or
a group of statements enclosed in braces
The general format is:
If (condition)
Statement;
Ex:-
prepared by :M V B REDDY
Subject: C and Data Structures
#include <stdio.h>
main()
{
int x;
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
}
else
{
statement 4;
}
}
statemnts5;
Ex:
/* Program to find out the maximum number from the given three numbers*/
#include<stdio.h>
main()
{
int x,y,z max;
printf(“enter first number”);
scanf(“%d”,&x);
printf(“enter second number”);
scanf(“%d”,&y);
printf(“enter third number”);
scanf(“%d”,&z);
if(x<y)
{ if (y<z)
max=z;
else
max=y;
}
else
{
if(x<z)
max=z;
else
prepared by :M V B REDDY
Subject: C and Data Structures
max=x;
}
printf(“max number of %d%d%d is :%d \n”,x,y,z,max);
}
Output:
Enter first number:8
Enter second number:23
Enter third number:9
Max number of 8 23 9 is :23
prepared by :M V B REDDY
Subject: C and Data Structures
if(c>’a’&&c<=’z’)
printf( “the given character is lowercase character\n”);
else if(c>=’0’&&c<=’9’)
printf(“the given character is uppercase character\n”);
else
printf(“the given character is special character\n”);
}
Output
Enter any character:7
The given character is DIGIT
Ternary operator:
C provides condition evaluation operator called the ternary operator in the from of
the? Symbol
The general format
exp1? exp1: exp2;
The ? Operator evaluates the expression1, if it is true it returns exp1 and returns exp2
otherwise.
Ex :-
If(n>0)
N=n>0?n+10:-n; (or) n+=10;
Else
N=-n;
/* program to find out the maximum number from the given two numbers by using
ternary operator */
#include<stdio.h>
main()
{
int x,y,max;
printf(“enter a first number”);
prepared by :M V B REDDY
Subject: C and Data Structures
scanf(“%d”,&x);
printf(“enter a second number”);
scanf(“%d”,&y);
max=x>y?x:y);
printf(“max number of %d%d is :%d\n”, x, y, max);
}
OUTPUT:
Enter first number: 43
Enter second number: 12
Enter third number: 43
Switch statement:
“switch” statement works in same way as “if else – if” but it is more elegant.
The switch statement is a special multi-way decision maker that tests whether an
expression matches one of a number of constancy values, and branches accordingly.
Switch differs from if else – if because switch can test for only equality, whether if can
evaluate logical expression. The ‘switch’ statement is often used to process keyboard
commands like menu options.
The general format:
Switch (expression)
{
case ‘constant exp 1’:
Statement 1;
break;
case ‘constant exp2’:
statement 2;
break;
case ‘constant exp3’:
statement 3;
break;
prepared by :M V B REDDY
Subject: C and Data Structures
default:
statement n;
break;
}
Note that in the above structure switch, case, break and default are C keywords.
EX:
/*Program to demo on Switch statement*/
#include<stdio.h>
main ()
{int i, j,rst;
char opt;
printf (“enter first number: ”) ;
scanf (“%d”,&x);
printf(“enter second number: “);
scanf (“%d”,&y);
printf (“enter your option + - * / % : “);
scanf (“%c”,&opt);
switch (opt)
{
case ‘+’:printf(“%d + %d = %d \n”,x,y,x+y);
break;
case ‘-’: printf (“%d - %d = %d \n”,x,y,x-y);
break;
case ‘*’: printf (“%d * %d = %d \n”,x,y,x*y);
break;
case ‘/’:printf (“%d / %d = %d \n”,x,y,x/y);
break;
case ‘%’: printf (“%d % %d = %d \n”,x,y,x%y);
break;
prepared by :M V B REDDY
Subject: C and Data Structures
OUTPUT:
Enter first number: 12
Enter second number: 8
Enter your option + - * / % : +
12+8 =20
while Loop:
The while loop in the C starts with the keyword while, followed by a
parenthesized Boolean condition has a set of statements which constitute the body of the
loop.
The general format:
while(expression)
{
Statement 1;
Statement 2;
Statement 3;
Statement n;
}
After executing whatever statements are prior to the while loop, you arrive at the
while loop, As soon as execution reaches the while loop, the condition specified is
tested. It is found to be true, you enter the body of the loop, execute the body through out
and once you reached the closing brace of the body you automatically loop back to the
top, test the condition freshly now, and if it is true re-enter the body and so on. When the
controlling condition of the while loop becomes false, you Break out of the while loop
and start executing whatever statement are subsequent to that.
EX:
prepared by :M V B REDDY
Subject: C and Data Structures
Statement n;
}while(expression);
prepared by :M V B REDDY
Subject: C and Data Structures
As soon as execution reaches the do-while loop you enter the body of the loop and
executes the statements present in the body. Once you reach the while, the expression
specified is evaluated. If it is found to be true, you automatically loop back to the top and
re-enter the body of the loop. If at the time of testing the condition evaluates as false, you
Break out the do-while loop
EX:
/*Factorial of the given number by using the do-while loop*/
#include<stdio.h>
main()
{
int x,i=1,rst=1;
printf (“Enter any integer number \n “);
scanf (“%d”,&x);
do
{
rst=rst*i;
i++;
}while(i<=x);
}
for loop:
This is used when the statements are to be executed more than once .This is the
most widely used iteration construct.The for loop supported by C is much more powerful
than its counterpart in other high level languages.
The general format:
for (initialization; expression;increment)
{
statement1;
statement2;
.
.
Statement n;
prepared by :M V B REDDY
Subject: C and Data Structures
}
The for loop starts with the keyword for. The keyword for is followed by a
parenthesized, what is called header. This is followed by the body of loop which typically
is a set of statements enclosed between braces. The header of the for loop consists of 3
portions; a set of statements to be executed initially before actually entering the loop, an
expression that will acts as the controlling condition of the loop and finally incrementing
or decrementing.
Ex:
/*Factorial of the given number by using for loop*/
#include<stdio.h>
main ()
{
int x,i,rst=1;
printf(“Enter any integer number:”);
scanf(“%d”,&x);
for (i=1;i<=x;i++)
rst=rst*1;
printf(“Factorial of %d is:%d”,x,rst);
}
Output:
Enter any integer number :5
Factorial of 5 is :120
Comma operator: Comma operators are basically used in for loops to have more than
initialization and increment statements.
The general format:
for(exp1,exp2:exp3;exp4,exp5)
{
statements;
}
prepared by :M V B REDDY
Subject: C and Data Structures
Break &continue: C provides two statements –break and continue using which the
normal behavior of a loop can be altered. We already have used the break statement in
switch statement. It can be also be used inside a while loop, a for loop and do-while loop.
It causes control to break out the loop. Because of its nature a break will always be
conditional (attached to an if).
The general format:
while(1)
{
/*do something*/
if(some condition)
Break;
/*do something*/
}
The continue statement whenever executed causes the rest of current iteration to
be skipped and causes the next iteration to begin, subjecting of course to the truth of the
controlling condition.
The general format:
while(exp)
{
/*do something*/
if(some condition)
continue;
/* do something*/
}
exit():
Exit() is a standard library function used to terminate the program execution.
The general format:
exit(argument);
goto :
C supports the goto statement to branch unconditionally from one point to
another in the program. Although it may not be essential to use the goto statement in a
prepared by :M V B REDDY
Subject: C and Data Structures
highly structured language like C, there may be occasions when the use of goto might be
desirable.
The goto requires a label in order to identify the lace where the branch is to be
made. A label is any valid variable name, and must be followed by a colon. The label is
placed immediately before the statement where the control is to be transferred.
The general format:
Key words:
if
switch
while
do while
for
goto
continue
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
A) ! B) != C)~ D) ==
Summary:
The basics of C language are exposed in this unit. We now studied about
various operators and studied about the formatted functions and aware of decision
making, looping statements.
UNIT-II
Objective:
prepared by :M V B REDDY
Subject: C and Data Structures
C provides storage classes such as auto, extern, register and static. In this unit we
will discuss the concepts of functions and storage classes and also the C preprocessor,
header files.
Introduction:
Arrays are homogeneous data type, and a group of homogeneous data items that
shared a common name. 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 us to develop concise
and efficient programs.
A particular value is indicated by writing a number called index number or
subscript in brackets after the array name.
prepared by :M V B REDDY
Subject: C and Data Structures
Array properties:
The type of an array is the data type of its elements
The location of an array is location of its first element
The length of an array is the number of data elements in the array
The size of an array is the length of the array times the size of an
element.
Array whose element are specified by one subscript are called single
subscripted or single dimensional array. Analogous array whose elements are
specified by two and three subscripts are called two-dimensional or double
subscripted and three-dimensional or triple-subscripted arrays respectively.
One-dimensional array:
A list of items can be given one variable name using only one subscript and
such a variable is called a single-subscript and such a variable is called a single-
subscripted variable or a one-dimensional array.
If we want to represent a set of five numbers, say (45, 65, 10, 93, 50) an array
variable marks. We may declare the variable marks as follows
int marks[5];
The value to array elements is assigned and stored as follows
marks [0]=45
marks [1]=65
marks [2] = 10
marks [3] =93
marks [4] = 40
Array declaration:
In c an array variable is declared by specifying first the base type of the array ,
then the name of the array variable, and then the number of elements the array will
have should be specified between a pair square brackets ([]). Note that these values
cannot be a variable and has to be an integral constant.
EX:
int marks [100];
float salary [1000];
prepared by :M V B REDDY
Subject: C and Data Structures
Array initialization:
Elements of an array can be assigned initial values by following the array
definition with a list of initializes enclosed in braces and separated by comma.
EX:
int marks [5] = {65, 98, 62, 48, 57};
Defines the array marks to contain five integer elements and initializes marks [0]
to 65, marks [1] to 98, marks [2] to 62, marks [3] to 48 and marks [4] to 57.
If the number of initializes is less than the number of element in the array, the
remaining elements are set zero.
EX:
int m [5] = {3, 4, 8};
int m [5]= {3, 4, 8, 0, 0}; is equivalent to
If initializes have been provided for an array, it is not necessary to explicitly specify
the array length, in which case the length is derived from the initializers.
A character array may be initialized by a string constant, resulting in the first
element of the array being set to the first character in the string, the second element to the
second character, and so on. The array also receives the terminating ‘\0’ in the string
constant.
Ex:
char name [10] =”COMPUTERS”;
char name[10] ={‘c’,’o’,’m’,’p’,’t’,’e’,’r’,’s’,’\0’};
Two-Dimensional arrays:
Till now we discussed the array of variables that can store a list of values.
There will be a situation where we need to store values. In that situation we will go
for two-dimensional arrays
Array Declaration:
The two-dimensional array can be declared by specifying first the base type of
the array, then the name of the array variable, and then the number of rows and
prepared by :M V B REDDY
Subject: C and Data Structures
column elements the array will have should be specified between a pair square
brackets ([] []). Note that this value cannot be a variable and has to be an integer
constant.
GENERAL FORMAT:
Array initialization:
Elements of an array can be assigned initial values by following the array
definition with a list of initializes enclosed in braces and separated by comma.
EX:
int marks [2] [3] = {65, 98, 62, 48, 57, 40};
Defines the array marks to contain six integer elements and initializes marks [0] [3] to
62, marks [1] [1] to 48, marks [1] [2] to 57 and marks [1] [3] to 40.
Strings:
A string as an array of characters. Any constant string defined between double
quotation marks.
Ex: “SHREETECH computers”
Declaration And Initialization:
A string variable is any valid C variable name and is always declared as an array.
General Format:
char variable_name[size]
The size determines the number of characters in string name.
Ex:
char city [25];
char name [50];
When a compiler assigns a character string to a character array, it
automatically supplies a NULL character ‘\0’ at the end of the string. Therefore the
size should be equal to maximum number of characters in the string plus one.
Character array may be initializes when they are declared.
Static char name [10] = “SHEREETECH”
Reading as String:
prepared by :M V B REDDY
Subject: C and Data Structures
The input function scanf() can be used with %s format specification to read a
string.
EX:
char city[20];
scanf(“%s”,city);
Printing a String:
The print function printf () can be used with %s format specification to print a
string.
EX:
char city[20];
scanf(“%s”,city);
printf (“%s”,city);
String Operations:
1. Reading and writing of strings
2. concatenating of strings
3. copying one string into another
4. Comparing Strings.
5. Extracting a portion of a string.
6. Converting the string from lowercase to uppercase.
prepared by :M V B REDDY
Subject: C and Data Structures
If the ASCII value of the character of the first string is less than the second
string it returns –ve. If both strings are equal it returns 0. If the ASCII value of the
character of the first string is greater than a second string then it returns +ve.
iii) strcat (): It is used to concatenate two strings that is it appends one string to
other string
Syntax: strcat (str1, str2)
Here string str2 is appended to the end of the string str1.
iv)strlen (): It is used to count the number of characters in the string.
Syntax: strlen (str1);
v)strlwr (): It is used to convert any upper case letters into the its equivalent lower
case letters.
Syntax: strlwr (str1)
vi) strupr (): It is used to convert any lower case letters into the equivalent upper case
letters.
Syntax: strupr (str1)
FUNCTIONS:
‘C’ programs are compound of a set of functions. The functions are
normally used to divide a large program into smaller programs which are easier to
handle. Each functions normally performs a specific task. Every program must certain
one function named as main where the program always begins execution. The main
program may call other functions with in it may call still other functions .When a
function is called program execution is transferred to the first statement on the called
function. The function is completed when it executes the last statement in the function
prepared by :M V B REDDY
Subject: C and Data Structures
ADVANTAGES:
1.To facilitates topdown modular programming as shown fig. In this programming
style, the high level logic of the over all problem is solved first while the details of the
each lower level function or addressed later.
2.The length of the source program is reduced by using functions at appropriate
places. This factor is particularly critical with microcomputers where memory space
is limited.
3.As mentioned earlier, it is easy to locate and isolate a faulty function for further
investigations.
4.A function may be used by many other programs. This means that a c programmer
can build on what other have already done, instead of starting over, from scratch.
Main program
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
(or)
return(expression);
The first plain return does not return any value, it acts much as the closing brace of the
function, when return is encountered the control is immediately passed back to the calling
function.
VOID FUNCTION: A function need not have a type. If you do not care to return a value from a
function at all, you may specify the return as void. A void function doesn’t return any value and
cannot return any value.
LOCAL VARIABLES: A variable declared inside a function called a local variables. This name
derives from the fact that a variable declared inside a function can be used only inside that
function.
GLOBAL VARIABLES: The variables you declare in the global variable section are called
Global variables or external variables. While the local variable can be used inside the function in
which it is declared. A global variable variable can be used any where in the program.
BLOCK VARIABLES: The variable declared inside any block such variables are called block
variables.
GLOBAL vs LOCAL VARIABLES:
1. Local variables can be used only inside the function of the block in which they are declared. On
the other hand global variables are used through out the program.
3. Global variables get initialized only once, typically just before the program starts
executing. But local variables get initialized each time the function or block containing
their declaration is entered.
prepared by :M V B REDDY
Subject: C and Data Structures
4. The initial that you supplied for a global variable must be a constant, where as a local
variable can contain variable in its initializer.
5. A local variables loses its value the movement the function/block containing it is
exited. So you cannot expect a local variable to retain the value deposited in it the
previous time the function/block was entered. Global variables retain there values
through the program’s execution.
SCOPE OF VARIABLES:
The scope of local variables is limited to the functions in which they are declared,
or in other words these variables are inaccessible outside of the function .Like wise the
scope of the block variables is limited to the block in which they are declared. Global
have a scope that spans the entire source program, which is why they can be used in any
function.
TYPES OF FUNCTIONS:
A function depending on whether arguments are present are not are whether a
value is returned or not, may belong to one of the following
1. Functions with no arguments and no return values.
2. Function with argument and no return values.
3. Function with arguments and return values.
#include<stdio.h>
main ( )
{
printline ( );
power ( );
prepared by :M V B REDDY
Subject: C and Data Structures
printline ( );
}
printline ( )
{
int i;
for (i=0; i<=50; i++)
printf (“_”);
printf (“\n”);
power ( );
{
int x,y,i,r;
printf(“enter the base value:”);
scanf(“%d”,&x);
printf(“enter the power value”);
scanf(“%d”,&y);
r=1;
for(i=0;i<y;i++);
r=r*x;
printf(“%d power%d is:%d\n”,x,y,r);
}
prepared by :M V B REDDY
Subject: C and Data Structures
printline(c);
printf(“the base value”);
scanf(“%d”,&x);
printf(“enter the power value:”);
scanf(“%d”,&y);
power(x,y);
printline(c);
}
printline(ch);
char ch;
{
int i;
for(i=0;i<=50;i++)
Printf(“%c”,ch);
Printf(“\n”);
}
power(a,b);
int a,b;
{
int i,r;
r=1;
for(i=0;i<b;i++);
r=r*a;
printf(“ %d power %d is:%d\n”,a,b,r);
}
#include <stdio.h>
prepared by :M V B REDDY
Subject: C and Data Structures
main()
{
char c;
int x,y;
printf(“enter any character”);
c=getchar();
println(c);
printf(“enter the base value”);
scanf(“%d”,&x);
printf(“enter the power value”);
scanf(“%d”,&y);
printf(“%d power %d is: %d \n “,x,y,power(x,y));
printline(c);
}
printline(ch);
char ch;
{
int i;
for(i=0;i<=50;i++)
printf(“%c”,ch);
printf(“\n”);
}
power(a,b);
int a,b;
{
int i,r;
r=1;
for(i=0;i<b;i++)
r=r*a;
return(r);
}
prepared by :M V B REDDY
Subject: C and Data Structures
STORAGE CLASSES:
To define a variable in C one needs to mention not only its but also its storage
class. In other words , not only do all variables have a data type, they also have a storage
class.
If we do not specify the storage class of a variable in its declaration , the compiler
will resume a storage class dependent on the context in which the variable is used. Thus
C has got certain default storage classes.
The variables may also be categorized, depending on the place of their declaration
, as INTERNAL (local) or EXTERNAL (global). Internal variables are within a particular
function, while external variables are declared outside of any function.
From C compiler point of view, a variable name identifies some physical location
within the computer where the strings of bits representing the variables value stored .
There are some basically two kinds of locations in a computer where such a value may be
kept: memory and CPU register. It is the variables storage class which determines it
which of these two locations the value is stored.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
int m=1000;
function2();
printf(“%d \n”,m);
}
function1()
{
int m=10;
printf(“ %d\n”,m);
}
function2()
{
int m=100;
function1();
printf(“%d\n”,m);
}
Output:
10
100
1000
ii)EXTERNAL VARIABLES: Variables that are both alive and active throughout the
entire program are known as external variables. They are also known as global variables.
Unlike local variables, global variables can be accessed by any function in the program .
External variables are declared outside a function. A program to illustrate the properties
of global variables. Note that variable X is used in all functions. But none except
function2 has a definition for X. Because X has been declared above all the functions, it
is declared as global, any function can use it, and change its value. Then subsequent
function can reference only those new values.
prepared by :M V B REDDY
Subject: C and Data Structures
main()
{
x=25;
printf(“x=%d \n “,x);
printf(“x=%d \n”,function 1());
printf(“x= %d \n”,function2());
printf(“x=%d \n”, function3());
}
function1()
{
x=x+1();
return(x);
}
function2()
{
int x;
x=10;
return(x);
}
function3()
{
x=x+10;
return(x);
prepared by :M V B REDDY
Subject: C and Data Structures
output:
x=25
x=35
x=10
x=45
iii)Static Variable: As the name suggests, the value of static variables persists until the
end of the program. A variable can be declared static using the keyword static.
A static variables may be either an internal type or an external type, depending on the
place of declaration. Internal static variable are those which are declared inside a
function. The scope of internal static variable extend up to the end of the function.
Therefore internal static variables are similar to auto variables, except that they remain in
existence(alive)throughout the remainder of the program.
program to illustration of properties of static variables:
main()
{
int i;
for(i=1;i<=3;i++)
fun();
}
fun()
{
static int x=5;
x=x+3;
printf(“x=%d\n”, x);
}
Output:
x=8
x=11
x=14
A static variable is initialized only once, when the program is compiled, it is never
initialized again. During the first call to fun, x is incremented to 3.Because x is static, this
prepared by :M V B REDDY
Subject: C and Data Structures
value persists and therefore, the next call adds another 3 to x giving it a value of 11. The
value of x becomes 14 when the third call is made.
An external static variable is declared outside of all functions and is available to all
functions in that program. The difference between a static external variable and a simple
external variable is that the static external variable is available only within the file where
it is defined while the simple external variable can be accessed by other files.
iv) Register Variables: We can tell the compiler that a variable should be kept in one of
the machine’s register, instead of keeping in the memory. Since a register access is much
faster than a memory access. Keeping the frequently accessed variables in the register
will lead to faster execution of programs. This is done as follows:
register int i;
Most compilers allow only int or char variables to be placed in the register. Since only a
few variables can be placed in the register. However C will automatically convert register
variables into non-register variables once the limit is reached.
Introduction to Recursion:
The function called by itself is called recursive function and this process often referred as
recursion.
Ex:-main()
{
printf(“welcome to SHREETECH\N”);
main();
}
Important conditions: There are two important conditions that must be satisfied by any
recursive procedure.
1.Each time a procedure calls itself, it must be nearer to a solution.
2.There must be a decision criterion for stopping the computation.
Types of recursion:
There are two types of recursions.
1.The first type concerns recursively defined functions. Example of this kind is the
Factorial function.
2.The second type of recursion is the recursive use of a procedure.
prepared by :M V B REDDY
Subject: C and Data Structures
Key points:
Key words:
Array
String
Actual parameter
prepared by :M V B REDDY
Subject: C and Data Structures
Formal parameter
Function
Recursive Function
Storage class
1) Write about arrays? How arrays can be initialized and declared? Illustrate with
examples?
2) Explain the various operations performed on string and explain the various string
handling functions?
3) What is meant by function? Explain the types of functions?
4) Explain recursive functions with an example?
5) Explain the storage classes in C and also explain the scope rules in detail?
prepared by :M V B REDDY
Subject: C and Data Structures
POINTERS IN ‘C’
Objective:
One of the powerful features of C is its ability to access the memory variables
by their memory addresses. A pointer data type is mainly used to hold memory address.
Pointers are useful to work with memory addresses, to pass values as arguments to
functions, to allocate memory dynamically and to effectively represent complex data
structures. Since arrays store data sequentially in memory, pointers allow a convenient
and powerful manipulation of array elements. This unit introduces pointers and covers
the basic features to work with pointers.
prepared by :M V B REDDY
Subject: C and Data Structures
Introduction:
A pointer is a derived data type in C, it is built from one of the fundamental data
types available in C. Pointers contain memory address as their values. Pointers are
one of the most distinct and exciting features of C language. It has added power and
flexibility to the language. Pointers are used frequently in C.
Need of pointers:
Basically arrays are static. It means that the maximum possible size of the array
has to be declared before it’s use (i.e., at compile time). It is not always possible
to guess the maximum size of an array, because for some applications we need the
size of an array to be changed during the program execution. This can be achieved
by using the pointers. Pointers allows memory allocation and de-allocation
dynamically.
Pointers are used for establishing links between data elements or objects for some
complex data structures such as stacks, queues, linked lists, binary trees and
graphs.
Benefits to the programmers with pointers:
Pointers are more efficient in handling arrays and data tables.
Pointers can be used to written multiple values from a function via
function arguments.
Pointers permit reference to functions and there by facilitating passing of
functions as arguments to other functions.
The use of pointer arrays to character string results in saving of data storage space
in memory.
Pointers allow C to support dynamic memory management.
Pointers provide an efficient tool for manipulating dynamic data structures such
as structures, linked lists, queues, stacks and trees.
Pointers reduce length and complexity of programs.
They increase the execution speed and reduce the program execution time.
prepared by :M V B REDDY
Subject: C and Data Structures
With the help of pointers, variables can be swapped without physically moving
them.
Pointers:
definition:
A pointer is a variable which contains the address of another variable.
Note: both pointer variable data types are same.
Declaration:
data-type *Pointer_ Name:
Here the * tells that variable Pointer _Name is pointer type variable. i.e. it holds the
address of another variable specified by the data-type. Pointer_ Name needs a memory
location .Pointer_ Name points to a variable of type data_ Type.
Consider the following declaration.
int n =20;
This declaration tells the C compiler to:
1. Reserve space in memory to hold the integer value.
2. Associate the name with this memory location.
3. Store the value 20 at this location.
We may represent n’s location in the memory by the following memory map:
n Location Name
20
Value at Location
prepared by :M V B REDDY
Subject: C and Data Structures
main ()
{
int n=20;
printf (“address of n is: %u \n “, &n);
printf (“value of n is: %d \n”, n);
printf (“value of n is: %d”,*(&n));
}
OUTPUT:
Address of n is: 2000
Value of n is: 20
Value of n is: 20
In the first printf ( ) statement ‘&’ is used it is C’s address of operator.
The expression &n returns the address of the variable n, which in this it are 2000. The
third printf ( ) statement we used other pointer operator ‘*’ called ‘value at address’
operator. It returns the value stored at a particular address. The ‘value at address’
operator is also called as‘indirection’ operator. The above program says the value of
*(&n) is same as n.
POINTER EXPRESSIONS:
In the above example &n returns the address of n, if we desire this address can be
collected in a variable by saying
m=&n;
But remember that m is not an ordinary variable like any other integer variable. It is a
variable which contains the address of another variable (n in this case). The following
memory map would illustrate the contents of n and m.
n m
20 65498
prepared by :M V B REDDY
Subject: C and Data Structures
65498 65500
As you can see n’s value is 20 and m’s value is n’s address. Here we can’t use m
in a program with out declaring it. And since m is a variable which contains the address
of n, it is declared as
Int * m;
This declaration tells compiler that m will be used to store the address of an
integer value. In other words m points to an integer.
OUTPUT:
Address of n is: 65498
Address of n is: 65498
prepared by :M V B REDDY
Subject: C and Data Structures
The concept of pointer can be further extended. Pointer we know is a variable which
contains address of another variable. Now this variable itself could be another pointer.
Thus we have a pointer which contains another pointer’s address.
prepared by :M V B REDDY
Subject: C and Data Structures
The Following memory map would help you in tracing out how the program prints
the above output
n m p
20 65496 65498
prepared by :M V B REDDY
Subject: C and Data Structures
to the formal arguments in the called function have no effect on the values of the actual
arguments in the calling function.
#include<stdio.h>
main ()
{
int x, y;
printf (“enter the first value i. e x is :”);
scanf (“%d”, &x);
printf (“enter the second value i.e. y is:”);
scanf (“%d”, &y);
swap(x, y);
printf (“in the main program:\n”);
printf (“x =%d\n”, x);
printf (“y=%d\n”, y);
}
swap (int a, int b)
{
int t;
printf (“in the swap function:\n “);
printf (“x=a=%d\n “, a);
printf (“y =b=%d\n”, b);
t=a;
a=b;
b=t;
printf (“after interchanging:\n”);
printf (“x=a=%d\n”, a);
printf (“y=b=%d\n”, b);
}
prepared by :M V B REDDY
Subject: C and Data Structures
output:
enter first value i.e. x: 43
enter second value i.e. y: 94
x=a=43
y=b=94
after interchanging:
x=a=94
y=b=43
in the main program:
x=43
y=94
SENDING THE ADDRESS OF THE ARGUMENTS (Call by Reference):
In this method the address of the actual arguments in the calling function are
copied into formal arguments of the called function. This means that using the formal
arguments in the called function we can make changes in the actual arguments of the
calling function.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
#include<stdio.h>
main ( )
{
int i;
int a[5]={33, 44, 55, 66, 77}
for (i=0; i<5; i++)
write (&a[i])
}
write (int *n)
{
printf (“%d\n”, n);
}
prepared by :M V B REDDY
Subject: C and Data Structures
POINTER ARITHMETIC:
Suppose i, j, k are stored in memory at address 65490, 65492 &65497 the output
would be
Value of i= 5
Value of j= 5.800000
Value of k= z
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
}
ex2:
#include<stdio.h>
main ()
{
int a [] = {32, 43, 54, 65, 78}, i, *j;
j=&a [0];
for (i=0;i<5;i++)
{
printf (“address = %u”, j);
printf (“element = %d \n”,*j);
j++;
}
}
In the second ex program instead printing address of any location we are stored base
address i.e. a [0] stored in pointer j.
PASSING AN ENTIRE ARRAY TO A FUNCTION:
Let us now see how to pass the entire array to a function rather individual elements.
Consider the following ex:
#include<stdio.h>
main (_)
{
int a [] =p {32, 43, 54, 65, 78};
display (&a [0], 5);
}
display (int *i, int x)
{
int j;
for (j=0; j<5;j++)
{
prepared by :M V B REDDY
Subject: C and Data Structures
Here the display ( ) function is needed to print the array elements. Note that
address of the zeroth element is being passed to the display ( ).
ACCESSING ARRAY ELEMENTS IN DIFFERENT WAYS:
Consider an array num contains {12, 23, 34, 45, 56} elements.
Here we can access the ith element from the array by following notations:
Num [i], * (num + i),*(i+ num), i[num]
EX:
/*ACCESSING ARRAY ELEMENTS IN DIFFERENT WAYS: */
#include<stdio.h>
main ( )
{
int num [] = {12, 23, 34, 45, 56};
int i;
for (i=0;i<5;i++)
{
printf (“address=%u”, &num[i]);
printf (“element=%d”, num[i]);
printf (“%d”, *(num + i));
printf (“%d”,*(i+ num));
printf (“%d\n” i[num]);
}
}
OUTPUT:
Address=65490 Element=12 12 12 12
Address= 65492 Element =23 23 23 23
prepared by :M V B REDDY
Subject: C and Data Structures
Address=65494 Element=34 34 34 34
Address=65496 Element=45 45 45 45
Address=65498 Element=56 56 56 56
main ( )
{
char city [100];
int i, l;
printf (“enter any city name :”);
scanf (“%s”, city);
printf (the given string is :”);
printf (“city”);
}
printf(char *city)
{
while (*city! =’\0’)
{
printf (“%c”,*city);
city++;
}
}
OUTPUT:
Enter any city name: Hyderabad
The given string is: Hyderabad
prepared by :M V B REDDY
Subject: C and Data Structures
#include<stdio.h>
main ()
{
char city [100];
int i, l;
printf (“enter any city name:” );
scanf (“%s”, city);
l=len (city);
printf (“the length of the given string is: %d \n”, l);
}
len (char*city)
{
int l1=0;
while (*city! =’\0’)
{
l1++;
city++;
}
return (l1);
}
OUTPUT:
Enter any city name: Bangalore
The length of the given string is: 9
prepared by :M V B REDDY
Subject: C and Data Structures
Structure pointers:-
The way we can have a pointer pointing to an int, or a pointer pointing to a char ,
similarly we can have a pointer pointing to the struct. Such pointers are known as
‘structure pointers’.
{
char title[25];
char author[25];
int no;
};
struct book b={“SHREETECH C Notes”,”srinivas”,102};
struct book *ptr;
ptr=&b;
printf(“%s %s %d\n”,b.tittle,b.author,b.no);
printf(“%s %s %d\n”, ptr->tittle,ptr->author,ptr->no);
}
Run1:
SHREETECH C Notes Srinivas 102
SHREETECH C Notes Srinivas 102
The first printf() is as usual.The second printf() however is peculiar.We cannot use
ptr.tittle,ptr.author and ptr.no because ptr is not a structure variable but a pointer to a
structure, and the dot operator requires a structure variable on its left.In such cases C
provides an operator -> called an arrow operator to refers the structure elements.
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
Other way round there always exists a possibility that when you run the
program you need to store more than 100 students’ marks, in this case the array would
fall short in size. Moreover there is no way to increase or decrease the array size during
execution, this is done by malloc () and calloc ().
# include <stdio.h>
main ()
clrscr ();
if (marks==null)
prepared by :M V B REDDY
Subject: C and Data Structures
exit ();
sum+=*(marks+i);
for (i=0;i<n;i++)
avg=sum/n;
Here we first ask for the no of students whose marks are to be entered and then
allocate only as much memory as is really required to these marks not byte more , not a
byte a less.The allocation job is done by malloc() function.if it returns NULL the memory
allocation is not at done. If it is successful it returns the address of memory.
prepared by :M V B REDDY
Subject: C and Data Structures
This address we collected is an integer pointer marks. The expression (int*) is used to
typecast being returned as the address is an integer. This typecasting is necessary for
malloc(),by default it returns a pointer to a void.
Here 2 indicates that we wish to allocate memory for sorting integers,since an integer is a
2 byte entry. And 10 indicates that we want to reserve space for storing 10 integers.
Another minor difference between malloc() and calloc() is that by default the memory is
allocated by malloc() contains garbage values, where as that allocates by calloc() contains
all zeros.while using these function to include the file’alloc.h’ at the beginning of the
program.
Points to remember:
Key words:
Address operator
prepared by :M V B REDDY
Subject: C and Data Structures
Indirection operator
Call by reference
prepared by :M V B REDDY
Subject: C and Data Structures
A) &275
B) &a+b
C) &(a*b)
D) All of the above.
prepared by :M V B REDDY
Subject: C and Data Structures
UNIT-IV
Objective:
INTRODUCTION:
We have seen arrays can be used to represent a group of data items that belong to the
same type, such as int or float. However we cannot use an array if we want to represent a
collection of data items of different types using the single name. C supports the constructed
data type known as structures, a mechanism for packing data of different types. The concept of
a structure is analogous to that of a record in many other languages.
EX:
Time Seconds(int),Minutes(int),Hours(float)
Date Day (int),Month(string),Year(int)
Book Author(string),Title(string),Price(float)
Address Name(string),Doornumber(string),Street(string),City(string)
Structures help to organize complex data in a more meaningful way. It is a
powerful concept that we may often need to use in our program design.
STRUCTURES DEFINITION:
A structure in C is heterogeneous compound data type, similar to the records of
data base and PASCAL. It is collection of logically related data items grouped together
under a single name called structure tag. The data items that make up a structure are
known as its members, components, or fields and can be of different type.
THE GENERAL FORMAT:
struct tag
prepared by :M V B REDDY
Subject: C and Data Structures
{
type var1;
type var2;
type var3;
.
.
.
.
.
type varn;
};
prepared by :M V B REDDY
Subject: C and Data Structures
member and a variable are established using a number operator “.” which is also known
as dot operator or period operator. For example , book2.price is the variable
representing the price of book2 and can be treated like any other ordinary variables.
#include<stdio.h>
struct personal
{
char name[20];
int day;
char month;
int year;
float salary;
main()
{
struct personal person;
clrscr();
printf(“ Enter a person details:\n\n”);
printf(“ Enter person name : “);
scanf(“%s”,person.name);
printf(“Enter a person joining day : “);
scanf(“%d”,&person.day);
printf(“Enter a person joining month: “);
scanf(“%d”,&person.month);
printf(“Enter a person joining year: “);
scanf(“%d”,&person.year);
prepared by :M V B REDDY
Subject: C and Data Structures
main()
{
static struct
{
int age;
float height;
}
prepared by :M V B REDDY
Subject: C and Data Structures
student={20,180,75};
………………
………………
………………
}
This assigns the value 20 to student.age and 180.75 to student.height.
Suppose you want to initialize more than one structure variable:
main()
{
struct st_record
{
int age;
float height;
};
static struct st_record student1={20,180,75};
static struct st_record student2={22,177,25};
…………………..
…………………..
}
Another method is to initialize a structure variable outside the function
struct st_record
{
int age;
float height;
}student1={20,180,75};
main()
{
static struct st_record student2={22,177,25};
………..
………..
prepared by :M V B REDDY
Subject: C and Data Structures
ARRAYS OF STRUCTURES:
We may declare an array as structures , each element of the array
representing a structure variable. For example
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
{
student[i].tot=student[i].eng+student[i].tel+student[i].sci;
t.eng=t.eng+student[i].eng;
t.tel=t.tel+student[i].tel;
t.sci=t.sci+student[i].sci;
t.tot=t.tot+student[i].tot;
}
printf(“ STUDENT TOTAL \n\n”);
for(i=0;i<3;i++)
{
printf(“ stu[%d] : %d\n”,i+1,stu[i].tot);
printf(“ SUBJECT TOTAL\n\n”);
printf(“English : %d\n Telugu : %d\n Science : %d\n”,t.eng,t.tel,t.sci);
printf(“\n Grand total : %d\n”,t.tot);
}
ARRAYS WITHIN STRUCTURES:
C permits the use of array as structure member. We can use single or multi-
dimensional array of type int or float.
struct marks
{
int no;
int sub[5];
float fee;
}stu[10];
STRUCTURES WITHIN STRUCTURES:
Structures within structures means nesting of structures .
struct employee
{
char name[30];
int age;
struct
prepared by :M V B REDDY
Subject: C and Data Structures
{
int day;
char month[20];
int year;
}j_date;
float sal;
}
UNIONS:
Unions are a concept borrowed from structures and therefore follow the same
syntax as structures . However there is major distinction between them in terms of
storage. In structures each member has its own storage location, whereas all the members
of a union use the same location. It can handle only one member at a time.
General format:
union name
{
type var1;
type var2;
.
.
.
};
Ex:
union item
{
int m;
float x;
char c;
}code;
This declares a variable code of type union item. The union contains three
members each with a different data type.
prepared by :M V B REDDY
Subject: C and Data Structures
However we can use only one of them at a time. This is due to the fact that only
one location is allocated for a union variable, irrespective of its size.
The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union.
In the declaration above the member x requires 4 bytes which is the largest
among the members. The above figure shows how all the three variables share the same
address.
ACCESSING UNION ELEMENTS:
To access a union member we can use the same syntax that we used in the
structure members.
Ex:
code.m;
code.x;
Pointers to remember:
prepared by :M V B REDDY
Subject: C and Data Structures
Key words:
prepared by :M V B REDDY
Subject: C and Data Structures
UNIT-V
Objective:
Files handles large amounts of data as before it became cumbersome and time
consuming to handle large volumes of data through terminals. The entire data is lost
when either the program is terminated or the computer is turned off. Thus the files drives
away all of those limitations of using ordinary data. Hence here in this unit we will learn
about the handling of files.
INTRODUCTION:
Till now we have been using the functions such that scanf and printf to read
and print data. There are console Oriented I/O functions which always use the terminals
(Key board and monitor) as the target place. This works fine as long as the data is small.
However many real life problems involves large volume of data and in such situations the
console oriented I/O operations pose two major problems.
prepared by :M V B REDDY
Subject: C and Data Structures
5. Closing a file
There are two distinct ways to perform the file operations in C. The first one is
known as the low level I/O and uses UNIX system calls. The second method is referred
to as the high level I/O operations and uses functions in C’s standard I/O library.
DEFINING AND OPENING A FILE:
If we want to store data in a file in the secondary memory, we must specify
certain things about the file, to the operating system. They include
1. Filename
2. Data structure
3. Purpose
Filename is a string of characters that make up a valid filename. Data structure of
a file is defined as FILE in the library of standard I/O function definition. Therefore all
files should be declared as type before they are used. FILE is a defined data type.
When we open a file we must specify what we want to do with the file. For
example we may write data to the file or read the already existing data.
THE GENERAL FORMATE FOR DECLARING AND OPENING A FILE:
FILE *fp;
fp = fopen(“filename”,mode);
The first statement declares the variable fp as a pointer to the data type FILE. The
second statement opens the file, named file name and assigns an identifier to the FILE
type pointer fp. This pointer which contains all the information about the file is
subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening this file. The mode does
this job. Mode can be one of the following
r opening the file for reading only.
w opening the file for writing only
a opening the file for appending (or adding) data to it.
Both the filename and mode are specified as string. They should be enclosed in
double quotation marks.
When trying to open the file of the following things may happen,
prepared by :M V B REDDY
Subject: C and Data Structures
1. When the mode is writing a file with the specified name is created if the file does
not exist. The contents are deleted if the file already exist
2. When the purpose is appending the file is opened with the current contents safe. A
file with the specified name is created if the file does not exist.
3. If the purpose is reading and if it exists then the file is opened with the current
contents safe. Otherwise an error occurs.
Many recent compilers include additional modes of operations they are:
r+ The existing file is opened to the beginning for both reading & writing.
w+ same as w except both for reading & writing.
a+ Same as a except both for reading & writing.
CLOSING A FILE: A file must be closed as soon as all operations on it have been
completed. We have to close a file is when we want to reopen the same file in a different
mode. The I/O library supports the functions to do this
fclose (file_pointer)
EX: FILE *x1,*x2;
x1 = fopen(“salary”,r);
x2 = fopen(“employee”,w);
………
………..
………..
fclose (x1);
fclose (x2);
All files are closed automatically whenever a program terminates. However
closing a file as soon as you are done with it is good programming habit.
INPUT/OUTPUT OPERATIONS ON FILES:
The getc and putc functions: the simplest file i/o functions are getc and
putc.these are analogous to getchar and putchar functions and handle one character at a
time. Assume that a file is opened with mode W and file pointer fp then the statement is
Putc(c, fp);
Writes the character contained in the character variable c to the file associated
with file pointer,fp.
prepared by :M V B REDDY
Subject: C and Data Structures
.
similarly getc is used to read a character from a file that has been opened in read mode,
the statement is
C= getc(fp);
The file pointer moves by one character position for every operation of getc or
putc. The getc will return an end-of-file marker EOF, when end of the file has been
reached. Therefore the reading should be terminated when EOF is encountered.
EX:
/*write a program to read data form the keyboard , write it to a file called INPUT ,
again reqad the same data form the INPUT file and display it on the screen*/
#include<stdio.h>
main ( )
{
file *f1;
char c;
clrscr ( );
printf (“data into \n\n”);
f1=fopen (“input”,”w”);
while ((c=getchar ()! =eof)
putc(c, f1);
fclose (f1);
printf (“\n data output\n\n”);
f1=fopen (“input”,”r”);
while ((c=getc (f1))! =eof)
printf (“%c”, c);
fclose (f1);
prepared by :M V B REDDY
Subject: C and Data Structures
EX:
/*A file name DATA contains a series of integer numbers. Code a program to read
these numbers and then write all the odd numbers to the file to be called ODD and
all even numbers to a file to be called EVEN.*/
#include<stdio.h>
main ( )
{
file *f1,*f2,*f3;
int num, i;
clrscr ( );
printf (“contents of data file:\n”);
f1=fopen (“data”,”w”);
for (i=1;i<=30;i ++)
{
scanf (“%d”, &num);
if (num==-1)
break;
putw (num, f1);
}
fclose (f1);
f1=fopen (“data”,”r”);
f2=fopen (“odd”,”w”);
f3=fopen (“even”,”w”);
while (num==getw (f1))! =eof)
{
if (num%2= =0)
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
Extend the program to read this data from the file INVENTORY and display the
inventory table with the value of each item.
*/
#include<stdio.h>
main ( )
{
file *fp;
int num, qty, i;
float price, value;
char item [10], filename [20];
printf (“enter the name”);
scanf (“%s”, filename);
fp=fopen (filename,”w”);
printf (“input inventory data”);
printf (“itemname number price quantity”);
for (i=1; i<=3; i ++)
fscanf (stdin.”%s%d%f%d”, item, &num, &price, &qty);
fclose (fp);
fprintf (stdout,”\n”);
fp=fopen (filename,”r”);
printf (“itemname number price quantity value”);
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY
Subject: C and Data Structures
1) fopen() is the function name that creates a new file for use.
2) fopen() is the function name that opens an existing file for use.
3) getc() is the function that reads a character from the file.
4) fscanf() reads a set of values from a file.
5) ftell() function gives the current position in the file.
prepared by :M V B REDDY
Subject: C and Data Structures
UNIT-VI
Objective:
This unit is designed to know how to program efficiently. There are no. of
ways to write programs; they must run correctly and efficiently; be easy to read and
understand; be easy to debug and; be easy to modify.
DATA STRUCTURES
INTRODUCTION:-
Data structure is representation of the logical relationship existing between individual
elements f data. In other words, a data structure is a way of organizing all data items that
considers not only the elements stored but also their relationship to each other.
Stacks
A stack is a non primitive linear data structure. It is an ordered test in which addition of
new data items and deletion of already existing data item is done from only one end,
known as top of stack. As all insertions and deletions is done from one end (i.e., from top
of the stack), the element that is added last is deleted first. That is the reason why stack is
also called as last in first out (LIFO) type of list.
prepared by :M V B REDDY
Subject: C and Data Structures
Operations on stack
Push:
Process of adding a new element to the top of stack is called PUSH operation. Pushing
an element in the stack invoke adding of element, as the new element will be inserted at
the top after every push operation the top is incremented by one. When the array is full,
the new element can be accommodated, it is called stack-full condition. This condition is
called as stack overflow.
Pop:
The process of deleting an element from the top of stack is called Pop operation. After
every pop operation the stack is decremented by one. If these is no element on the stack
and the pop is performed then this will result into stack underflow condition.
Stack Terminology:
MAXSIZE
Top of the stack
Stack empty or underflow
Stack full or overflow
prepared by :M V B REDDY
Subject: C and Data Structures
EX:
Infix - A+B
Postfix- AB+ (reverse polish)
Prefix - +AB (polish)
prepared by :M V B REDDY
Subject: C and Data Structures
1. Parenthesis
2. exponent (R to L)
3. * & ? (L to R)
4. +,_ (L to R)
Evaluation of postfix
1. Expression is scanned from left to right
2. If number is encountered, push onto stack.
3. If an operator is encountered apply it to the top two operands on stack. After it is
pushed onto the stack.
4. Above steps are repeated until the end of an expression
EX:
256+*2^4/
Scanned symbol Stack contents
2 2
5 2, 5
6 2,5,6
+ 2,5,6
* 2,11
2 22
^ 22,2
4 484,4
/ 121
prepared by :M V B REDDY
Subject: C and Data Structures
QUEUES:
A queue is an ordered collection of data such that data structure which holds collection of
items to be processed on first in first out basis
Representing a Queue:
One of the most common ways to implement a queue is using an array. Tqo variables are
used, rear and front.
Front- We can delete from this end
Rear- We can insert from this end.
prepared by :M V B REDDY
Subject: C and Data Structures
Points to remember:
Queue is called as FIFO structure .In contrast, a stack is called as LIFO
structure.
A pop operation in the case of stack is destructive i.e once an item is popped
,it is no longer available.
Arrays and lists are called as linear data structures .
In prefix notation the operators are placed before the operands.
prepared by :M V B REDDY
Subject: C and Data Structures
Keywords:
Stack
Queue
Overflow
Underflow
Infix
Postfix
Prefix
prepared by :M V B REDDY
Subject: C and Data Structures
prepared by :M V B REDDY