Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 48

CS6202 PROGRAMMING AND DATA STRUCTURES

SYLLABUS

CS6202 PROGRAMMING AND DATA STRUCTURES

UNIT I C PROGRAMMING FUNDAMENTALS- A REVIEW 9


Conditional statements – Control statements – Functions – Arrays – Preprocessor - Pointers
- Variation in pointer declarations – Function Pointers – Function with Variable number of
arguments.

UNIT II C PROGRAMMING ADVANCED FEATURES 9


Structures and Unions - File handling concepts – File read – write – binary and Stdio - File
Manipulations.

UNIT III LINEAR DATA STRUCTURES – LIST 9


Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list
implementation –– singly linked lists- circularly linked lists- doubly-linked lists –
applications of lists –Polynomial Manipulation – All operation (Insertion, Deletion, Merge,
Traversal).

UNIT IV LINEAR DATA STRUCTURES – STACKS, QUEUES 9


Stack ADT – Evaluating arithmetic expressions- other applications- Queue ADT – circular
queue Implementation – Double ended Queues – applications of queues.

UNIT V SORTING, SEARCHING AND HASH TECHNIQUES 9


Sorting algorithms: Insertion sort - Selection sort - Shell sort - Bubble sort - Quick sort -
Merge sort - Radix sort – Searching: Linear search –Binary Search Hashing: Hash Functions
– Separate Chaining – Open Addressing – Rehashing – Extendible Hashing.

TOTAL: 45 PERIODS
TEXT BOOKS:

1. Brian W. Kernighan and Dennis M. Ritchie, “The C Programming Language”, 2nd


Edition, Pearson Education, 1988.
2. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C”, 2nd Edition,
Pearson Education, 1997.

REFERENCES:

1. Thomas H. Cormen, Charles E. Leiserson, Ronald L.Rivest, Clifford Stein,


“Introduction to Algorithms", Second Edition, Mcgraw Hill, 2002.
2. Reema Thareja, “Data Structures Using C”, Oxford University Press, 2011
3. Aho, Hopcroft and Ullman, “Data Structures and Algorithms”, Pearson
Education,1983.
4. Stephen G. Kochan, “Programming in C”, 3rd edition, Pearson Ed.,

Unit 1 Page 1
CS6202 PROGRAMMING AND DATA STRUCTURES

UNIT I

C PROGRAMMING FUNDAMENTALS- A REVIEW

Conditional statements – Control statements – Functions – Arrays – Preprocessor -


Pointers - Variation in pointer declarations – Function Pointers – Function with
Variable number of arguments.

CONDITIONAL STATEMENTS

 Conditional statements are features of a programming language, which perform


different computations or actions depending on whether a condition evaluates to
true or false.
 Program control is transferred from one point to another based on some condition.
 The conditional statements are
o if statements
o if…..else statements
o nested if….else statements
o switch statements
if statements
 if is a c keyword.
 The if statement is a decision making statement
 It has only one option.
 The set of statements are executed only when logical condition is true.
if (condition)
{ Condition
statement -1;
statement -2; Statements
}

Unit 1 Page 2
CS6202 PROGRAMMING AND DATA STRUCTURES

Eg: Write a program to check equivalence of two numbers


#include < stdio.h> Output
#include < conio.h> Enter two numbers: 5 5
main ( ) Two numbers are equal.
{
int m, n;
clrscr ( );
printf (“\n Enter two numbers:”);
scanf(“%d%d”,&m,&n);
if ( m- n = = 0)
printf(“\n Two numbers are equal.”);
getch ( );
}
if ……..else statement
 It is two way decision making statement
 if…..else statement take care of true as well as false condition..
 It has two block if & else
 if block is executed when the condition is true; else block is executed when the
condition is false.
Syntax:
if(condition is true)
False True
{ Condition
statement 1;
statement 2;;
Statements
} Statements

else
{
statement 3;
statement 4;
}

Unit 1 Page 3
CS6202 PROGRAMMING AND DATA STRUCTURES

Eg:/* Given number is odd (or) even */


#include<stdio.h>
#include<conio.h>
void main()
{
int num,rem;
clrscr();
printf(“Enter ur number”);
scanf(“%d”,&num);
rem=num%2;
if(rem==0)
printf(“the number is even”);
else
printf(“the number is odd”);
getch();
}
Output:
Enter the number 2
The number is even

Nested if……else statement


 In this statement, numbers of logical conditions are checked for executing various
conditions.
 if…..else statement is written in another if….else statement called nesting and the
statement is called nested if
Syntax:
if(condition 1)
{
if(condition 2)
{
statement 2;

Unit 1 Page 4
CS6202 PROGRAMMING AND DATA STRUCTURES

}
False
else Condition 1
{
True Statements
statement 2; False
Condition 2
}
} True
else Statements
Statements
{
statement 1;
}

Example:Write a program to find the maximum of three numbers using Nested if else
statement.
#include < stdio.h> Output
#include <conio.h> Enter the value of a & b: 7 8 5
void main ( ) b = 8 is greater.
{
int a, b,c;
clrscr( );
printf (“\n Enter the value of a, b, c:”);
scanf (“%d %d %d”, &a, &b, &c);
if(a>b && a>c)
printf(“\n a= %d is greater”, a);
else if (b>c)
printf(“\n b= %d is greater”, b);
else
printf(“\n c= %d is greater”, c);
getch( );
}

Unit 1 Page 5
CS6202 PROGRAMMING AND DATA STRUCTURES

The switch( ) case statement


 The switch ( ) statement is a multi way branch statement.
 The switch ( ) statement requires only one argument of any data type, which is
checked with number of case options.
 The switch ( ) statement evaluates expression and then looks for its value among
the case constants.
 If the value matches with case constant, this particular case statement is executed.
 If not, default is executed.
 Here switch, case, and default are reserved keywords.
 Every case statement terminates with ‘:’.
 The break statement is used to exit from the current case structure.
 The switch ( ) statement is useful for writing menu driven program.
Syntax
switch (variable or expression)
{
case constant A:
statement;
break;
case constant B:
statement;
break;
default:
statement;
}
Eg:
Write a program to perform1. Addition 2. Substraction 3. Multiplication 4.
Division 5. Remainder using switch() statement.
#include <stdio.h>
#include <conio.h>
int main()
{

Unit 1 Page 6
CS6202 PROGRAMMING AND DATA STRUCTURES

int a,b,c, ch;


clrscr();
printf(“\t=============”);
printf(“\n\t MENU”);
printf(“\t=============”);
printf(“\n\t[1] ADDITION”);
printf(“\n\t[2] SUBSTRACTION”);
printf(“\n\t[3] MULTIPLICATION”);
printf(“\n\t[4] DIVISION”);
printf(“\n\t[5] REMAINDER”);
printf(“\n\t[0] EXIT”);
printf(“\n\t=============”);
printf(“Enter your choice”);
scanf(“%d”, &ch);
if (ch <=5 & ch>0)
{
printf (“Enter Two Numbers:”);
scanf(“%d%d”, &a, &b);
}
switch(ch)
{
case 1:
c=a+b;
printf(“\n Sum: %d”, c);
break;
case 2:
c=a-b;
printf(“\n Difference : %d”, c);
break;
case 3:
c=a*b;

Unit 1 Page 7
CS6202 PROGRAMMING AND DATA STRUCTURES

printf(“\n Product : %d”, c);


break;
case 4:
c=a/b;
printf(“\n Quotient : %d”, c);
break;
case 5:
c=a%b;
printf(“\n Remainder : %d”, c);
break;
case 0:
printf(“\n Terminated by choice”);
exit();
break;
default:
printf(\n Invalid choice”);
}
getch();
}

Output
MENU
=================
[1] ADDITION
[2] SUBSTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[0] EXIT
=================

Unit 1 Page 8
CS6202 PROGRAMMING AND DATA STRUCTURES

Enter your choice 2


Enter two numbers 9 5
Difference: 4

CONTROL STATEMENTS
 Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed.
 They make it possible to make decisions, to perform tasks repeatedly or to jump from
one section of code to another.
 Loop:
A loop is defined as a block of statements which are repeatedly executed for certain
number of times.
 Three types of loop control statements
1. for
2. while
3. do-while
for loop
The for loop is used to execute set of instructions repeatedly until the condition is
false.
Syntax of for loop:
for(initialize counter; test condition; increment/decrement counter)
{
statement 1;
statement 2;
}
(i) Initialise counter:
It is used to initialize the counter variable
(ii) Test condition:
It is used to test the condition.
(iii) Increment / decrement counter:

Unit 1 Page 9
CS6202 PROGRAMMING AND DATA STRUCTURES

It is used to Increment / decrement the counter variable


Ex: Program to find the sum of the series 1+2+3+…+10
#include<stdio.h>
#include<conio.h>
main()
{
int i, sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
printf(“The addition of numbers upto 10 is %d”,sum);
getch();
}
Output:
The addition of numbers upto 10 is 55

Nested for loop


For loops are placed within the body of another for loop is called nested for loop.

While loop:
 It is repetitive control structure used to execute the statements within the body
until the condition becomes false.
Syntax:
while(test condition)
{ Test Condition? Stop
body of the loop;
}
Body of the loop

Unit 1 Page 10
CS6202 PROGRAMMING AND DATA STRUCTURES

 The while loop is top driven loop. The condition is evaluated first and if it is true,
then the body of the loop is executed.
 After executing the body of the loop, the condition is once again evaluated and if it is
true, the body is executed once again.
 This process is repeated until the condition becomes false
 Then the control is transferred out of the loop.

Eg: Sum of given number using while loop.


#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+1;
i++;
}
printf(“the sum of numbers upto 10 is %d”);
getch();
}
Output:
the sum of numbers upto 10 is 84

The do – while loop


Syntax
do Body of the loop

{
statement; Condition

}
while(condition);

Unit 1 Page 11
CS6202 PROGRAMMING AND DATA STRUCTURES

 Here the condition is checked at the end of the loop.


 The do while loop will executed at least one time even if the condition is false
initially.
 The do-while loop executes until the condition becomes false.

Addition of two numbers upto 10 by using the do - while loop


#include <stdio.h>
main ( ) Output
{ The sum of numbers upto 10 is 55.
int i = 1, sum = 0;
do
{
sum = sum + i;
i++;
}
while ( i<=10)
printf(“\n The sum of numbers upto 10 is %d”, sum);
}

Difference between while and do….while


While do….while
1. This is the top tested loop. 1. This is the bottom tested
2.The condition is first tested, if the 2. It executes the body once after it
condition is true, then the block is checks the condition, if it is true the
executed until the condition becomes body is executed until the condition
false. become false.
3.Loop is executed at least once even
3. Loop will not be executed if the through condition is false.
condition is false

Unit 1 Page 12
CS6202 PROGRAMMING AND DATA STRUCTURES

Jumping statements
1. break
2. continue
3. goto
4. return

The break statement


 The keyword break allows the programmers to terminate the loop.
 The break skips from the loop or block in which it is defined.
 The control then automatically goes to the first statement after the loop or block.

The continue statement


 The continue statement is used for continuing next iteration of loop statements.
 When it occurs in the loop it does not terminate, but it skips the statements after
this statement.
 It is useful when we want to continue the program without executing any part of the
program.
The goto statement
 This statement does not require any condition.
 This statement passes control anywhere in the program, that is control is
transferred to another part of the program without testing any condition.
 The user has to define goto statement as follows.
goto label;
Where, the label name must start with any character. Where label is the position
where the control is to be transferred.

The return statement


 General format return; or
return expression;
 A return statement terminates the execution of a function and returns the control to
the calling function.

Unit 1 Page 13
CS6202 PROGRAMMING AND DATA STRUCTURES

Example
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
clrscr();
printf(“\n Enter a number:”);
scanf(‘%d”, &x);
if(x%2 = = 0)
goto even;
else
goto odd.
even:
printf(“ \n %d is even number” , x);
odd:
printf(“\n %d is odd number”, x);
}
Output
Enter a number: 7
7 is odd number.
Difference between Break and Continue
Break Continue
Exits from current block or Loop takes next iteration.
loop.
Control passes to next Control passes to the beginning of the
statement. loop.
Terminates the program. Never terminates the program.

Unit 1 Page 14
CS6202 PROGRAMMING AND DATA STRUCTURES

FUNCTIONS
A function is a sub-program that contains one or more statements to perform a
specified task. The C language supports two types of functions
i) Library functions (Predefined Function)
ii) User defined functions
Use or need of functions
 The length of the source program can be reduced by dividing it into smaller
function.
 If we want to perform a task repetitively then it is not necessary to re-write the
particular block of the program again and again.
 Using functions, large programs can be reduced to smaller ones.
 It is easy to debug and find out the errors in it.
 It also increases readability.
Difference between user defined function and predefined function
The predefined or library functions are not required to be written by the
programmer. Their task is limited. The user can only use the functions but cannot change
or modify them.
Example: sqrt(81) gives result 9
The user defined function has to be written by the programmer at the time of
programming.
User defined functions
The function defined by the user according to their requirement is called user
defined function. The user can modify the function according to their requirement.
Working of function:
Whenever a function is called, control passes to the called function and working of
the calling function is temporarily stopped, when the execution of the called function is
completed then a control return back to the calling function and executes the next
statement.
Elements of User defined function:
i. Function declaration(prototype)
ii. Function call

Unit 1 Page 15
CS6202 PROGRAMMING AND DATA STRUCTURES

iii. Function definition


Function declaration(prototype) :
Function declaration is the process of declaring the function before they defined and
invoked. While declaring a function, follow the points given below.
a) The list of parameters must be separated by comma.
b) If the function does not return any value, then the return type void is must.
c) If there is no parameters simply place void in braces.
d) The data type of actual and formal parameters must match.
Syntax:
return-type function-name(parameter-list)
where, return-type is the return type of function.
function-name is the name of the function.
parameter-list are the list of parameters that the function can use.
Example: int add(int x, int y);

Function call :
A function can be called by typing the function name in a source program with
parameters.
Syntax : Example
function_name(); add();
function_name(parameters); add(a,b);
return_value = function_name(parameters); c=add(a,b);

Function definition :
It is the process of specifying and establishing the user defined function by
specifying all of its elements and characteristics to perform a particular task.
Parameters :
Parameters provide the data communication between the calling function and called
function. There are two types of parameters.
a) Actual Parameters
b) Formal Parameters

Unit 1 Page 16
CS6202 PROGRAMMING AND DATA STRUCTURES

main()
{
------
------
function_name(x,y,z); // Function call
------- Actual Arguments
-------
}
function_name(a,b,c) // Function definition
{ Formal arguments
-----
-----
return( ); // Return value
}
a) Actual argument: The arguments of calling function or function call are formal
arguments.These are transferred from the calling program(main program) to the
called program(function).
b) Formal arguments: The arguments of called function are formal arguments.
c) Function name: A function must follow the same rule as variable.
d) Argument/parameter list: The argument list contains variable names enclosed
within the parenthesis. The formal arguments receive values from the actual
argument.
Return statement
The return statement may or may not send back any values to the main
program.
Syntax: return; (or) return(exp)
Types of Functions
i. Functions with no arguments and no return values.
ii. Functions with arguments and no return values.
iii. Functions with arguments and return values.
iv. Functions with no arguments and return values.

Unit 1 Page 17
CS6202 PROGRAMMING AND DATA STRUCTURES

i)Functions with no arguments and no return values


In these functions there is no data transfer takes place between the calling function
and the called function. The called program does not receive any data from the calling
program and does not send back any value to calling program.

Syntax :
main( ) fun1( )
{ {
……… …………
fun1( ); …………
……… …………
} }

Eg: Addition of two numbers


void main( )
{
void add(void);
add( );
}
void add( )
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Sum = %d”,c);
}
Output :
Enter two numbers 10 20
Sum = 30

Unit 1 Page 18
CS6202 PROGRAMMING AND DATA STRUCTURES

ii)Functions with arguments and no return values


In these functions the data are transferred from the calling function to called
function. The called program receives some data from the calling program and does not
send back any values to calling program.

Syntax :

main() fun1(x,y)
{ {
……… …………
fun1(a,b); …………
……… …………
} }

Eg:
void main( )
{
void add(int, int);
int a,b; Output :
printf(“Enter two numbers”); Enter two numbers 10 20
scanf(“%d%d”,&a,&b); Sum = 30
add(a,b);
}
void add(int x, int y)
{
int z;
z= x+y;
printf(“Sum = %d”,z);
}

Unit 1 Page 19
CS6202 PROGRAMMING AND DATA STRUCTURES

iii)Functions with arguments and with return values.


Data is transferred between the calling function and called function. The
called program receives some data from the calling program and sends back a value
to the calling program.

Syntax :
main() data_type fun1(x,y)
{ {
……… …………
c = fun1(a,b); …………
……… return(z);
}
}

Example:
void main()
{ Output :
int add(int, int); Enter two numbers 10
20
int a,b,c; Sum = 30
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“Sum = %d”,c);
}
int add(int x, int y)
{
int z;
z= x+y;
return(z);
}

Unit 1 Page 20
CS6202 PROGRAMMING AND DATA STRUCTURES

iv) Functions with no arguments and with return values.


The calling program cannot pass any arguments to the called program but
the called program may send some return values to the calling program.

Syntax :
main() data_type fun1()
{ {
……… …………
c = fun1( ); …………
……… return(z);
} }

Example:
void main( ) Output :
{ Enter two numbers 10 20
int add( ); Sum = 30
c=add(a,b);
printf(“Sum = %d”,c);
}
int add( )
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c);
}

Unit 1 Page 21
CS6202 PROGRAMMING AND DATA STRUCTURES

Sample programs using function


Ex: 1 Program to generate Fibonacci series using function
void main( )
{
int n;
void fin(int);
printf(“\n Enter the value of n”);
scanf(“%d”, &n);
fib(n);
}
void fib(int n)
{
int i, f1 = 0, f2 = 1, f3;
for ( i=1; i<=n; i++)
{
f3 = f1 + f2;
printf(“%d\t”, f1);
f1 = f2;
f2 = f3;
}
}
Output
Enter the value of n 5
0 1 1 2 3

Ex: 2 Find maximum of three numbers using function


int max(int, int, int);
void main ( )
{
int a, b,c,d;
printf (“\n Enter three integer values:”);

Unit 1 Page 22
CS6202 PROGRAMMING AND DATA STRUCTURES

scanf (“%d %d %d”, &a, &b, &c);


d = max (a, b, c);
printf(“\n Maximum is %d”, d);
}
int max(int a, int b, int c)
{
int max;
if(a>b && a>c)
max = a;
else if (b>c)
max = b;
else
max = c;
return(max);
}
Output
Enter three integer values: 9 7 10
Maximum is 10

Ex: 3 Find the factorial of a given number using function


int factorial(int);
int fact = 1;
void main()
{
int n;
printf("Enter an integer number :");
scanf("%d",&n);
fact = factorial(n);
printf("The factorial of the given number=%d", fact);
}
int factorial(int n)

Unit 1 Page 23
CS6202 PROGRAMMING AND DATA STRUCTURES

{
int i;
for(i=1;i<=n;i++)
fact=fact*i;
return(fact);
}
Output
Enter an integer number: 5
The factorial of the given number is 120

Parameter passing Methods


In C language there are two ways that the parameters can be passed to a function,
they are
i. Call by value
ii. Call by reference
Call by value
 This method copies the values of actual parameters into the formal parameters of the
function.
 Here the changes of the formal parameters cannot affect the actual parameters,
because formal parameters are photocopy of actual parameters.
 Changes made to the formal arguments are local to the block of the called function.
 Once control returns back to the calling function the changes made will disappear.
Example: Swapping two numbers
void swap(int a, int b);
void main( )
{
int i=10, j=20;
printf(“i and j values before swapping : %d %d\n”,i,j);
swap(i, j);
printf(“i and j values after swapping : %d %d\n”,i,j);
}

Unit 1 Page 24
CS6202 PROGRAMMING AND DATA STRUCTURES

void swap(int a, int b)


{
int t;
t = a;
a = b;
b=t;
}
Output:
i and j values before swapping : 20 30
i and j values after swapping : 20 30

Ex : Find the cube of given value


int cube (int x) ;
void main( )
{
int n=5;
printf(“cube of %d is %d”,n, cube(n));
}
int cube(int)
{
x = x*x*x;
return(x);
}
Output:
Cube of 5 is 125

Call by reference
 The address of arguments are copied into the parameter inside the function, the
address is used to access the actual arguments used in the cell. In this example
program, pointers are passed to function.
 Here changes made in the arguments are permanent.

Unit 1 Page 25
CS6202 PROGRAMMING AND DATA STRUCTURES

 Here pointers are passed to function.


Example: Interchanging two values
void swap(int *a, int *b);
void main( )
{
int i=10, j=20;
printf(“i and j values before swapping : %d %d\n”,i,j);
swap(&i, &j);
printf(“i and j values after swapping : %d %d\n”,i,j);
}
void swap(int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b=t;
}
Output
i and j values before swapping : 20 30
i and j values after swapping : 30 20

ARRAYS
The ordinary variables are capable of storing one value at a time. Array variables are
able to store more than one value at a time.
Definition of array
An array is a collection of similar data types in which each element is located in
separate memory locations.
An array is a collection of similar dataitems that are stored under a common name.
Declaration of array
Declaration of an array is done as
int a[5];

Unit 1 Page 26
CS6202 PROGRAMMING AND DATA STRUCTURES

It tells the compiler that a is an integer type of array and can store 5 integers. The compiler
reserves 2 bytes of memory for each integer array element.

Array initialization
Array initialization is done as
int a[5]= { 1, 2, 3, 4, 5};
Here 5 elements are stored in an array a. The array elements are stored sequentially in
separate locations. Initialization of array elements begins from subscript 0. Array
elements are called by array names followed by the subscript value. E.g. a[0] refers to 1 st
element, a[1] refers to 2nd element and so on.

Characteristics of array
 Any particular element of an array can be modified separately without disturbing
other elements.
int a[5] = { 1, 2, 3, 4, 5}; a[4] = 10;
 Any element of an array a[ ] can be assigned to another ordinary variable or array
variable of its type. b = a[2]; a[3] = a[4];

One Dimensional Array

Element a[0] a[1] a[2] a[3] a[4]


Address 2000 2002 2004 2006 2008

Here the elements are stored in continuous memory locations. It is assumed that the
starting memory location is 2000. Each integer element requires 2 bytes. Therefore the
subsequent element appears after a gap of two locations.

Difference between character array and integer array.


In character array NULL(\0) character is automatically added at the end, whereas in
integer or other type of arrays no character is placed at the end.

Unit 1 Page 27
CS6202 PROGRAMMING AND DATA STRUCTURES

Program to sort the numbers in ascending order.


#include<stdio.h>
#include<conio.h>
void main( )
{
int i, j, n, num[10], temp;
clrscr( );
printf(“\n Enter how many numbers to sort:”);
scanf(“%d”, &n);
for(i=0; i<n; i++)
{
printf(“\n Enter Number %d:”,i+1);
scanf(“%d”, &num[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(num[i]>num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf(“\n The numbers in ascending order”);
for(i=0; i<n; i++)
printf(“%4d”, num[i]);
getch( );
}

Unit 1 Page 28
CS6202 PROGRAMMING AND DATA STRUCTURES

Output
Enter how many numbers to sort: 5
Enter Number 1: 8
Enter Number 2 : 3
Enter Number 3 : 2
Enter Number 4 : 1
Enter Number 5: 9
The numbers in ascending order
1 2 3 8 9

Program to search an element in the given array of elements


#include<stdio.h>
#include<conio.h>
void main( )
{
int i, j, n, num[10], key;
clrscr( );
printf(“\n Enter the number of elements:”);
scanf(“%d”, &n);
for(i=0; i<n; i++)
{
printf(“\n Enter Number %d:”,i+1);
scanf(“%d”, &num[i]);
}
printf(“Enter the element to be searched”);
scanf(“%d”, &key);
for(i=0; i<n; i++)
{
if(key==num[i])
{

Unit 1 Page 29
CS6202 PROGRAMMING AND DATA STRUCTURES

printf(“key found”);
found=1;
break;
}
}
if(found=0)
printf(“Key not found”);
getch();
}

Two Dimensional array


A two dimensional array is a rectangular display of elements with rows and
columns. The elements are shown in matrix form. The array elements are stored in one
continuous form in the memory. A two dimensional array is a collection of a number of one
– dimensional arrays, which are placed one after another.
Declaration of two dimensional array
Syntax data_type array_name[row_size][column_size];
Example int m[10][10];

Program to display the elements of a two dimensional array


void main ( )
{
int i, j;
int a[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
clrscr( );
printf(“\n Elements of an array”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf(“%5d”, a[i][j]);

Unit 1 Page 30
CS6202 PROGRAMMING AND DATA STRUCTURES

printf(“\n”);
}
}
}
Output
Elements of an array
1 2 3
4 5 6
7 8 9

Sample Programs using array


1. Finding the largest and smallest number in an array
#include<stdio.h>
int main( )
{
int a[50],size,i,big,small;
  printf("\nEnter the size of the array: ");
  scanf("%d",&size);
  printf("\nEnter %d elements in to the array: ", size);
  for(i=0;i<size;i++)
      scanf("%d",&a[i]);
  big=a[0];
  for(i=1;i<size;i++)
{
      if(big<a[i])
           big=a[i];
}
  printf("Largest element: %d",big);
   small=a[0];
  for(i=1;i<size;i++)
{

Unit 1 Page 31
CS6202 PROGRAMMING AND DATA STRUCTURES

      if(small>a[i])
           small=a[i];
  }
printf("Smallest element: %d",small);
  return 0;
}
Output:
Enter the size of the array: 4
Enter 4 elements in to the array: 2 7 8 1
Largest element: 8
Smallest element: 1

2. Program to sort set of strings in alphabetical order


#include<stdio.h>
#include<string.h>
void main()
{
char s[5][20],t[20];
int i,j;
clrscr();
printf("Enter any five strings : \n");
for(i=0;i<5;i++)
scanf("%s",s[i]);
for(i=1;i<5;i++)
{
for(j=1;j<5;j++)
{
if(strcmp(s[j-1],s[j])>0)
{
strcpy(t,s[j-1]);
strcpy(s[j-1],s[j]);

Unit 1 Page 32
CS6202 PROGRAMMING AND DATA STRUCTURES

strcpy(s[j],t);
}
}
}

printf("Strings in order are : \n");


for(i=0;i<5;i++)
printf("\t%s",s[i]);
getch();
}
Output :
Enter any five strings:
priya pravin pruni prabha arun
Strings in order are:
arun prabha pravin priya pruni

3. Transpose of the Matrix


The transpose of matrix interchanges rows and columns, that is the row elements
becomes column element and vice versa.
#include<stdio.h>
void main( )
{
int i, j, row, col, a[10][10];
printf(“\n Enter the order of matrix:”);
scanf(“%d%d”,&row, &col);
printf(“\n Enter the elements of matrix: \n”);
for(i=0; i<row;i++)
{
for(j=0;j<col;j++)
scanf(“%d”, &a[i][j]);
}

Unit 1 Page 33
CS6202 PROGRAMMING AND DATA STRUCTURES

printf (“\n Original Matrix is”);


for(i=0; i<row;;i++)
{
for(j=0;j<col;j++)
printf(“%4d” a[i][j]);
printf(“\n”);
}
printf(“\n The Matrix Transpose is \n”);
for(i=0; i<col;i++)
{
for(j=0;j<row;j++)
printf(“%4d”, a[j][i]);
printf(“\n”);
}
}

Output
Enter the order of matrix: 2 3
Enter the elements of matrix:
1 5 7 8 9 6
Original Matrix is
1 5 7
8 9 6
The Matrix Transpose is
1 8
5 9
7 6

4. Matrix Addition

Unit 1 Page 34
CS6202 PROGRAMMING AND DATA STRUCTURES

#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf("\nEnter the number of rows and columns for matrix : \n");
scanf("%d%d",&r,&c);
printf("\nEnter values of matrix A :");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
}
printf("\nEnter values of matrix B :");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<=c;j++)
c[i][j]=a[i][j]+b[i][j];
}

printf("\n The resultant matrix is \n\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
printf("%5d",c[i][j]);
printf("\n");

Unit 1 Page 35
CS6202 PROGRAMMING AND DATA STRUCTURES

}
}
Output
Enter the number of rows and columns of matrix A : 2 2
Enter the number of rows and columns of matrix B : 2 2
Enter the values of matrix A: 1 2 3 4
Enter the values of matrix B : 7 4 6 5
The resultant matrix is
8 6
9 9

5. Matrix multiplication
#include<stdio.h>
int main()
{
  int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,r1,r2,c1,c2;
  printf("\nEnter the row and column of first matrix");
  scanf("%d %d",&r1,&c1);
  printf("\nEnter the row and column of second matrix");
  scanf("%d %d",&r2,&c2);
  if(c1!=r2 )
{
      printf("Matrix mutiplication is not possible");
      printf("\nColumn of first matrix must be same as row of second matrix");
  }
  else
{
      printf("\nEnter the First matrix->");
      for(i=0;i<r1;i++)
       for(j=0;j<c1;j++)
            scanf("%d",&a[i][j]);

Unit 1 Page 36
CS6202 PROGRAMMING AND DATA STRUCTURES

      printf("\nEnter the Second matrix->");


      for(i=0;i<r2;i++)
       for(j=0;j<c2;j++)
            scanf("%d",&b[i][j]);
      }
      for(i=0;i<r1;i++)
       for(j=0;j<c2;j++)
            c[i][j]=0;
      for(i=0;i<r1;i++)
{
       for(j=0;j<c2;j++)
{
            for(k=0;k<c1;k++)
{
                c[i][j]= c[i][j]+a[i][k]*b[k][j];
            }
      }
  }
  printf("\n The multiplication of two matrix is\n");
  for(i=0;i<r1;i++)
{
      printf("\n");
      for(j=0;j<c2;j++)
{
           printf("%d\t",c[i][j]);
      }
  }
  return 0;
}

Output

Unit 1 Page 37
CS6202 PROGRAMMING AND DATA STRUCTURES

Enter the row and column of first matrix 2 2


Enter the row and column of second matrix 2 2
Enter the First matrix-> 1 2 3 4
Enter the Second matrix-> 5 6 7 2
The First matrix is
1 2
3 4
The Second matrix is
5 6
7 2
The multiplication of two matrix is
19 10
43 26

Preprocessor
Introduction
Preprocessor is a program that processes our source program before compilation.
These are placed before the main ( ) function in source program. The compiler examines
the preprocessor for any preprocessor directives. If there is any preprocessor directive, the
appropriate actions are taken and then the source program is moved for compilation. The
preprocessor operates under the following preprocessor directives.
i. File inclusion
ii. Macro Substitutions
iii. Conditional Inclusion

i. File Inclusion
This is used to include an external file, which contains functions or some other
macro definitions to our source program, so we need not rewrite that functions and
macros in our source program.
Syntax #include “file name” and #include<file name>

Unit 1 Page 38
CS6202 PROGRAMMING AND DATA STRUCTURES

Where file name is the name of the file that can be included in our source program.
When filename is quoted, it searches for that file in current directory and then in
standard directories. When the file is included in Angle brackets the included file is
searched only in standard directories.
ii. Macro Substitutions
This is used to define symbolic constants in the source program. The identifier or
string or integer defined is replaced by Macro substitution.
Syntax: #define identifier string / integer.
The preprocessor accomplish the task specified in #define statement. This
statement is also placed before the main ( ) function in source program. The
preprocessor replaces the every occurrence of an identifier by the specified string or
integer in source program.
There are three different forms of macros.
Example:
#define A 10
#define CITY “CHENNAI”
The #define A 10 macro substitutes ‘A’ with 10 in all occurrences in the source
program.

Write a program to print the values using macro substitution.


#include<stdio.h>
#include<conio.h>
#define VAL 30
#undef VAL
#define VAL 40
void main( )
{
clrscr( );
printf(“\n The value is %d”, VAL);
getch( );
}

Unit 1 Page 39
CS6202 PROGRAMMING AND DATA STRUCTURES

Output
The value is 40
iii. Conditional Inclusion
These are used to control the preprocessor with conditional statements.
The preprocessor directives are
#if ,#else ,#elif, #endif these directives allow you to conditionally include portions of
code based on the outcome of the expression.
Eg: #define MAX 10
void main( )
{
#if MAX>100
printf(“ max above 100”);
#else
printf(“max below 100”);
endif
}
#if is associated with endif. In the above code the else part is compiled, #else directive
works much like the else. #elif means elseif, establishes an if-else-if chain for multiple
compilation option.
#ifdef, #ifndef , #undef:
#ifdef means if defined ,. #ifndef means if not defined
Syntax:
#ifdef macro-name
Statements;
endif
#ifndef macro-name
Statements;
endif
Eg:
#define TED 10
void main()

Unit 1 Page 40
CS6202 PROGRAMMING AND DATA STRUCTURES

{
#ifdef TED
printf(“hi TED”);
#else
printf(“hi anyone”);
#endif
#ifndef RALPH
printf(“RALPH not defined”);
#endif
}
The above program will print hi TED and RALPH not defined.
#undef – removes a previously defined definition of the macro name that follows it.
#undef macroname
#define LEN 100
-----
-----
#undef LEN //LEN undefined at this point
Rules for Defining Preprocessor
 Every processor must start with # symbol.
 The preprocessor is always placed before main ( ) function.
 The preprocessor cannot have termination with semicolon.
 There is no assignment operator in #define statement.
 The conditional macro must be terminated (#ifdef, #endif).

POINTERS
Introduction to Pointer
A pointer is a memory variable. It contain the memory address of another variable.
It is declared in the same manner like other variables. It is always denoted by ‘*’
operator.

Unit 1 Page 41
CS6202 PROGRAMMING AND DATA STRUCTURES

A pointer is a variable; its value is also an address. Each variable has two
attributes: address and value. A variable can take any value specified by its data type.
A pointer to an integer is a variable that can store the address of that integer.
Features of Pointer
 Pointers are used for saving memory space.
 Using the pointer, execution time is decreased, because data is directly accessed from
memory.
 Pointers reduce the length and complexity of the program.
 The pointer assigns the memory space and also releases the memory. Dynamically
memory is allocated.
 We can efficiently access the memory with pointers.
Advantages of using Pointer
 Pointers are more compact and efficient code.
 Pointers can be used to achieve clarity and simplicity.
 Pointers are used to pass information between function and its reference point.
 Pointers enable us to access the memory directly.
 Pointers also provide an alternate way to access an array element.
Variation in pointer declarations

Pointer Declaration
Pointer is a variable, it contain the address of another variable. The pointer variable
can be declared as
Syntax: datatype *pointer_name;
Where datatype specifies the type of data to which the pointer point. Pointer name
specifies the name of the pointer. It must preceded with an (*) asterisk. The asterisk
operator is called indirection operator. Another name for the indirection operator is the
dereferencing operator.
Example:
int *x; - Here x is an integer pointer. It contains the address of integer variable.
float *y; - Here y is an float pointer. It contains the address of float variable.

Unit 1 Page 42
CS6202 PROGRAMMING AND DATA STRUCTURES

char *z; - Here z is an character pointer. It contains the address of character


variable.
Pointer Initialization
The process of assigning the address of a variable to a pointer variable is known as
initialization. The address of the variable is accessed through an ampersand (&) sign. We
can use the assignment operator to initialize the pointer variable.
Example: int *x; int y = 10; x = &y;
 In declaration (*) indicates that it is a pointer variable.
 In dereference (*) indicates the value stored in the memory address of pointer
variable.
 The ‘&’ is the address operator. It represents the address of the variable.
Accessing data through pointers
Once the pointer is declared and assigned to the address of another variable, the
variable can be accessed through its pointer.
Program to accessing variable through pointer variable.
#include<stdio.h>
void main( )
{
int a = 10, *x;
float b = 2.5, *y;
x = &a;
y = &b;
printf(“\n The value of x = %d”,* x);
printf(“\n The value of y = %f”, *y);
getch( );
}

Program to print the address and value of variable.


#include<stdio.h>
void main( )
{
int a = 10, *x;
x = &a;
printf(“\n Value of x = %d”,* x);
printf(“\n Address of x = %u”, x);
printf(“\n Value at address %u = %d”, x, *x);
Unit 1 Page 43
CS6202 PROGRAMMING AND DATA STRUCTURES

getch( );
}

Program to add two numbers through variables and their pointers


#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, c, d. *ap, *bp;
printf(“\n Enter two numbers”);
scanf(“%d %d”, &a, &b);
ap = &a;
bp = &b;
c = a+b;
d = *ap + *bp;
printf(“\n Sum of a & b using variable: %d”, c);
printf(“\n Sum of a & b using pointer: %d”, d);
}
Null Pointer
A pointer is said to be a null pointer when its right value is 0. A null pointer can
never point to a valid data. For checking a pointer, if it is assigned to 0, then it is a null
pointer and is not valid.
Example: int *a; int *b; b = a =0;
Hence b and a become null pointers after the integer value of 0 is assigned to them.

Pointer to Pointer
The pointer is known as a variable containing address of another variable. The
pointer variable also has an address. The pointer variable containing address of another
pointer variable is known as pointer to pointer.

Program to print value of a variable through pointer and pointer to pointer.


void main( )
{
int a = 2, *p, **q;
p = &a;
q = &p;

Unit 1 Page 44
CS6202 PROGRAMMING AND DATA STRUCTURES

printf(“\n The value of a = %d Address of a = %u”, a, &a);


printf(“\n Through *p value of a = %d, Address of a =%u”, *p, p);
printf(“\n Through **q value of a = %d Address of a = %d”, **q,*q);
getch( );
}

void Pointers
Pointers can also be declared as void type. Void pointers cannot be dereferenced
without explicit type conversion. This is because; being void the compiler cannot determine
the size of the object that the pointer points to. Though void pointer declaration is possible,
void variable declaration is not allowed.

Write a program to declare a void pointer. Assign address of int, float and char
variables to the void pointer using type casting method. Display the contents of
various variables.
#include<stdio.h>
#include<conio.h>
int p;
float d;
char c;
void *pt ;
void main( )
{
pt = &p;
*(int*)pt = 12;
printf(“\n p = %d”, p);
pt = &d;
*(float*)pt=5.4;
printf(“\n d = %f”,d);
pt = &c;
*(char*)pt=’s’;
printf(“\n c = %c”,c);
}

Function Pointers

Unit 1 Page 45
CS6202 PROGRAMMING AND DATA STRUCTURES

Function pointers (pointers to functions) are interesting and powerful tool in C. A


function has a physical location in memory that can be assigned to a pointer. This address
is the entry point of the function and it is the address used when the function is called.
A Simple Function and Function Pointer
To print out the message hello world
#include <stdio.h>
void Hello( )
{
   printf("hello world\n");
}
void main( )
{
  Hello( );
}
Here we have a function called Hello( ). This function returns nothing (void) and
doesn’t take any parameters. We call the function from main and it prints out “hello world”.
Now let’s convert main to use a function pointer instead of calling the function directly.
int main( )
{
   void (*HelloPtr)( ) = Hello;
   (*HelloPtr)( );
}
We have the pointer name HelloPtr. We must have parentheses around the pointer
(*HelloPrt). function pointers must have parentheses around them. void (*HelloPtr)( ) is , a
pointer to a function that returns void and takes no parameters.In (*HelloPtr)() = Hello,
the address of the function Hello can be assigned to a function pointer HelloPtr,We call our
function pointer using (*HelloPtr)( ).
Function with Variable number of arguments

A Function Pointer with Parameters


Now let us create a function pointer with parameters.
 void subtract(int x, int y); // function prototype
void subtract(int x, int y)
{
   int z = x - y;
   printf(" the answer is: %d\n", z);
Unit 1 Page 46
CS6202 PROGRAMMING AND DATA STRUCTURES

}
 // calling from main
int main( )
{
   void (*subPtr)(int, int) = subtract;
   (*subPtr)(10, 2);
}
Here the subtract function takes two parameters, both integers, subtracts one from
the other and prints the result. We create our subPtr function pointer with void (*subPtr)
(int, int). The only difference from before is now instead of empty parentheses on the end
when creating the function we have (int, int) which matches the signature of our new
function.
A Function Pointer with Parameters and Return Value
Let’s change our subtract function to be called subtract and to return the result
instead of printing
int subtract(int x, int y); // function prototype
 int subtract(int x, int y)
{
   return x - y;
}
 int main( )
{
  int (*subtractPtr)(int, int) = subtract;
    int y = (*subtractPtr)(10, 2);
   printf("Subtract gives: %d\n", y);
 }
Here the subtract function returns an int. The prototype and function signatures
have changed as would be expected. We create our subtractPtr function pointer with int
(*subtractPtr)(int, int). The only difference from before is instead of void we have an int
return value. This matches our subtract method signature.
Passing a Function Pointer as a Parameter
Let’s move on to a little more complex example where we pass a function pointer
into another function as a parameter.
int add(int x, int y); // function prototypes
int subtract(int x, int y);

Unit 1 Page 47
CS6202 PROGRAMMING AND DATA STRUCTURES

int domath(int (*mathop)(int, int), int x, int y);


 int add(int x, int y) // function definitions
{
  return x + y;
}
 int subtract(int x, int y)
{
   return x - y;
}
 int domath(int (*mathop)(int, int), int x, int y)
{
   return (*mathop)(x, y);
}
 int main( )
{
   int a = domath(add, 10, 2); // call math function with add
   printf("Add gives: %d\n", a);
     int b = domath(subtract, 10, 2); // call math function with subtract
  printf("Subtract gives: %d\n", b);
}
We have two functions with the same signature int function(int, int), add and
subtract. Both return an integer and both take two integers as parameters. In int
domath(int (*mathop)(int, int), int x, int y) the first parameter int (*mathop)(int, int) is a
pointer to a function that takes two integers as input and returns an integer. The last two
parameters x and y are just integer inputs into the domath function.

Unit 1 Page 48

You might also like