0% found this document useful (0 votes)
32 views150 pages

C Languauge Notes

The document outlines a syllabus for a course on Programming in C and Data Structures, detailing key topics such as C language features, data types, control statements, and various data structures like arrays, stacks, and trees. It also includes session objectives, programming structure, and examples of operators and input/output functions. Additionally, it provides exercises to reinforce learning and emphasizes the importance of proper syntax and variable declaration in C programming.

Uploaded by

rayan rajab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views150 pages

C Languauge Notes

The document outlines a syllabus for a course on Programming in C and Data Structures, detailing key topics such as C language features, data types, control statements, and various data structures like arrays, stacks, and trees. It also includes session objectives, programming structure, and examples of operators and input/output functions. Additionally, it provides exercises to reinforce learning and emphasizes the importance of proper syntax and variable declaration in C programming.

Uploaded by

rayan rajab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

PROGRAMMING IN C &

DATA STRUCTURES
Sub.Code:
1BIT2C1,4BIT2C1,7BIT2C1

Handled by
PR.RAJESH MCA.,B.Ed
SYLLABUS
Introduction to C – Character set – Identifiers and keywords – Data types –
constants – Variables – declarations – Operator and Expressions – Data input,
output and control statements: Preliminaries – single character input and output
– Entering input data – Writing output data – gets and puts functions –
Branching and looping – Nested control structures Arrays: defining and
processing an array – Passing on array to functions – Multidimensional arrays –
arrays and strings.
Pointers: Fundamentals –Dynamic memory allocation – operations on pointers –
arrays of pointers
Structures and Unions: defining a structure – Structures and pointers– Self
referential structures – Bit fields – Unions – Enumerations.
Data file: Opening and Closing a data file – Creating a data file – Processing a
data file – Unformatted data file – Command line parameters.
Stack: Definition and Examples – Representing stacks in C – An example: Infix,
Postfix and Prefix. Queues and Lists: The queues and Sequential representation
– Linked lists – Lists in C.
Trees: Binary trees – Representing Lists and Binary Trees – trees and their
applications.
Session Objectives
 Discuss the Origin of C

 Features of C

 Characteristics of C

 Current Uses of C

 “C” Programming Structure

 Character Set
“C” is a Middle Level language
“C” is a Structure & Procedure Oriented Programming
language developed by Dennis Ritchie at AT&T Bell Laboratories
in USA in the Year 1972

(Basic Combined Programming Language)


Features of “C” Language

 Economy of Expressions
 Modern Control Flow and Structures
 Rich Set of Operators
 It is Well suited for writing both System
Software like Operating Systems,
Interpreters, Editors and Assembly
Programs
 UNIX Operating System was Developed by Using “C”
Language
 Developing database Systems
 Graphics Packages

 Spread Sheets

 Word Processors

 Office automation

 Scientific/Engineering Applications

 CAD/CAM Applications
Preprocessor Directives (Incl. headerFile)
Global Variable Declarations;
void main()
{
Local Variable Declarations;
Input/Output Statements;
}

Note :
Every “C” Statements should end with Semicolon(;)
The C Program Structure
 Preprocessor directives are the instructions given to the
compiler.

 They are not translated into machine language, but are


operated upon directly by the compiler before the
compiling process begins.

 Preprocessor directives begin with a # (hash)

 Preprocessor directives are often placed in the beginning


of a program before the main() is declared.
A lot of library functions are
subdivided into number of groups.
This groups are called Header files

Syntax : #include<headerfilename.h>
Examples: #include<stdio.h>
#include<conio.h>
Stdio -> Standard Input/Output
Conio -> Console Input/Output
Void -> Keyword. It Means Returns Nothing.
main() -> It is a function name which can be used to
indicate the beginning of the program
execution
C has 32 keywords.

These keywords combined with a formal syntax form a C


programming language.

Rules to be followed for all programs written in C

All keywords are lowercased

C is case sensitive, do while is


different from DO WHILE
Keywords cannot be used as a
variable or function name
Programs

Instructions

Keywords

Constants,
variables &
Data Types

Alphabets,
Digits,Special
Characters
A Character denotes an alphabet, digit or a special
character. These characters can be combined to form variables.

Lowercase Letters – A,B,C….. Z


Uppercase Letters - a,b,c…… z

Digits – 0,1,2,3,…7,8,9

+ Plus Sign - Minus Sign , Comma

* Asterisk / Slash = Equal to


@ At Symbol < Less Than : Colon
; Semicolon
10 4600.5 “A”
‘A’
-356 -0.963 “CSC”
‘*’
Escape Sequence
Escape sequences are specified as the first argument in
Output Statement. They are always preceded with a
backslash
Variables are named locations in memory that are used to
hold a value that may be modified by the program.

The syntax for declaring a variable is

Data type Variablename;

Valid Examples :
APOLLO avg_val m1
MELUR Anu mark_1

Some erroneous identifier names are - 1stsst


oh!god
start….end
RULES for framing a variable :

The first character in the Variable name must be an alphabet


Alphabets can be followed by a number of digits or
underscores
No commas or Blank spaces are allowed within a variable
name
No Special character other than Underscore(_) can be used in
a variable name.
The variable name should not be a keyword
Variable names are case sensitive
It should not be of length more than 31 characters
Character structure
Integer Union
Float Pointer
Double enum
1.Type Definition
Example: Typedef int age;
age male,female

2.Enumerated Datatype
Example :
enum mon{jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec };
Session Summary

 All variables must be declared in the program before all executable statement

 Comments statements may or may not be present in a program

 Comment statement improves the readability of a program

 A program will always begin by executing the main() function

 Every C program must contain atleast one function which must be a main()
EXERCISES

1. Why it is required to include header files your C program?

2. What is #include statement? Indicate its use?

3. Why is the main() function is so special

4. Write a program to calculate Simple and Compound Interest?

5. State the use of comment symbol in a program?

6. Describe the types of constants? Give example?


1. Arithmetic operators
2. Unary Operators
3. Relational and Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Increment and Decrement Operators
Arithmetic Operators:

To do arithmetical calculations.
1. +  Addition
2. -  Subtraction
3. *  Multiplication
4. /  Division (Quotient)
5. %  Division (Reminder)
Unary Operators:

1. --  Unary Minus (To represent Negative


Number)
2. ++  Increment Operator
Two types
1. Preincrement operatorEx: ++i
2. Post increment OperatorEx: i++
3. --  Decrement Operator
Two Types
1. Predecrement OperatorEx:--i
2. Post decrement OperatorEx:i--
4. sizeof  To print the size of data types.
Relational Operators

• >  greater than


• <  less than
• >=  greater than or equal to
• <=  less than or equal to
• ==  perfectly equal to
• !=  not equal to
Logical Operators

• &&  logiacl and


• ||  logical or
• !  logical not
Assignment operator

=
• It is used to assign values to a variable.
Syntax:
Identifier=expression;
Eg:
A=2
B=5.6
Conditional Operator

• It is also called as ternary operator.


Syntax:
expression 1? expression 2 : expression 3;
• Here expression 1 is evaluated first and if it is
true, expression 2 is evaluated and assign the
value to expression 3.
• If expression is false, then expression 2 is
not evaluated, and the initial value is assigned to
expression 3.
Type casting
Converting one data type to another is called as casting. For
sometimes certain variables declared as float might be required as int for
some expressions. For that purpose the cast is used.
General form
(data type) expression
Eg:
• Let a, b are float variables and c integer variable
• If we want to use a and b as int in some expression then we can change
this as follows
((int)(a+b))+c;
• Here a+b is converted to int and then added with c. After the execution
of this expression and b will be returned as float variables.
Standard Input and Output Functions

Standard Input function: Conversion character:


scanf( ) • %d  Data item is a
Syntax: decimal integer
scanf(“format string”, list of • %f  Data item is a
address variable); floating point value
Definition: • %s  Data item is a string
• This function accepts the • %c  Data item is a
input value from the keyboard and character
stores it into the corresponding • %lf  Data item is a double
memory location. • %ld  Data item is an long
Ex: integer.
scanf(“%d”,&a); • &  Address Operator
scanf(“%f%f,&a,&b);
Standard output function:

printf( )
Syntax:
printf(“format string”, list of variables);
Description:
This function prints the given output on the screen.
Ex:
printf(“%d”,sum);
printf(“Enter the values for a and b”);
printf(“Sum=%d”,sum);
Character Input Output function:

Single character Input function:


getchar( );
Syntax:
Variable name=getchar( );
Description:
• This function inputs a single character from the keyboard and
converts it into the equivalent ASCII value.
Ex:
C=’A’
C=getchar( );
Single character Output function

putchar( );
Description:
This function converts the ASCII value of a single
character and displays the result on the monitor.
Syntax:
putchar(variable name);
Ex:
putchar(a);
Standard string Input output functions

Standard String Input Function:


gets( );
Syntax:
Variable name=gets( );
Description:
This function inputs the string given in the keyboard and stores it into
the corresponding memory location.
Ex:
Name=”Kavitha”
Name=gets( );
Standard String Output function

puts( );
Syntax:
puts(variable name);
Description:
This function prints the string on the monitor.
Format of a C Program

#include<header file>
main()
{
Variable declarations;
clrscr();
Program statements;
getch();
}
EX for Operators
ARITHMETIC OPERATOR: • ASSIGNMENT AND RELATIONALAND
LOGICALOPERATOR
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{
{
int a=10,b=5;
int a,b,sum; clrscr();
clrscr(); printf(“A<=B:”,(a<=b));
printf(“\nA>=B:”,(a>=b));
printf(“Enter the values for a and b:”);
printf(“\nA==B:”,(a==b));
scanf(“%d%d”,&a,&b); printf(“\nA!=B:”,(a!=b));
sum=a+b; getch();
printf(“Sum=%d”,sum); }

getch();
}
EX for Operators
CONDITIONAL and TERNARY INCREMENT AND
OPERATOR DECREMENT OPERATOR
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main() main()
{ {
int num,absolute; int i=1;
clrscr(); clrscr();
printf(“Enter any no:”); printf(“i=%d\n”,i);
scanf(“%d”,&num); printf(“i=%d\n”,++i);
absolute=(num<0)?-num:num; printf(“i=%d\n”,i);
printf(“Absolute value=%d”,absolute); getch();
getch(); }
}
EX for INPUT & OUTPUT FUNCTIONS
SINGLE CHARACTER INPUT &
STANDARD INPUT & OUTPUT OUTPUT
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
main( ) main()
{ {
int a,b,sum; int c;
clrscr(); clrscr();
printf(“Enter the values for a&b:”); printf(“Enter an upper case letter”);
scanf(“%d%d”,&a,&b); c=getchar();
sum=a+b; printf(“Lowercase=”);
printf(“Sum=%d”,sum); putchar(c+32);
getch( ); getch();
} }
Standard string Input output functions

#include<stdio.h>
#include<conio.h>
main( )
{
char name[30];
clrscr( );
puts(“Enter your name”);
gets(name);
puts(“Your Name is:”);
puts(name);
getch();
}
Session Objectives
Explain 8 Types of Operators
Explain Arithmetic Operators
Understand Arithmetic Expressions
Explain Relational and Logical Operators
Explain the Conditional Operators
Explain Input/Output Statement
Control Statements
It determines the flow of control in a
program Control statements

Conditional control statements Unconditional control statements

1. simple if statement 1. go to statement


2. if else statement 2. continue
3. Nested if statement 3. break
4. Switch case statement
Looping statements

1.for statement
2. while statement
3. do while statement
Conditional control statements
if else if statement
simple if statement syntax:
Syntax: if (condition)
if (condition) statements;
Statements; else
E.g.: statements;
#include<stdio.h> eg:
#include<stdio.h>
#include<conio.h>
#include<conio.h>
main()
main()
{ {
int pos; clrscr(); int pos; clrscr();
printf(“Enter a no:”); printf(“Enter any no:”);
scanf(“%d”,&pos); scanf(“%d”,&pos);
if (pos>0) if (pos>0)
printf(“The given no is a positive printf(“The given no is a positive no”);
number”); else
getch(); printf(“The given no is a negative no”);
getch();
}
}
Nested if statement
eg:
#include<stdio.h>
#include<conio.h>
main()
{
int pos;
syntax: clrscr();
if (condition) printf(“Enter any no:”);
statements; scanf(“%d”,&pos);
elseif (condition) if(pos>0)&&(pos!=0)
statements;
else printf(“The given no is a positive no”);
statements; elseif(pos<0)&&(pos!=0)
printf(“The given no is a negative no”);
else
printf(“The given no is a zero);
getch();
}
switch case statement
It allows us to make a decision from the eg:
number of choices .The keyword case is
followed by an integer constant or a character
#include<stdio.h>
constant. #include<conio.h>
First, the expression is evaluated and if the main()
value matches any one of the case statement {
then the corresponding statement is evaluated.
If there is no match then the statements below, char code;
default is evaluated. clrscr();
Syntax: printf(“Enter a code[a/m/p]:”);
switch(expression) scanf(“%c”,&code);
{
switch(code)
case 1:statements;break;
case 2:statements;break;
{
case 3:statements;break; case ‘a’:printf(“Accounts staff”);break;
default:statements; case ‘m’:printf (“Management staff”);break;
} case ‘p’:printf (Purchase staff”);break;
default :printf (“Invalid choice ! Try again”);
} getch(); }
Looping statements
#include<stdio.h>
#include<conio.h>
while loop
main()
syntax:
{
while ( condition) int n,i=0;
{ clrscr();
printf(“Enter the range:”);
statements; scanf(“%d”,&n);
} while(i<n)
{
printf(“i=%d\n”,i);
i++;
}
getch();
}
do……. While loop
eg:
#include<stdio.h>
do……. While loop #include<conio.h>
The do while statement test the main()
condition after having executed the {
statements within the loop.
int i,n;
This means it will executes the
clrscr();
statements at least once even if the
condition fails for the first time itself. printf(“Enter the range:”);
syntax: scanf(“%d”,&n);
do do
{ {
statements; printf(‘i=%d\n”,i);
} while(condition); i++;
}while(i<n);
getch();
}
for loop

for loop eg:


syntax: #include<stdio.h>
for (expression 1 ; expression 2; expression 3) #include<conio.h>
statements; main()
where {
expression 1  initialization statement int i,n;
expression 2  condition checking statement clrscr();
expression 3  increment or decrement printf(“Enter the range:”);
operator scanf(“%d”,&n);
for(i=0;i<n;i++)
printf(“i=%d\n”,i);
getch();
}
Unconditional control statements
1. break statement
It is used to terminate from 2. continue statement
the loop.This statement is used with
This statement will take the
for,, do while,switch case statements.
control to the beginning of the loop.It
Eg: can be included only in a while, do
#include<stdio.h> while, for statement.
#include<conio.h>
main() 3. goto statement
{ It transfers the control to
int x=1;clrscr(); anywhere in the program. Avoid using
while (x<=10) { this statement.
printf(“x=%d\n”,x);
if(x==5) break; x++;
} getch(); }
Session Objectives
Explain Types of Control Statements
Explain If, If..else statements
Understand Looping concepts
Explain Switch..Case statement
Explain Break,continue Statements
Explain the Goto Statement
• An array is a group of elements that belongs to same
data type and calls with a common name.
• Arrays a kind of data structure that can store a fixed-
size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of
variables of the same type.
• Instead of declaring individual variables, such as
number0, number1, ..., and number99, you declare
one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an
array is accessed by an index.
• All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highest address to the last element.
An array subscript starts with a[0] and ends with a[n-1].
Syntax:-
datatype varname[array size];
Ex:- int a[10];

Types of Array:-
• Single/one dimensional Array
• Multi/Two dimensional Array
Intializing an Array:-
An array can be initialized when declared by specifying
the values of some or all of the elements.
Syn:-
int a[5]={1,2,3,4,5};
ONE DIMENSIONAL
ARRAY
Example
• An array with only one #include<stdio.h>
#include<conio.h>
subscript is known as void main()
{
one dimensional array. int i,a1=0,a[5];
clrscr();
• Syn:- Printf(“Enter 5 Elements:”);
for(i=0;i<5;i++)
arrayname[subscript]; {
Datatype arrayname[size]; scanf(“%d”,&a[i]);
}
for(i=0;i<5;i++)
a1=a1+a[i]; printf(“\nTotal is:%d”,a1);
}
getch();
}
FOR CHARACTER
• A character/string is stored • Example:-
#define size 256
internally as a one #include<stdio.h>#include<conio.h>
dimensional array of void main()
character. {
char a[size]; int s; clrscr();
• Each character with in the printf(“Enter a String:”); gets(a);
string will stored with one printf(“\n The array contains:%s”,a);
element of an array. for(s=0;((s<size) && (s[s]!=‘\0’);s++)
{
• Syn:- char arrayname[size]; putchar(a[s]); putchar(‘\n’);
}
printf(“\n The length of the string
is:%d”,s);
getch();
}
MULTI DIMENSIONAL ARRAY
Example:
#include<stdio.h> #include<conio.h>
An array with 2 subscripts is called
void main()
2D/MD array.
{
Syn:- datatype int a[5][5],b[5][5],c[5][5],i,j;
arrayname[subscript][subscript]; clrscr();
Intialization:- printf(“Enter A matrix:”);
datatype arrayname[rowsize][column for(i=0;i<5;i++) { for(j=0j<5;j++) {
size]; scanf(“%d”,&a[i][j]);
} } printf(“Enter B matrix:”);
(i.e) here 2 subscript are denoted as row for(i=0;i<5;i++) { for(j=0j<5;j++) {
and column . An array can be stored in scanf(“%d”,&b[i][j]); } }
the memory in 2 orders RowMajor order for(i=0;i<5;i++) { for(j=0j<5;j++) {
and Column Major Order.Usually int c[i][j]=a[i][j]+b[i][j]; printf(“RESULT IS:”);
types are stored in row major order , char for(i=0;i<5;i++) { for(j=0j<5;j++) {
types are stored in column major order. printf(“%d”,c[i][j]);
} }printf(“\n\n”); getch(); }
Session Objectives
Explain Arrays
Explain Declaration,Initialization of Array

Explain Types of Array


One Dimensional,Two Dimensional and Multi
Dimensional Array
Functions

Definition
Function is a self-contained block of programs that performs a
coherent task of some kind... Every C program can be thought of as a
collection of these functions.
There are two types of functions
1. Library functions e.g.: printf() , scanf()
2. User defined functions
User defined functions can be broadly divided into two types
1. Functions without arguments
2. Functions with arguments
Functions without arguments Implementation

1. Three steps e.g.:


1. Function prototype declaration void message()
Syntax: {
return type function name (); printf(“Welcome to Functions”);
e.g.: }
void message(); #include<stdio.h>
void italy(); #include<conio.h>
int sum();
void message();
2. Function calling
Syntax: void main()
function name(); {
e.g.: clrscr();
---- printf("I am in main function\n");
message();
message();
italy();
sum(); getch();
3. Function Definition }
Syntax: void message()
return type function name () {
{
printf("Welcome to c program");
body of the function;
} }
Points to remember 5. Each of the function is called in a sequence specified
1. C program is a collection of one or more functions. by the function calls in the main().
2. If a program function only one function it must be 6. After each function has done its thing, its control
main(). returns to main().
3. Program execution always begin with main(). 7. A function gets called when a function name is
4. There is no limit on the number of functions that might followed by a semicolon.
be present in a C program. 8. A function is defined when function name is followed
E.g.: by a pair of braces in which one or more statements may
present.
#include<stdio.h> #include<conio.h>
9. Any function can be called from any other function.
void message(); void usage(); Even main() can be called from other function. For e.g.
void main() main()
{ {
clrscr(); printf("I am in main function\n"); message();
message(); usage(); }
printf("I am back in main"); getch(); } message()
void message() {
{ printf(“I am in C \n”);
printf("I am in message\n"); main();
} }
void usage()
{
printf("I am in usage\n");
}
#include<stdio.h>
#include<conio.h>
void italy();
void brazil();
void main()
{
clrscr();
printf("I am in main function\n");
italy();
printf("I am back in main function");
getch();
}
void italy()
{
printf("Welcome to italy\n");
brazil();
printf("I am back in italy\n");
}
void brazil()
{
printf("I am in brazil\n");
}
10. A function can be called any no of times.
11. The order in which the functions are defined in the program and the order in which
they are called need not necessarily be same.
12. A function can call itself. Such a process is called “recursion”.
13. A function can be called from the other function, but a function cannot be defined in
another function.
Advantages of using functions
1. Writing functions avoids rewriting the same code repeatedly.
2. Using functions it is easier to write programs and keep track of what they
are doing.
Functions with arguments
Sometimes we want to communicate between the calling function and
the called function. This is done by using argument.
The mechanism used to convey information to the function is the
argument. The arguments are sometimes also called ‘parameters’.
There are two types of arguments.
Actual arguments.
Formal arguments.
We must declare the type of the arguments through type declaration statements
before beginning with the statements in the functions.
Syntax:
return type function name(data type arg1, data type arg2,….data type arg n)
{ statements; }
STRING FUNCTIONS
• Strings is a collection of character group of characters are stored in array ant
this arrays are called as strings.
• Strings are 1 dimensional array of character and it terminated by null
character which is represented by (‘\0’) char.
• The null (‘\0’) is including end of string so it is important to know where the
string is end.
• Syntax:- char varname[size];
0 1 2 3 4
It stores in memory as char a[5]={‘R’,’A’,’J’};
R A J

• Char a1[20]={“RAJ”}; It displays the full string as


RAJ.
VARIOUS STRING FUNCTIONS
S.N. Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.

2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.

3 strlen(s1);
Returns the length of string s1.

4 strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than
0 if s1>s2.

5 strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
EXAMPLE
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) :%s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2):%s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) :%d\n", len );
return 0;
}
Session Objectives
Explain User Defined Functions
Explain Type of Functions
Discuss category of Functions
Declaration & Prototypes
Storage class in “C”
Calling the Function
A Function may call itself again and again is
called Recursive Function
The C programming language supports recursion, i.e., a function to
call itself. But while using recursion, programmers need to be careful
to define an exit condition from the function, otherwise it will go into
an infinite loop.

Recursive functions are very useful to solve many mathematical


problems, such as calculating the factorial of a number, generating
Fibonacci series, etc.
Example:
#include <stdio.h>
int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i)); return 0;
}
Session Objectives

Define Recursive Functions


Write a Program to find the factorial using
Recursive Method
POINTERS
A pointer is a variable whose value is the This is done by using unary operator * that returns
address of another variable, i.e., direct address of the the value of the variable located at the address
memory location. Like any variable or constant, you specified by its operand. The following example makes
must declare a pointer before using it to store any use of these operations:
variable address. The general form of a pointer #include <stdio.h>
variable declaration is:
int main ()
type *var-name;
{
Here, type is the pointer's base type; it
must be a valid C data type and var-name is the name int var = 20; *ip;
of the pointer variable. The asterisk * used to declare /* actual variable declaration */ /* pointer
a pointer is the same asterisk used for multiplication. variable declaration */
However, in this statement, the asterisk is being used
to designate a variable as a pointer. Take a look at ip = &var;
some of the valid pointer declarations: /* store address of var in pointer variable*/
int *ip; /* pointer to an integer */ printf("Address of var variable: %x\n", &var
double *dp; /* pointer to a double */ );
float *fp; /* pointer to a float */ /* address stored in pointer variable */
char *ch /* pointer to a character */ printf("Address stored in ip variable: %x\n",
How to Use Pointers? ip );
There are a few important operations, which we will /* access the value using the pointer */
do with the help of pointers very frequently. (a) We
printf("Value of *ip variable: %d\n", *ip );
define a pointer variable, (b) assign the address of a
variable to a pointer, and (c) finally access the value at return 0; }
the address available in the pointer variable.
Pointers in Detail
• Pointers have many but easy concepts and they are very important to C programming.
The following important pointer concepts should be clear to any C programmer:
Concept Description

Pointer arithmetic There are four arithmetic operators that


can be used in pointers: ++, --, +, -

Array of pointers You can define arrays to hold a number of


pointers.

Pointer to pointer C allows you to have pointer on a pointer


and so on.

Passing pointers to functions in C Passing an argument by reference or by


address enable the passed argument to be
changed in the calling function by the
called function.

Return pointer from functions in C C allows a function to return a pointer to


the local variable, static variable, and
dynamically allocated memory as well.
ARRAY OF POINTERS
#include<stdio.h>
• Pointers and arrays are strongly #include<conio.h>
related, infact pointers and void main()
arrays are interchangeable in {
many cases. int i,j,n,a[25],*p;
• For ex. Apointer that points to clrscr();
the beginning of an array can printf(“Enter the no.of.Elements:”);
access that array by using either scanf(“%d”,,&n);
pointer arithmetic or array style printf(“\nEnter the array elements:”);
indexing. for(i=0;i<n;i++)
{
• An array may contain pointers, scanf(“%d”,&a[i]);
each entry in the array is a }
string, in c a string is essentiall a *p=a[o]; for(i=0;i<n;i++) if(a[i]>*p) *p=a[i];
pointer to its 1st character. Printf(“\n The biggest element in the array
• Syntax:- char *varname [size]; is:%d”,p);
getch();
}
Passing pointer to functions
• C programming allows passing #include <stdio.h> #include <time.h>
a pointer to a function. To do void getSeconds(unsigned long *par);
so, simply declare the function int main ()
parameter as a pointer type. {
unsigned long sec;
getSeconds( &sec );
• Following is a simple example /* print the actual value */ printf("Number
where we pass an unsigned long of seconds: %ld\n", sec );
pointer to a function and return 0;
change the value inside the }
function which reflects back in void getSeconds(unsigned long *par)
the calling function: {
/* get the current number of seconds */ *par
= time( NULL ); return;
}
MEMEORY MANAGEMENT
This chapter explains dynamic memory management in C. The C
programming language provides several functions for memory
allocation and management. These functions can be found in
the <stdlib.h> header file.

S.N. Function and Description

1 void *calloc(int num, int size);


This function allocates an array of num elements each of which size in bytes will be size.

2 void free(void *address);


This function releases a block of memory block specified by address.

3 void *malloc(int num);


This function allocates an array of numbytes and leave them initialized.

4 void *realloc(void *address, int newsize);


This function re-allocates memory extending it upto newsize.
Dynamic Memory Allocation
The process of allocating memory at runtime is known as dynamic
memory allocation. Library routines known as "memory management
functions" are used for allocating and freeing memory during execution of
a program. These functions are defined in stdlib.h.

Function Description

malloc() allocates requested size of bytes and returns a


void pointer pointing to the first byte of the
allocated space

calloc() allocates space for an array of elements,


initialize them to zero and then returns a void
pointer to the memory

free releases previously allocated memory

realloc modify the size of previously allocated space


C malloc()
The name malloc stands for "memory allocation".
The function malloc() reserves a block of memory of specified size and return a pointer of
type void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with
size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of memory.
C calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block of
memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes
to zero.
Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of nelements. For example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4 bytes.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own.
You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Arrays allow to define type Defining a Structure
of variables that can hold several To define a structure, you must use the
data items of the same kind. struct statement. The struct statement
Similarly, structure is another defines a new data type, with more
user-defined data type available in than one member. The format of the
struct statement is as follows:
C that allows to combine data
items of different kinds. struct [structure tag]
Structures are used to {
represent a record. Suppose you member definition;
want to keep track of your books in member definition;
a library. You might want to track ...
the following attributes about each
member definition;
book:
} [one or more structure
Title
variables];
Author
Subject
Book ID
EXAMPLE
#include<stdio.h>
#include<conio.h>
void main()
{
struct complex
{
float rp,ip;
};struct complex x,y,z;
clrscr();
printf("enter the 1st complex number real part and imaginary part");
scanf("%f%f",&x.rp,&x.ip);
printf("\nEnter the 2nd complex number real and imaginary part");
scanf("%f%f",&y.rp,&y.ip);
z.rp=x.rp+y.rp;
z.ip=x.ip+y.ip;
printf("\nZ=%6.2f+6.2fi",z.rp+z.ip);
getch();
}
Array of structures
#include<stdio.h>
#include<conio.h>
Array of structures can be void main()
defined as a group of data of {
different datatypes stored in a int i; struct student {
consecutive memory location int rno; char name[25]; int marks;
with a common variable };struct student s1[5];
name. clrscr();
Syn: for(i=0;i<=5;i++)
{
struct <struct name>
printf("\nEnter rno,name and marks of %d
{ students:",i);
data type mem1; scanf("%d%s%d",&s1[i].rno,&s1[i].name,&s1[i].
marks);
datatype mem2[],mem3[];
}
. for(i=1;i<=5;i++)
. {
}struct name[size]; printf("\n\nRECORD OF %d student:",i);
printf("\rno:%d\nName:%s\nMarks:%d",s1[i].rn
o,s1[i].name,s1[i].marks);
} getch(); }
SELF REFERENTIAL
STRUCTURES
• A Structure containing a member that is a pointer to the same structure type
is called as a self referential structure.
BIT FIELDS:
A bit field is a built-in feature that allows you to access a single bit,
they must be defined as a member of a structure and declared as type unsigned
or int.
Each bit field can then be accessed individually similar to other
numbers of a structure.
Syn: Struct <struct-name>{ type member1:size; --- type member
n:size;}variable(s);
Advantages of using Bit fields:
• To store Boolean variables(true/false) in one byte.
• To encrypt certain routines to access the bits with in a byte
• To transmit status information of devices encoded into one or morebits
with in a byte.
Limitations of Bit fields:
• Bit fields cannot be created
• Bit fields are machine dependent
• Address of a bit field cannot be read.
• Bit fields cannot be declared as static.
Session Objectives

Define Structure
Create Structure variable
Access structure member using . operator
Nested Structures
A union is a special data type available in C that allows to store different data types in the same memory location. You can define
a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same
memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data
type with more than one member for your program. The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition.
At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you
would define a union type named Data having three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., same memory
location, can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will
occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string. The following example displays
the total memory size occupied by the above union −
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
Accessing Union Members
To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable name and the
union member that we wish to access. You would use the keyword union to define variables
of union type. The following example shows how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

return 0;
}
Session Objectives

Discuss Unions
Create Union variable
Access Union member using . operator
Discuss Unions of Structures
Compare Structure and Array
Difference between structure & union
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language
provides access on high-level functions as well as low-level (OS level) calls to handle file on your storage devices.
This chapter will take you through the important calls for file management.
Opening Files
FILE *fopen( const char * filename, const char * mode );

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of
the type FILE, which contains all the information necessary to control the stream. The prototype of this function call
is as follows: Here, filename is a string literal, which you will use to name your file, and access mode can have one
of the following values:
Mode Description

r Opens an existing text file for reading purpose.

w Opens a text file for writing. If it does not exist, then a new file is created. Here your
program will start writing content from the beginning of the file.

a Opens a text file for writing in appending mode. If it does not exist, then a new file is
created. Here your program will start appending content in the existing file content.

r+ Opens a text file for both reading and writing.

w+ Opens a text file for both reading and writing. It first truncates the file to zero
length if it exists, otherwise creates a file if it does not exist.

a+ Opens a text file for both reading and writing. It creates the file if it does not exist.
The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files, then you will use the following
access modes instead of the above-mentioned ones:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );
The fclose() function returns zero on success, or EOF if there is an error in closing the file. This
function actually flushes any data still pending in the buffer to the file, closes the file, and
releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by
character, or in the form of a fixed length string.
Writing a File
Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream referenced
by fp. It returns the written character written on success otherwise EOF if there is an error. You
can use the following functions to write a null-terminated string to a stream:
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-
negative value on success, otherwise EOF is returned in case of any error. You can use int
fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the
following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create
this directory on your machine.
Example 1: Write to a text file using
fprintf() Reading from a text file
Example 2: Read from a text file using
fscanf()
#include <stdio.h>
int main()
#include <stdio.h>
{
int main()
int num;
{
FILE *fptr;
int num;
fptr = fopen("C:\\program.txt","w");
FILE *fptr;
if(fptr == NULL)
if ((fptr = fopen("C:\\program.txt","r"))
{
== NULL){
printf("Error!");
printf("Error! opening file");
exit(1);
// Program exits if the file pointer
} returns NULL.
printf("Enter num: "); exit(1);
scanf("%d",&num); }
fprintf(fptr,"%d",num); fscanf(fptr,"%d", &num);
fclose(fptr); printf("Value of n=%d", num);
return 0; fclose(fptr);
} return 0;
}
Session Objectives
Explain files

Discuss text File and binary File


Use basic file Operations & functions
Explain file pointer

Explain Formatted/Unformatted I/O Statements in File

Discuss current active pointer

Define the term “Preprocessor”


DATA STRUCTURES
• Data structures refers to the way data is organized and
manipulated.
• It seeks to find ways to make access data more
efficient.
• When dealing with data structure, we not only focus
on one piece of data but rather different set of data
and how they can relate to one another in an
organized manner.
Data Structure is a systematic way to organize data in order to use it efficiently. Following
terms are the foundation terms of a data structure.
Interface − Each data structure has an interface. Interface represents the set of
operations that a data structure supports. An interface only provides the list of
supported operations, type of parameters they can accept and return type of these
operations.
Implementation − Implementation provides the internal representation of a
data structure. Implementation also provides the definition of the algorithms used
in the operations of the data structure.
Characteristics of a Data Structure
Correctness − Data structure implementation should implement its interface
correctly.
Time Complexity − Running time or the execution time of operations of data
structure must be as small as possible.
Space Complexity − Memory usage of a data structure operation should be as
little as possible.
Need for Data Structure
As applications are getting complex and data rich, there are three common problems
that applications face now-a-days.
Data Search − Consider an inventory of 1 million(106) items of a store. If the
application is to search an item, it has to search an item in 1 million(106) items
every time slowing down the search. As data grows, search will become slower.
Processor Speed − Processor speed although being very high, falls limited if the
data grows to billion records.
Multiple Requests − As thousands of users can search data simultaneously on a
web server, even the fast server fails while searching the data. To solve the above-
mentioned problems, data structures come to rescue. Data can be organized in a data
structure in such a way that all items may not be required to be searched, and the
required data can be searched almost instantly.
Basic Terminology
Data − Data are values or set of values.
Data Item − Data item refers to single unit of values.
Group Items − Data items that are divided into sub items are called as Group
Items.
Elementary Items − Data items that cannot be divided are called as Elementary
Items.
Attribute and Entity − An entity is that which contains certain attributes or
properties, which may be assigned values.
Entity Set − Entities of similar attributes form an entity set.
Field − Field is a single elementary unit of information representing an
attribute
of an entity.
Record − Record is a collection of field values of a given entity.
File − File is a collection of records of the entities in a given entity set.
ALGORITHMS
Algorithm is a step-by-step procedure, which defines a set of instructions to be
executed
in a certain order to get the desired output. Algorithms are generally created
independent
of underlying languages, i.e. an algorithm can be implemented in more than one
programming language.
From the data structure point of view, following are some important categories of
algorithms −
Search − Algorithm to search an item in a data structure.
Sort − Algorithm to sort items in a certain order.
Insert − Algorithm to insert item in a data structure.
Update − Algorithm to update an existing item in a data structure.
Delete − Algorithm to delete an existing item from a data structure.
Characteristics of an Algorithm

Not all procedures can be called an algorithm. An algorithm should have the
following
characteristics −
Unambiguous − Algorithm should be clear and unambiguous. Each of its steps
(or phases), and their inputs/outputs should be clear and must lead to only one
meaning.
Input − An algorithm should have 0 or more well-defined inputs.
Output − An algorithm should have 1 or more well-defined outputs, and should
match the desired output.
Finiteness − Algorithms must terminate after a finite number of steps.
Feasibility − Should be feasible with the available resources.
Independent − An algorithm should have step-by-step directions, which should
be independent of any programming code.
How to Write an Algorithm?
There are no well-defined standards for writing algorithms. Rather, it is problem and
resource dependent. Algorithms are never written to support a particular programming
code.
As we know that all programming languages share basic code constructs like loops
(do, for, while), flow-control (if-else), etc. These common constructs can be used to write
an algorithm.
We write algorithms in a step-by-step manner, but it is not always the case. Algorithm
writing is a process and is executed after the problem domain is well-defined. That is,
we
should know the problem domain, for which we are designing a solution.
Example
Let's try to learn algorithm-writing by using an example.
Problem − Design an algorithm to add two numbers and display the result.
step 1 − START
step 2 − declare three integers a, b & c
step 3 − define values of a & b
step 4 − add values of a & b
step 5 − store output of step 4 to c
step 6 − print c
step 7 − STOP
Algorithms tell the programmers how to code the program. Alternatively, the algorithm
can be written as −
step 1 − START ADD
step 2 − get values of a & b
step 3 − c ← a + b
step 4 − display c
step 5 − STOP
In design and analysis of algorithms, usually the second method is used to describe an
algorithm. It makes it easy for the analyst to analyze the algorithm ignoring all unwanted
definitions. He can observe what operations are being used and how the process is flowing.
Writing step numbers, is optional.
STACK
A stack is an Abstract Data Type (ADT), commonly used in most
programming languages. It is named stack as it behaves like a real-
world stack, for example – a deck of cards or a pile of plates, etc.

A real-world stack allows operations at one end only. For example, we can
place or remove a card or plate from the top of the stack only. Likewise,
Stack ADT allows all data operations at one end only. At any given time, we
can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out.
Here, the element which is placed (inserted or added) last, is accessed first.
In stack terminology, insertion operation is called PUSH operation and
removal operation is called POP operation.
Stack Representation
The following diagram depicts a stack and its operations −

A stack can be implemented by means of Array, Structure,


Pointer, and Linked List. Stack can either be a fixed size one
or it may have a sense of dynamic resizing. Here, we are
going to implement stack using arrays, which makes it a
fixed size stack implementation.
Basic Operations
• peek() − get the top data element of
Stack operations may involve
the stack, without removing it.
initializing the stack, using it and
then de-initializing it. Apart from • isFull() − check if stack is full.
these basic stuffs, a stack is used for • isEmpty() − check if stack is empty.
the following two primary operations At all times, we maintain a pointer to
− the last PUSHed data on the stack. As
• push() − Pushing (storing) an this pointer always represents the top
element on the stack. of the stack, hence named top. The
• pop() − Removing (accessing) an top pointer provides top value of the
element from the stack. stack without actually removing it.
When data is PUSHed onto stack. First we should learn about
procedures to support stack functions
To use a stack efficiently, we need to
check the status of stack as well. For
the same purpose, the following
functionality is added to stacks −
peek()

Algorithm of peek() function −

begin procedure peek


return stack[top]
end procedure
Implementation of peek() function in C programming
language −
int peek() {
return stack[top];
isfull()
Algorithm of isfull() function −

begin procedure isfull


if top equals to MAXSIZE
return true
else
return false
endif
end procedure
Implementation of isfull() function in C programming language −
bool isfull() {
if(top == MAXSIZE)
return true;
else
return false;
}
isempty()
Algorithm of isempty() function −

begin procedure isempty


if top less than 1
return true
else
return false
endif
end procedure
Implementation of isempty() function in C programming language is slightly
different. We initialize top at -1, as the index in array starts from 0. So we
check if the top is below zero or -1 to determine if the stack is empty. Here's
the code −
bool isempty() {
if(top == -1)
return true; else return false; }
Push Operation

The process of putting a new data element onto stack is known as a


Push Operation. Push operation involves a series of steps −
•Step 1 − Checks if the stack is full.
•Step 2 − If the stack is full, produces an error and exit.
•Step 3 − If the stack is not full, increments top to point next empty
space.
•Step 4 − Adds data element to the stack location, where top is
pointing.
•Step 5 − Returns success.
Algorithm for PUSH Operation
A simple algorithm for Push operation can be derived as follows −

begin procedure push: stack, data


if stack is full
return null
endif
top ← top + 1
stack[top] ← data
end procedure
Implementation of this algorithm in C, is very easy. See the following code −
void push(int data) {
if(!isFull()) {
top = top + 1; stack[top] = data;
}else { printf("Could not insert data, Stack is full.\n");
} }
Pop Operation
Accessing the content while removing it from the stack, is known
as a Pop Operation. In an array implementation of pop() operation, the
data element is not actually removed, instead top is decremented to a
lower position in the stack to point to the next value. But in linked-list
implementation, pop() actually removes data element and deallocates
memory space.
A Pop operation may involve the following steps −
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error and exit.
• Step 3 − If the stack is not empty, accesses the data element at which top
is pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success.
Algorithm for Pop Operation
A simple algorithm for Pop operation can be derived Implementation of this
as follows − algorithm in C, is as
follows −

begin procedure pop: stack


int pop(int data) {
if stack is empty
if(!isempty()) {
return null
data = stack[top];
endif
top = top - 1;
data ← stack[top]
return data;
top ← top - 1
}else {
return data
printf("Could not retrieve
end procedure
data, Stack is empty.\n");
} }
Stack Program in C
#include <stdio.h> int MAXSIZE = 8;
int stack[8]; int top = -1; int main() {
int isempty() { push items on to the stack push(3);
if(top == -1) return 1; else return 0; } push(5); push(9); push(1); push(12); push(15);
int isfull() { printf("Element at top of the stack: %d\n"
,peek());
if(top == MAXSIZE) return 1; else
return 0; } printf("Elements: \n");
int peek() { print stack data while(!isempty()) { int data =
pop();
return stack[top]; } int pop() { int data;
printf("%d\n",data);
if(!isempty()) { data = stack[top];
}
top = top - 1; return data; }else {
printf("Stack full: %s\n" ,
printf("Could not retrieve data, Stack is
isfull()?"true":"false");
empty.\n");
printf("Stack empty: %s\n" ,
}}
isempty()?"true":"false");
int push(int data) {
return 0;
if(!isfull()) { top = top + 1;
}
stack[top] = data; }else {
printf("Could not insert data, Stack is
full.\n");
} }
EVALUATION OF ARITHMETIC EXPRESSIONS
The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in
three different but equivalent notations, i.e., without changing the essence or output of an expression.
These notations are −
Infix Notation
Prefix (Polish) Notation
Postfix (Reverse-Polish) Notation
Infix Notation
We write expression in infix notation, e.g. a-b+c, where operators are used in-
between operands. It is easy for us humans to read, write, and speak in infix notation but the
same does not go well with computing devices. An algorithm to process infix notation could
be difficult and costly in terms of time and space consumption.
Prefix Notation
In this notation, operator is prefixed to operands, i.e. operator is written ahead of
operands. For example, +ab. This is equivalent to its infix notation a+b. Prefix notation is
also known as Polish Notation.
Postfix Notation
This notation style is known as Reversed Polish Notation. In this notation style,
the operator is postfixed to the operands i.e., the operator is written after the operands. For
example, ab+. This is equivalent to its infix notation a+b.
The following table briefly tries to show the difference in all three notations −
Sr.no Infix Notation Prefix Notation Postfix Notation

1 a+b +ab ab+

2 (a + b) * c *+abc ab+c*

3 a * (b + c) *a+bc abc+*

4 a/b+c/d +/ab/cd ab/cd/+

5 (a + b) * (c + d) *+ab+cd ab+cd+*

6 ((a + b) * c) - d -*+abcd ab+c*d-


Parsing Expressions
As multiplication operation has precedence
over addition, b * c will be evaluated first. A
As we have discussed, it is not a very table of operator precedence is provided later.
efficient way to design an algorithm or
program to parse infix notations. Instead, Associativity
these infix notations are first converted into Associativity describes the rule where
operators with the same precedence appear in
either postfix or prefix notations and then
an expression. For example, in expression
computed. a+b−c, both + and – have the same precedence,
To parse any arithmetic expression, we need then which part of the expression will be
to take care of operator precedence and evaluated first, is determined by associativity
of those operators. Here, both + and − are left
associativity also. associative, so the expression will be evaluated
as (a+b)−c.
Precedence
Precedence and associativity determines the
When an operand is in between two order of evaluation of an expression. Following
different operators, which operator will take is an operator precedence and associativity
the operand first, is decided by the table (highest to lowest) −
precedence of an operator over others. For
example −
Sr.
Operator Precedence Associativity
No.
1 Exponentiation ^ Highest Right Associative

2 Multiplication ( * ) & Division ( / ) Second Highest Left Associative

3 Addition ( + ) & Subtraction ( − ) Lowest Left Associative

The above table shows the default behavior of operators. At any point of time in
expression evaluation, the order can be altered by using parenthesis. For example . In
a+b*c, the expression part b*c will be evaluated first, with multiplication as
precedence over addition. We here use parenthesis for a+b to be evaluated first, like
(a+b)*c.
Postfix Evaluation Algorithm
We shall now look at the algorithm on how to evaluate postfix notation −
Step 1 − scan the expression from left to right
Step 2 − if it is an operand push it to stack
Step 3 − if it is an operator pull operand from stack and perform operation
Step 4 − store the output of step 3, back to stack
Step 5 − scan the expression until all operands are consumed
Step 6 − pop the stack and perform operation
QUEUE :
• It is a non-primitive, linear data structure, and a subclass of list data
structure.

• It is an ordered, homogeneous collection of elements in which elements


are appended at one end called REAR end, and elements are deleted at
other end called FRONT end.

• It follows First-in First-Out mechanism, in which elements comes first


will be removed first.

• Two operation are frequently carried on queue. They are insertion and
deletion.

• The insertion operation is possible only when the queue contains


elements less than the capacity it can hold.

• The deletion is possible when the queue contains at least one element.
• Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks,
a queue is open at both its ends. One end is always used to insert data
(enqueue) and the other is used to remove data (dequeue). Queue follows First-
In-First-Out methodology, i.e., the data item stored first will be accessed first.

Queue Representation
As we now understand that in queue, we access both ends for
different reasons. The following diagram given below tries to
explain queue representation as data structure −As in stacks, a
queue can also be implemented using Arrays, Linked-lists,
Pointers and Structures. For the sake of simplicity, we shall
implement queues using one-dimensional array.
Basic Operations
peek()
Queue operations may involve initializing or This function helps to see the data at
defining the queue, utilizing it, and then completely the front of the queue. The algorithm
erasing it from the memory. Here we shall try to of peek() function is as follows −
understand the basic operations associated with
queues − begin procedure peek
•enqueue() − add (store) an item to the queue.
return queue[front]
•dequeue() − remove (access) an item from the
queue.
end procedure
Few more functions are required to make the above- Implementation of peek() function in C
mentioned queue operation efficient. These are − programming language −
peek() − Gets the element at the front of the queue
without removing it. int peek()
isfull() − Checks if the queue is full. {
isempty() − Checks if the queue is empty. return queue[front];
In queue, we always dequeue (or access) data,
}
pointed by front pointer and while enqueing (or
storing) data in the queue we take help of rear
pointer.
Let's first learn about supportive functions of a
queue
isfull() isempty()
As we are using single dimension array Algorithm of isempty() function −
to implement queue, we just check for
begin procedure isempty
the rear pointer to reach at MAXSIZE
to determine that the queue is full. In if front is less than MIN OR front is
case we maintain the queue in a greater than rear return true
circular linked-list, the algorithm will else
differ. Algorithm of isfull() function − return false
begin procedure isfull endif
if rear equals to MAXSIZE end procedure
return true else If the value of front is less than MIN or
return false 0, it tells that the queue is not yet
Endif end procedure initialized, hence empty.
Implementation of isfull() function in C
programming language − bool isempty() {
bool isfull() { if(front < 0 || front > rear)
if(rear == MAXSIZE - 1) return true;
return true; else
Else return false; return false;
} }
Enqueue Operation

Queues maintain two data pointers, front and rear. Therefore, its
operations are comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue

Step 1 − Check if the queue is full.
Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next
empty space.
Step 4 − Add data element to the queue location, where the rear is
pointing.
Step 5 − Return success.
Algorithm for enqueue Operation

procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Implementation of enqueue() in C
programming language −
int enqueue(int data)
if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
Dequeue Operation

Accessing data from the queue is a process of


two tasks − access the data where front is
pointing and remove the data after access.
The following steps are taken to perform

dequeue operation −

• Step 1 − Check if the queue is empty.


• Step 2 − If the queue is empty, produce
underflow error and exit.
• Step 3 − If the queue is not empty, access
the data where front is pointing.
• Step 4 − Increment front pointer to point to
the next available data element.
• Step 5 − Return success.
int intArray[MAX];
Algorithm for dequeue Operation
int front = 0;
int rear = -1;
procedure dequeue
int itemCount = 0;
if queue is empty
int peek(){
return underflow
return intArray[front];
end if
}
data = queue[front]
bool isEmpty(){
front ← front + 1
return itemCount == 0;
return true
}
end procedure
bool isFull(){
Implementation of dequeue() in C
return itemCount == MAX;
programming language −
}
int dequeue() {
int size(){
if(isempty())
return itemCount;
return 0;
}
int data = queue[front];
void insert(int data){
front = front + 1;
if(!isFull()){
return data;
}
Implementation in C
#include <stdio.h> #include <string.h>
#include <stdlib.h> #include <stdbool.h>
#define MAX 6
if(rear == MAX-1) { rear = -1; } // front : 1
intArray[++rear] = data; // rear : 5
itemCount++; } } // -------------------
int removeData() { // index : 1 2 3 4 5
int data = intArray[front++]; // -------------------
if(front == MAX) { front = 0; } // queue : 5 9 1 12 15
itemCount--; return data; } // insert more items insert(16);
int main() { // front : 1
/* insert 5 items */ // rear : -1
insert(3); insert(5); insert(9); // ----------------------
insert(1); insert(12); // index : 0 1 2 3 4 5
// front : 0 // ----------------------
// rear : 4 // queue : 16 5 9 1 12 15
// ------------------ //As queue is full, elements will not be inserted. insert(17); insert(18);
// index : 0 1 2 3 4 // ----------------------
// ------------------ // index : 0 1 2 3 4 5
// queue : 3 5 9 1 12 insert(15); // ----------------------
// front : 0 //queue : 16 5 9 1 12 15
// rear : 5 printf("Element at front: %d\n",peek());
// --------------------- printf("----------------------\n");
// index : 0 1 2 3 4 5 printf("index : 5 4 3 2 1 0\n");
// --------------------- printf("----------------------\n");
// queue : 3 5 9 1 12 15 printf("Queue: "); while(!isEmpty()){
if(isFull()){ int n = removeData(); printf("%d ",n); } }
printf("Queue is full!\n");
}
// remove one item
int num = removeData();
printf("Element removed: %d\n",num);
Linked List
A linked list is a sequence of data
structures, which are connected together via
links.

Linked List is a sequence of links which


As per the above illustration, following are the
contains items. Each link contains a
important points to be considered.
connection to another link. Linked list is the
• Linked List contains a link element called first.
second most-used data structure after
• Each link carries a data field(s) and a link field
array. Following are the important terms to called next.
understand the concept of Linked List.
• Each link is linked with its next link using its
Link − Each link of a linked list can store a next link.
data called an element. • Last link carries a link as null to mark the end of
Next − Each link of a linked list contains a the list.
link to the next link called Next. Types of Linked List
Linked List − A Linked List contains the Following are the various types of linked list.
connection link to the first link called First. • Simple Linked List − Item navigation is forward
Linked List Representation only.
• Doubly Linked List − Items can be navigated
Linked list can be visualized as a
forward and backward.
chain of nodes, where every node points to
• Circular Linked List − Last item contains link of
the next node. the first element as next and the first element has a
link to the last element as previous.
Basic Operations Imagine that we are inserting a node B
(NewNode), between A (LeftNode) and C
Following are the basic operations supported (RightNode). Then point B.next to C -
by a list.
• Insertion − Adds an element at the
beginning of the list.
• Deletion − Deletes an element at the
beginning of the list.
• Display − Displays the complete list.
• Search − Searches an element using the
given key.
• Delete − Deletes an element using the given
key. Now, the next node at the left should point to the new
Insertion Operation node.
Adding a new node in linked list is
a more than one step activity. We shall learn
this with diagrams here. First, create a node
using the same structure and find the
location where it has to be inserted.
This will put the new node in the middle of the two. The new list should look
like this −

Similar steps should be taken if the node is being inserted at the beginning of the list.
While inserting it at the end, the second last node of the list should point to the new
node and the new node will point to NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial
representation.
First, locate the target node to be removed, by using searching algorithms.

The left (previous) node of the target node now should point to the next
node of the target node −

LeftNode.next −> TargetNode


This will remove the link that was pointing to the target node. Now, using the following code, we will remove what
the target node is pointing at.
TargetNode.next −> NULL;

We need to use the deleted node. We can keep that in memory otherwise we can simply deallocate memory and
wipe off the target node completely.

Reverse Operation
This operation is a thorough one. We need to make the last node to be pointed by the head node and reverse the
whole linked list.
First, we traverse to the end of the list. It should be pointing to NULL. Now, we shall make it point to
its previous node −

We have to make sure that the last node is not the lost node. So we'll have some temp node, which
looks like the head node pointing to the last node. Now, we shall make all left side nodes point to their
previous nodes one by one.

Except the node (first node) pointed by the head node, all nodes should point to their predecessor, making
them their new successor. The first node will point to NULL.
We'll make the head node point to the new first node by using the temp node.

Doubly Linked List is a variation of Linked list in which navigation is possible in both ways, either forward and
backward easily as compared to Single Linked List. Following are the important terms to understand the concept of
doubly linked list.
• Link − Each link of a linked list can store a data called an element.
• Next − Each link of a linked list contains a link to the next link called Next.
• Prev − Each link of a linked list contains a link to the previous link called Prev.
• Linked List − A Linked List contains the connection link to the first link called First and to the last link called Last.

DOUBLE LINKED LIST REPRESENTATION

As per the above illustration, following are the important points to be considered.
• Doubly Linked List contains a link element called first and last.
• Each link carries a data field(s) and a link field called next.
• Each link is linked with its next link using its next link.
• Each link is linked with its previous link using its previous link.
• The last link carries a link as null to mark the end of the list.
Basic Operations
Following are the basic operations supported by a list.
• Insertion − Adds an element at the beginning of the list.
• Deletion − Deletes an element at the beginning of the list.
• Insert Last − Adds an element at the end of the list.
• Delete Last − Deletes an element from the end of the list.
• Insert After − Adds an element after an item of the list.
• Delete − Deletes an element from the list using the key.
• Display forward − Displays the complete list in a forward manner.
• Display backward − Displays the complete list in a backward manner.

Insertion Operation
Following code demonstrates the insertion operation at the beginning of a doubly
linked list.
//insert link at the first location
void insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key; link->data = data; if(isEmpty()) {
//make it the last link last = link; }else {
//update first prev link head->prev = link; }
//point it to old first link
link->next = head;
//point first to new first link
head = link; }
Deletion Operation Insertion at the End of an Operation
Following code demonstrates the Following code demonstrates the insertion
deletion operation at the operation at the last position of a doubly linked
beginning of a doubly linked list. list.
//delete first item //insert link at the last location
struct node* deleteFirst() { void insertLast(int key, int data) {
//save reference to first link //create a link
struct node *tempLink = head; struct node *link = (struct node*)
//if only one link malloc(sizeof(struct node));
if(head->next == NULL) { link->key = key;
last = NULL; link->data = data;
}else { if(isEmpty()) {
head->next->prev = NULL; //make it the last link
} last = link;
head = head->next; }else {
//return the deleted link //make link a new last link
return tempLink; last->next = link;
} //mark old last node as prev of new link
link->prev = last;
}
//point last to new last node
last = link;
}
Tree represents the nodes connected by edges. We will discuss binary tree or binary search tree
specifically.
Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special
condition that each node can have a maximum of two children. A binary tree has the benefits of
both an ordered array and a linked list as search is as quick as in a sorted array and insertion or
deletion operation are as fast as in linked list.
Important Terms
Following are the important terms with respect to tree.
• Path − Path refers to the sequence of nodes along the edges of a tree.
• Root – The node at the top of the tree is called root. There is only one root per tree and one path from the root node to
any node.
• Parent − Any node except the root node has one edge upward to a node called parent.
• Child – The node below a given node connected by its edge downward is called its child node.
• Leaf – The node which does not have any child node is called the leaf node.
• Subtree − Subtree represents the descendants of a node.
• Visiting − Visiting refers to checking the value of a node when control is on the node.
• Traversing − Traversing means passing through nodes in a specific order.
• Levels − Level of a node represents the generation of a node. If the root node is at level 0, then its next child node is at
level 1, its grandchild is at level 2, and so on.
• Keys − Key represents a value of a node based on which a search operation is to be carried out for a node.

Binary Search Tree Representation


Binary Search tree exhibits a special behavior. A node's left child must have a value less than its
parent's value and the node's right child must have a value greater than its parent value.
Tree Node Insert Operation
The code to write a tree node would be The very first insertion creates the
similar to what is given below. It has a data part tree. Afterwards, whenever an element is to be
and references to its left and right child nodes. inserted, first locate its proper location. Start
struct node { searching from the root node, then if the data is
int data; less than the key value, search for the empty
struct node *leftChild; location in the left subtree and insert the data.
struct node *rightChild; Otherwise, search for the empty location in the
}; right subtree and insert the data.
In a tree, all nodes share common construct. Algorithm
BST Basic Operations If root is NULL then create root node
The basic operations that can be performed on a return
binary search tree data structure, are the If root exists then compare the data with node.
following − data
• Insert − Inserts an element in a tree/create a while until insertion position is located
tree. If data is greater than node. data goto right
• Search − Searches an element in a tree. subtree
• Pre-order Traversal − Traverses a tree in a pre- else
order manner. goto left subtree
• In-order Traversal − Traverses a tree in an in- endwhile
order manner. insert data
• Post-order Traversal − Traverses a tree in a end If
post-order manner.
Search Operation • In-order Traversal
Whenever an element is to be searched,
start searching from the root node, then if the data is • Pre-order Traversal
less than the key value, search for the element in the • Post-order Traversal
left subtree. Otherwise, search for the element in the We shall now look at the implementation
right subtree. Follow the same algorithm for each
of tree traversal in C programming
node.
Algorithm language here using the following binary
If root.data is equal to search.data tree
return root
else
while data not found
If data is greater than node.data
goto right subtree
else
goto left subtree
If data found
return node
endwhile
return data not found
end if
Tree Traversal in C
Traversal is a process to visit all the nodes of a tree
and may print their values too. Because, all nodes
are connected via edges (links) we always start from
the root (head) node. That is, we cannot random
access a node in a tree. There are three ways which
we use to traverse a tree
Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes
are connected via edges (links) we always start from the root (head) node. That is, we cannot randomly
access a node in a tree. There are three ways which we use to traverse a tree −
• In-order Traversal
• Pre-order Traversal
• Post-order Traversal
Generally, we traverse a tree to search or locate a given item or key in the tree or to print all the values
it contains.
In-order Traversal
In this traversal method, the left subtree is visited first, then the root and later the right sub-tree.
We should always remember that every node may represent a subtree itself.
If a binary tree is traversed in-order, the output will produce sorted key values in an ascending order.
We start from A, and following in-order
traversal, we move to its left subtree B. B is also
traversed in-order. The process goes on until all
the nodes are visited. The output of in-order
traversal of this tree will be −
D→B →E →A→F→C→G
Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.
Pre-order Traversal
In this traversal method, the root node is Algorithm
visited first, then the left subtree and finally the right Until all nodes are traversed −
subtree. Step 1 − Visit root node.
Step 2 − Recursively traverse left subtree.
Step 3 − Recursively traverse right subtree.
Post-order Traversal
In this traversal method, the root node is
visited last, hence the name. First we traverse the left
subtree, then the right subtree and finally the root node.

We start from A, and following pre-order


traversal, we first visit A itself and then move to its left
subtree B. B is also traversed pre-order. The process goes
on until all the nodes are visited. The output of pre-order
traversal of this tree will be −
A→B→D→E→C→F→G
We start from A, and following pre-order traversal, we first visit the left subtree B. B is also
traversed post-order. The process goes on until all the nodes are visited. The output of post-
order traversal of this tree will be −
D→E→B→F→G→C→A
Algorithm
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Recursively traverse right subtree.
Step 3 − Visit root node.

You might also like