DS Module 1 Intro
DS Module 1 Intro
SEE Marks 50
INTRODUCTION TO DATA
STRUCTURES
Module 1
Mrs. Madhu Nagaraj
Assistant Professor
Dept of CSE-Data Science
ATMECE
CLO 1. To explain fundamentals of data structures and
Course Learning Objectives their applications.
• -Davids Johnson
“What is data? “
DICT definition - The quantities, characters, or symbols on which a computer
performs operations may be stored and transmitted in the form of electrical signals
and recorded on magnetic, optical, or mechanical recording media.
• DATA and INFORMATION are often confusing, and we often interchange these
two terms.
• UHDAM SI EMAN YM is just data because it is merely a collection of
characters, and from this, the user cannot understand anything properly
What is information?”
• If data is arranged systematically, then it gets a structure and becomes
meaningful.
• An array is a data
structure for storing
more than one data
item that has a
similar data type.
• Dynamic structures are ones which expand or shrink as required during the
program execution and there associated memory location change.
Data Structure Operations
Traversing: Traversing a Data Structure means to visit the element stored in it.
This can be done with any type of DS.
Searching: Searching means to find a particular element in the given data-
structure. It is considered as successful when the required element is found.
Insertion: It is the operation which we apply on all the data-structures. Insertion
means to add an element in the given data structure.
Deletion: It is the operation which we apply on all the data-structures. Deletion
means to delete an element in the given data structure.
Sorting: Sorting means arranging the data either in ascending or on decending.
Pointers
->Pointer is a variable which can hold the address of
another variable
1) Direct method
int num;
num=26;
printf("the content of the num is %d", num);
Printf("the address of the num is %x", &num); .
2. Indirect method (by using a pointer)
q ? ?
datatype * variable; float *q;
100 101 102
Ex: int *p; num 103
385.2367
num=385.2367;
float *q;
double *r; q 100
q=#
3.
4.
int n=5;
int n=5;
int *p;
float *p;
p=&n;
p=&n;
printf("%d", p);
printf("%d", *p);
#include <stdio.h> Accessing variables through pointer
void main()
{ 1000 2000 3000
int a,b,c; a ? b ? c ?
int *p, *q; 5000 6000
a=5; p ? q ?
b=10;
1000 2000 3000
a 5 b 10 c ?
p=&a;
q=&b;
c=*p+*q; p 1000 q 2000
printf("c is:%d",c); Output:
} c is: 15
Can there be more than one pointer to a
variable?
#include <stdio.h> 1000
void main() a
{
?
int a;
int *p,*q,*r; 5000 6000 7000
p ? q ? r ?
a=365;
p=&a;
1000
q=&a; a 365
r=&a;
• Wastage of memory
• malloc()
• Reediting is a time consuming
• calloc()
process
• realloc()
• free()
malloc()
• malloc stands for Memory allocation
• A memory space equivalent to 100 times the size of an int bytes is reserved
• The address of the first byte of the allocated memory is assigned to
the pointer p of type int
• On successful allocation, the function returns the address of first byte
of allocated memory.
• Since address is returned, the return type is a void pointer. By type
casting appropriately we can use it to store integer, float etc.
• cptr = (char *) malloc (20);
• Index − Each location of an element in an array has a numerical index, which is used to
identify the element.
• Array Representation - Arrays can be declared in various ways in different languages.
• Imagine that we have 100 scores. We need to read them, process them and print
them. We must also keep these 100 scores in memory for the duration of the
program. We can define a hundred variables, each with a different name.
But having 100 different names creates other problems. We need 100 references
to read them, 100 references to process them and 100 references to write them.
• An array is a sequenced collection of elements, normally of the same data type,
although some programming languages accept arrays in which elements are of
different types. We can refer to the elements in the array as the first element, the
second element and so forth, until we get to the last element.
Multi-dimensional arrays
• The arrays discussed so far are known as one-dimensional arrays because the
data is organized linearly in only one direction. Many applications require that
data be stored in more than one dimension. Figure shows a table, which is
commonly called a two-dimensional array
Memory Layout
• The indexes in a one-dimensional array directly define the relative positions of the
element in actual memory. Figure shows a two-dimensional array and how it is
stored in memory using row-major or column-major storage. Row- major storage
is more common.
Dynamically allocated Arrays
#include <stdio.h>
#include <stdlib.h>
void main()
{
int r = 3, c = 4, i; //Taking number of Rows and Columns
int *ptr; //creating pointer
ptr = (int *)malloc((r * c) * sizeof(int)); //Dynamically Allocating Memory (12*2=24)
for(i = 0; i < r * c; i++)
{
ptr[i] = i + 1; //Giving value to the pointer and simultaneously printing it.
printf("%d ", ptr[i]);
if ((i + 1) % c == 0)
{
printf("\n");
}
}
free(ptr);
}
35 23 45 20 100 70
m a t u w r
Array means, a series of entities or a sequence of entities of the same type (homogeneous).
In C language entities can be char, int, float and double type data
Declaration of 1-D array
Syntax:
datatype arrayname[size];
Ex: int a[5];
float b[5];
29 47 132 229 50
a[0] a[1] a[2] a[3] a[4]
int a[5];
int i;
printf(" Enter an integer"); a[0] a[1] a[2] a[3] a[4]
for(i=0; i<=4; i++)
{
scanf("%d", &a[i]); 29 47 132 229 50
}
a[0] a[1] a[2] a[3] a[4]
How do we store single integer in memory and how do we store array of
integers in memory?
To store single integer, To store array of integers,
a a 35 39 87 53 28
35
a[0 a[1 a[2 a[3 a[4
] ] ] ] ]
Note: Array is a Indexed Data Structure
Total size of the array=size of the array * number of bytes per block
=5*2
=10 bytes
#define N 20
#define M 10 4
int main()
Tendulkar
{
char word[N], *w[M]; Sourav Khan
int i, n; Khan
scanf("%d",&n); India
for (i=0; i<n; ++i) { scanf("%s", word);
w[i] = (char *) malloc ((strlen(word)+1)*sizeof(char)); w[0] = Tendulkar w[1]
= Sourav
strcpy (w[i], word) ; w[2] = Khan
}
for (i=0; i<n; i++) {
printf("w[%d] = %s \n",i,w[i]);
return 0;
}
w
0
T e n d u l k a r \0
1
S o u r a v \0
2
K h a n \0
3
I n d i a \0
1. A car manufacturing company uses an array car to record
number of cars sold each year starting from 1965 to 2015
i) Find the total number of years(elements)
ii) Suppose base address = 500, word length (w) = 4, find
address of car[1967], car[1969] and car[2015]
Two Dimensional Array
The programming language will store the array A either (1) column by column, is called
column-major order, or (2) row by row, in row-major order.
Structure provides a mechanism for the programmer to create his/her own data
type called "user defined date type"
31.71
t1.noofbranches=23; 12
t1.height=31.71; 13
14
.(dot) -> Member access 15
operator
printf("Enter Student Details\n");
//program to read and display printf("enter the name of the
student details using structures student\n");
#include <stdio.h> scanf("%s", s1.name);
struct student printf("enter student age\n");
{ scanf("%d", &s1.age);
printf("enter student marks\
char name[20];
n");
int age; scanf("%d", &s1.marks);
int marks; printf("enter student height\
float height; n");
}; scanf("%f", &s1.height);
void main() printf("Student details you
{ entered:\n");
struct student s1; printf("Student name is: %s\
n",s1.name);
//program to read and
display tree details using scanf("%s", t1.name);
structures printf("enter tree height\n");
#include <stdio.h> scanf("%f", &t1.height);
struct tree
{ printf("enter number of
char name[20]; noofbranches\n");
float height; scanf("%d", &t1.noofbranches);
int noofbranches; printf("the tree name is: %s\
}; n",t1.name);
void main() printf("the tree height is: %f\
{ n",t1.height);
struct tree t1; printf("noofbranches in the tree are:
printf("enter the name of %d\n",t1.noofbranches);
Array Structure
80 90 70
Array of Structures printf("enter the name of the tree\n");
#include <stdio.h> scanf("%s", t1[i].name);
struct tree printf("enter tree height\n");
{ scanf("%f", &t1[i].height);
char name[20]; printf("enter number of noofbranches\n");
float height; scanf("%d", &t1[i].noofbranches);
int noofbranches; }
};
void main() for(int i=0; i<=1; i++)
{ {
struct tree t1[2]; printf("the tree name is: %s\n",t1[i].name);
printf("the tree height is: %f\n",t1[i].height);
for(int i=0; i<=1; i++) printf("noofbranches in the tree are: %d\
{ n",t1[i].noofbranches);
}
}
#include<stdio.h>
Typedefing a Structures typedef struct
{
• The typedef is a keyword char name[10];
that is used to provide int usn;
existing data types with a }student;
new name. void main()
• The C typedef keyword is {
used to redefine the name of student s1;
already existing data types. printf("enter student name:\
n");
scanf("%s", s1.name);
printf("enter student usn:\n");
scanf("%d", &s1.usn);
printf("student name is
Different ways of writing a program using structure
#include<stdio.h> #include<stdio.h> #include<stdio.h>
struct student struct student typedef struct
{ { {
char name[10]; char name[10]; char name[10];
int usn; int usn; int usn;
}; }s1; }student;
void main() void main()
{ { void main()
struct student s1; printf("enter student name:\ {
printf("enter student name:\ n"); student s1;
n"); scanf("%s", s1.name); printf("enter student name:\
scanf("%s", s1.name); printf("enter student usn:\n"); n");
printf("enter student usn:\n"); scanf("%s", s1.name);
scanf("%d", &s1.usn); printf("enter student usn:\n");
scanf("%d", &s1.usn); printf("student name is %s\
printf("student name is %s\ n",s1.name); scanf("%d", &s1.usn);
n",s1.name); printf("student usn is %d", printf("student name is %s\
printf("student usn is %d", s1.usn); n",s1.name);
s1.usn); } printf("student usn is %d",
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("name:%s\nCity:%s\nPincode:%d\nPhone:
%s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
Self-Referential
Structures
A self-referential structure is one in which one or more of its components is a
pointer to itself. Self referential structures usually require dynamic storage
management routines (malloc and free) to explicitly obtain and release memory.
typedef struct
{
char data;
struct list *link
;
Each instance of the structure list will have two components data and link.
} list;
• Data: is a single character,
• Link: link is a pointer to a list structure. The value of link is either the address in
memory of an instance of list or the null pointer.
Self-Referential
Structures
Union
A union is similar to a structure, it is collection of data similar data type or
dissimilar.
Syntax:
union tag_name{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
}variable_name;
Union
typedef union union item
{ {
int i; int i;
double d; double d;
char c; char c;
}item; };
item x; x
d
void main() void main()
{ {
typedef struct typedef union
{ {
int marks; int marks;
char grade; char grade;
float percentage; float percentage;
}student; }student;
student s; student s;
s.marks=90; S.marks=90;
s.grade='A'; marks: 90 printf("marks:%d\n",s.marks);
s.percentage=90.0; grade: A
percentage: 90.0 s.grade='A';
printf("marks:%d\n",s.marks); printf("Grade:%c\n",s.grade);
printf("Grade:%c\n",s.grade);
printf("percentage:%f\ s.percentage=90.0;
n",s.percentage); printf("percentage:%f\n",s.percentage);
} }
Difference between Structure and Union
Polynomials
• A polynomial is a sum of terms, where each term has a form axe ,
where x is the variable, a is the coefficient and e is the exponent
A(x) = 2xl000+ 1
B(x) = x4 + 10x3 + 3x2 +1
The above figure shows how these polynomials are stored in the array terms. The
index of the first term of A and B is given by startA and startB, while finishA and
finishB give the index of the last term of A and B.
• The index of the next free location in the array is given by avail.
• For above example, startA=0, finishA=1, startB=2, finishB=5, & avail=6.
int i;
Program to read and display Polynomial for(i=0; i<n; i++)
#include<stdio.h> {
typedef struct if(p[i].cf < 0)
{ printf("%d",p[i].cf);
int cf; //used to hold coefficient
int px; //used to hold power of x if(p[i].px != 0)
}poly; printf("x^%d",p[i].px); }
//function to read a polynomial with n terms printf("\n");}
void read_poly(poly p[], int n) void main()
{ {
int i,cf,px; int n;
for(i=0; i<n; i++) poly p[10];
{ printf("enter number of terms:\n");
printf("enter Coefficient and scanf("%d", &n);
exponent:"); read_poly(p, n);
scanf("%d%d", &p[i].cf, &p[i].px);); print_poly(p,n);
} }
}
//function to display a polynomial with n
terms
void print_poly(poly p[], int n)
SPARSE MATRICES
What is Sparse Matrix?
A matrix which contains many zero entries or very few non-zero entries is called as Sparse
matrix.
In the figure B contains only 8 of 36 elements are nonzero and that is sparse.
Row 0
Row 1
Row 2
Row 4
Row 5
• The various information can be accessed using as shown below:
• The size of the matrix using : a[0].row, a[0].col
• The number of non-zero elements using : a[0].val
• The row index of a non-zero element : a[j].row
• The column index of a non-zero element : a[j].col for j = 1 to a[0].col
• The index of non-zero element : a[j].val
//Function to read the sparse matrix as a triple
void read_sparse_matrix(TERM a[], int m, int n)
{
int i,j,k,item;
a[0].row=m, a[0].col=n, k=1;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++) Row Col Val
{
scanf("%d",&item); 6X6 is the size and 8 non zero
if(item==0) values in given matrix
Row 0
continue;
a[k].row=i, a[k].col=j, a[k].val=item;
k++; Row 1
} Row 2
} Row 4
a[0].val=k-1; Row 5
}
Row Col Val
Transpose of a matrix
Row Col
Val
6X6 is the size and 8 non zero values in
given matrix
Col 0
Col 1
Col 2
Col 3
Col 5
Row Col Val
//Function to find the transpose of a given sparse matrix matrix
0 1 2 3 4 5 6 7
Initialization:
char a[8] = {'H','e','l','l','o','\0'}; a H e l l o \0
Or 0 1 2 3 4 5 6 7
a H e l l o H i \0
char a[]="HelloHi";
BASIC TERMINOLOGY:
String: A finite sequence S of zero or more Characters is called string.
Length: The number of characters in a string is called length of string.
Empty or Null String: The string with zero characters.
Concatenation: Let S1 and S2 be the strings. The string consisting of the characters of S1
followed by the character S2 is called Concatenation of S1 and S2.
Ex: ‘THE’ // ‘END’ = ‘THEEND’
‘THE’ // ‘ ’ // ‘END’ = ‘THE END’
Substring: A string Y is called substring of a string S if there exist string X and Z such that
S = X // Y // Z
If X is an empty string, then Y is called an Initial substring of S, and Z is an empty string then
Y is called a terminal substring of S.
Ex: ‘BE OR NOT’ is a substring of ‘TO BE OR NOT TO BE’
‘THE’ is an initial substring of ‘THE END’
1. Fixed length storage structures
In this storage structure, each line of text to be manipulated is viewed as a record where
all records have same length.
R A M A
0
K R I S H N A
1
M I T H I L
2
3 A B
5 A B C D E F G H
Disadvantages:
2. Variable length
structures R A M A \0
• variable-length strings don’t have a pre-
defined length. In this string, neither 5 bytes
the precise length nor
• maximum length is known at creation K R I S H N A \0
time.
• The storage structure for a string can
expand or shrink to accommodate any
String delimiter
size of data.
• ->In C language strings end with a 8 bytes
special character called NULL (denoted char
by \0) a[ ]="RAMA";
char a[ ]="KRISHNA";
3. Linked storage structures
• In most of the word processing applications, the strings are represented using linked lists.
• Using linked lists inserting/deleting a character/word is much easier.
• The string “MITHIL” can be represented using linked list as shown below:
String Operations
Substring
Indexing
Concatenation
Length
Substring
Substring is a string obtained by extracting a part of a given string, given the position and length
of the substring.
Ex: SUBSTRING ('TO BE OR NOT TO BE’, 4, 7) = 'BE OR N’
SUBSTRING ('THE END', 4, 4) = ' END'
Indexing
The process of finding the position of pattern string in a given text t is called indexing.
It is also called pattern matching.
If the paatern string is present in text t, the position of the first occurrence of the pattern string is
returned otherwise, 0 is returned.
Let, text t = “RAMA IS THE KING OF AYODHYA”, the pattern string pattern is “KING”.
Then, INDEX(t, pattern) = 13
Concatenation
• The process of appending the second string to the end of first string is called concatenation.
• We can denote the concatenation symbol by “+”.
For example, let first string is s1=”SEETA” and the second string s2 =” RAMA”.
Then, s1+ s2 = “SEETA RAMA”
Length
The number of characters in a string is called length of the string. For example,
Length(“RAMA”) = 4
Printing and Reading Strings
#include<stdio.h>
Void main()
Ex. for reading string using
{
formatted input function:
char name[20]; O/p:
char c[20];
Printf("enter your name:"); enter your name: Sachin Tendulkar
scanf("%s", c);
Scanf("%s", name); your name is: Sachin
Printf("your name is %s:", name);
}
STRING HANDLING FUNCTIONS IN C
strcpy(dest, src) Copies the source string src to destination string dest
#include<stdio.h>
void main()
{
char str[6]="Hello";
#include<stdio.h>
int len = my_strlen(str);
#include<string.h>
printf("length of str is %d",len);
void main()
}
{
int my_strlen(char str[])
char str[6]="Hello";
{
int len = strlen(str);
int i=0;
printf("length of str is %d",len);
while(str[i] != '\0')
}
{
i++;
}
return i;
}
String copy
#include<stdio.h>
void main()
{
char str1[6]="HELLO";
char str2[6];
My_strcpy(str1, str2);
}
void my_strcpy(char str1[], char str2[])
{ #include<stdio.h>
int i=0; #include<string.h>
while(str1[i] != '\0') void main()
{ {
str2[i]=str1[i]; char str1[6]="HELLO";
i++; char str2[6];
} strcpy(str1,str2);
str2[i]='\0'; printf("string 2 is %s",str2);
} }
#include<stdio.h> String concatenation
void main()
{
char str1[6]="HELLO";
char str2[6]="WORLD";
My_strcat(str1, str2);
}
void my_strcat(char str1[], char str2[])
{
int i,j;
i=0,j=0;
while(str1[i] != '\0') #include<stdio.h>
{ #include<string.h>
i++; void main()
} {
while(str2[j]!='\0') char str1[6]="HELLO";
{ char str2[6]="WORLD";
str1[i++]=str2[j++]; strcat(str1,str2);
} printf("str1 is %s",str1);
str1[i++] = '\0'; }
}
String compare
#include<stdio.h>
void main()
{
char str1[6]="Hello";
char str2[6]="Hello";
int res = my_strcmp(str1, str2);
if(res==0) { printf("strings are equal\n"); }
else if(res < 0) { printf("string 1 is smaller than string 2");
else { printf("string 1 is greater than string 2"); }
}
Int my_strcmp(char str1[], char str2[])
{
int i;
i=0;
while(str1[i] == str2[i])
{
if(str1[i] == '\0')
break;
i++;
}
return str1[i] - str2[i];
}
String Reverse
#include<stdio.h>
#include<string.h>
void main()
{
char str1[6]="Hello";
char str2[6];
my_strrev(str1, str2);
}
void my_strrev(char str1[], char str2[])
{
int i,n;
n = strlen(str1)
for(i=0; i<n; i++)
{
str2[n-1-i] = str1[i];
}
str2[n] = '\0';
}
PATTERN MATCHING ALGORITHM
The first pattern matching algorithm is one in which comparison is done by a given pattern P with each of
the substrings of T, moving from left to right, until a match is found.
WK = SUBSTRING (T, K, LENGTH (P))
• Where, WK denote the substring of T having the same length as P and beginning with the Kth character
of T.
•First compare P, character by character, with the first substring, W1. If all the characters are
the same, then P = W1 and so P appears in T and INDEX (T, P) = 1.
• Suppose it is found that some character of P is not the same as the corresponding character
of W1. Then P ≠ W1
• Immediately move on to the next substring, W2 That is, compare P with W2. If P ≠ W2
then compare P with W3 and so on.
• The process stops, When P is matched with some substring WK and so P appears in T and
INDEX(T,P) = K or When all the WK'S with no match and hence P does not appear in T.
• The maximum value MAX of the subscript K is equal to LENGTH(T) -LENGTH(P) +1.
Algorithm: (Pattern Matching_Brute Force)
P and T are strings with lengths R and S, and are stored as arrays with one
character per
element. This algorithm finds the INDEX of P in T.
1. [Initialize.] Set K: = 1 and MAX: = S - R + 1
2. Repeat Steps 3 to 5 while K ≤ MAX
3. Repeat for L = 1 to R: [Tests each character of P]
If P[L] ≠ T[K + L – l], then: Go to Step 5
[End of inner loop.]
4. [Success.] Set INDEX = K, and Exit
5. Set K := K + 1
[End of Step 2 outer loop]
6. [Failure.] Set INDEX = O
7. Exit
PATTERN MATCHING ALGORITHM - KMP algorithm(Knuth Morris Pratt)
1 2 3 4 5 6 7 8 9 10 11
Algm PatternMatching_KMP(s, p) return int
String s: a a a a a a a a a a b
{
Pattern p: a a a b
k=1, s1=q0, n=length(s)
While(k<=n && sk!=p)
{
Read tK
sk+1 = F(sk,tk) Pattern p: a a b a
k=k+1
}
If(k>n)
{
index=0
}
else
{
Index=k-length(p)
}
return index
}
Stacks
3 3 3 3 3
#define Max_Size 4
void push()
2 2 2 2 2 {
if (top >= Max_Size-1)
Stack overflow
1 1 1 1 1 Else
top++
stack[top] = item;
0 0 0 0 0 }
Function to push an integer item Function to push an integer item
(using global variables) (by passing parameter)
void push()
void push(int item, int top, int s[])
{
{
If(top == Max_Size - 1)
If(top == Max_Size - 1)
{
{
printf("Stack Overflow");
Printf("Stack Overflow");
exit(0);
Return;
}
}
top++;
top++;
s[top] = item;
s[top] = item;
}
}
pop()
Deleting an element from the stack is called pop operation. The element is
deleted only from the top of the stack and only one element is deleted at a
time.
If(top==-1) If(top==-1)
Return 0; Return 0;
item_deleted=s[top--]; item_deleted=s[(top)--];
Return item_deleted; Return item_deleted;
} }
Display()
->Display the elements of stack
->Check for underflow condition
->Display using for loop
Display Stack content using global variables Display Stack content by pass by parameter
Infix Expression: In this expression, the binary operator is placed in-between the operand.
The expression can be parenthesized or un- parenthesized.
Example: A + B
Here, A & B are operands and + is operator
Prefix or Polish Expression: In this expression, the operator appears before its operand.
Example: + A B
Here, A & B are operands and + is operator
Postfix or Reverse Polish Expression: In this expression, the operator appears after its
operand.
Example: A B + Here, A & B are operands and + is operator
Steps to evaluate postfix expression
Step 1: If operand - push
Step2: If operator -
* Pop the top of the stack and make it operand 2
* Pop the next top of the stack and make operand 1
* Perform operation
* Push the result
Recursion
Direct Indirect
Recursion Recursion
Direct Recursion Indirect Recursion
func1(); func2();
func1();
} }
}
Direct Recursion Indirect Recursion
Example: Example:
#include<stdio.h> #include<stdio.h>
void main() void fun(void);
{ void main()
printf("I LOVE MY COUNTRY\n"); {
main(); printf("I LOVE MY COUNTRY\n");
} fun();
}
fun()
Output: {
I LOVE MY COUNTRY main();
I LOVE MY COUNTRY }
... Output:
... I LOVE MY COUNTRY
... I LOVE MY COUNTRY
(infinte number of times I LOVE MY ...
COUNTRY will printed ) (infinte number of times I LOVE MY COUNTRY
will printed )
General format of recursive function:
rec-fun()
No is exit
body condition
satisfied?
Yes
Stop
factorial of a given number
#inlcude<stdio.h>
void main()
{
fact=1;
Printf("enter the no\n");
Scanf("%d",&n);
For(i=1;i<=n;i++)
{
fact=fact*i;
}
printf("factorial of a number is %d", fact);
}
Example
int sum(int k);
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}}
#include<stdio.h>
Write a program to compute the factorial of a given
int fact(int);
number n using recursion.
void main()
0! = 1 {
1! = 1*(1-1)! = 1*1 =1 int n,ans;
2! = 2*(2-1)! = 2*1 = 2 printf("enter the value of n\n");
3! = 3*(3-1)! = 3*2 = 6 scanf("%d",&n);
4! = 4*(4-1)! = 4*6 = 24
ans=fact(n);
.
printf("answer is %d",ans);
.
. }
n! = n*(n-1)! int fact(int n)
{
if(n==0)
{
return 1;
{
1 if
fact(n) = n==0 }
else
n*fact(n-1) if n>0 { return n*fact(n-1);} }
Fibonacci Sequence
A series of numbers in which each number ( Fibonacci number ) is the sum of the
two preceding numbers.
n 1 2 3 4 5 6 7 8 9 10
fib(n) 0 1 1 2 3 5 8 13 21 34
{
0 if n==1
fib(n) = 1 if n==2
fib(n-1)+fib(n-2) if n>2
#include<stdio.h>
int fib(int); int fib(int n)
void main() {
{ if(n==1)
int n,ans; {
printf("enter the value of n\n"); return 0;
scanf("%d",&n); }
ans=fib(n); if(n==2)
printf("answer is %d",ans); {
} return 1;
}
if(n>2)
{
return fib(n-1)+fib(n-
2);
}
}
Tower of Hanoi
Suppose three pegs, labeled A, Band C, are given, and suppose on peg A a finite number n of
disks with decreasing size are placed.
The objective of the game is to move the disks from peg A to peg C using peg B as an auxiliary.
The rules of the game are as follows:
1. Only one disk may be moved at a time. Only the top disk on any peg may be moved to any
other peg.
2. At no time can a larger disk be placed on a smaller disk
1. Move top disk from peg A to peg C.
2. Move top disk from peg A to peg B.
3. Move top disk from peg C to peg B.
4. Move top disk from peg A to peg C.
5. Move top disk from peg B to peg A.
6. Move top disk from peg B to peg C.
7. Move top disk from peg A to peg C.
In other words,
n=3: A→C, A→B, C→B, A→C, B→A, B→C,
A→C
the solution to the Towers of Hanoi problem for n = 1 and n = 2
n=l: A→C
n=2: A→B, A→C, B→C
The Towers of Hanoi problem for n > 1 disks may be reduced to the following sub-
problems:
(1) Move the top n - 1 disks from peg A to peg B
(2) Move the top disk from peg A to peg C:A→C.
(3) Move the top
The general n - 1 disks from peg B to peg C
notation
• TOWER (N, BEG, AUX, END) to denote a procedure which moves the top n disks from
the initial peg BEG to the final peg END using the peg AUX as an auxiliary.
• When n = 1, the solution:
TOWER (1, BEG, AUX, END) consists of the single instruction BEG→END
• When n > 1, the solution may be reduced to the solution of the following three sub problems:
(a) TOWER (N - I, BEG, END, AUX)
(b) TOWER (l, BEG, AUX, END) or BEG → END
(c) TOWER (N - I, AUX, BEG, END)
Procedure: TOWER (N, BEG, AUX, END)
This procedure gives a recursive solution to the Towers of Hanoi problem
for N disks.
1. If N=l,then:
(a) Write: BEG →END.
(b) Return.
[End of If structure.]
2. [Move N - 1 disks from peg BEG to peg AUX.]
Call TOWER (N - 1, BEG, END, AUX).
3. Write: BEG →END.
4. [Move N - 1 disks from peg AUX to peg END.]
Call TOWER (N - 1, AUX, BEG, END).
5. Return.
#include<stdio.h>
void tower(int n,char frompeg,char topeg,char
void tower(int n,char frompeg,char
auxpeg)
topeg,char auxpeg);
{
int n;
if(n==1)
void main()
{
{
printf("move disk1 from %C to %C\n",
printf("Enter the no. of discs: \n");
frompeg,topeg);
scanf("%d",&n);
return;
printf("the number of moves in tower
}
of henoi problem\n");
tower(n-1,frompeg,auxpeg,topeg);
tower(n,'A','C','B');
printf("move disk%d from %C to%C\n",n,
}
frompeg,topeg);
tower(n-1,auxpeg,topeg,frompeg);
}