Unit 3
Unit 3
PROGRAMMING FOR
PROBLEM SOLVING
UNIT 3
Course Learning Outcome (CLO – 3)
• The inside braces, which indicates the wanted row, are optional.
• The following initialization is the same to the previous example −
int a[3][4]={{0,1,2,3,4,5,6,7,8,9,10,11}};
Accessing 2D Array Elements
• To access elements of a two-dimensional array we use array name with
row index value and column index value of the element that to be
accessed.
• The row and column index values must be in separate square braces. In
the case of the two-dimensional array, the compiler assigns separate index
values for rows and columns.
• An element in a two-dimensional array is accessed by using the subscripts,
i.e., row index and column index of the array. For example −
int val = a[2][3];
• The above statement will take the 4th element from the 3rd row of the
array.
Processing of 2D Array
• A two-dimensional can be considered as a matrix. Two loops are used to
process a two-dimensional array as shown below:
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{ .
.
}
}
where rows → number of rows in the matrix
cols → number of columns in the matrix
2D Array Memory representation
2D Array Memory representation (Cont..)
2D Array - Example
#include<stdio.h> for(i=0;i<rows;i++)
int main() {
{ for(j=0;j<cols;j++)
int rows,cols,i,j; {
int a[10][10]; printf("%d\t",a[i][j]);
printf("How many rows : "); }
scanf("%d",&rows); printf("\n");
printf("How many columns : "); } Output:
scanf("%d",&cols); return 0;
printf("Enter the elements of the matrix\n"); } How many rows : 2
for(i=0;i<rows;i++) How many columns : 2
{
Enter the elements of the
for(j=0;j<cols;j++)
{ matrix
scanf("%d",&a[i][j]); 5 10 8 4
} The matrix you've entered is
} 5 10
printf("The matrix you've entered is\n"); 8 4
2D Array – Example
// To add & subtract two matrices scanf(“%d”,&b[i][j]); for(j=0;j<cols;j++)
#include<stdio.h> } {
int main() { } printf("%d\t",d[i][j]);
int rows,cols,i,j; }
for(i=0;i<rows;i++)
int a[10][10],b[10][10],c[10][10],d[10][10]; printf("\n");
{
printf("MATRIX ADDITION\n\n"); } return 0;
for(j=0;j<cols;j++)
printf("How many rows : "); }
{
scanf("%d",&rows);
c[i][j]=a[i][j]+b[i][j];
printf("How many columns : ");
scanf("%d",&cols);
d[i][j]=a[i][j]-b[i][j]; Output:
}
printf("Enter the elements of the first matrix\n");
} MATRIX ADDITION
for(i=0;i<rows;i++)
printf("Result of Addition\n"); How many rows : 2
{ How many columns : 2
for(i=0;i<rows;i++)
for(j=0;j<cols;j++) Enter the elements of the first matrix
{ 2 5 8 9
{
for(j=0;j<cols;j++) Enter the elements of the second matrix
scanf("%d",&a[i][j]);
{ 1 2 3 4
}
printf("%d\t",c[i][j]);
} Result of Addition
} 3 7
printf(“Enter the elements of the second matrix \n”);
printf("\n"); 11 13
for(i=0;i<rows;i++)
}
{ Result of Subtraction
printf("Result of Subtraction\n"); 3 3
for(j=0;j<cols;j++)
for(i=0;i<rows;i++) 5 5
{
{
2D Array – Example
// To find the transpose of a matrix printf("The transpose of the matrix is\n");
#include<stdio.h> for(j=0;j<cols;j++)
int main() {
{ for(i=0;i<rows;i++)
int rows,cols,i,j; {
int a[10][10]; printf("%d\t",a[i][j]);
printf("How many rows : "); }
scanf("%d",&rows); printf("\n");
printf("How many columns : "); }
scanf("%d",&cols); return 0;
printf("Enter the elements of the matrix\n"); }
Output:
for(i=0;i<rows;i++)
{ How many rows : 3
for(j=0;j<cols;j++) How many columns : 3
Enter the elements of the matrix
{ 5 6 8 7 9 5 6 4 8
scanf("%d",&a[i][j]);
The transpose of the matrix is
} 5 7 6
6 9 4
} 8 5 8
2D Array – Example
// To find the sum of all the {
elements of a matrix scanf("%d",&a[i][j]);
sum=sum+a[i][j];
}
#include<stdio.h>
}
int main()
printf("Sum of all the elements = %d\n",sum);
{
return 0;
int rows,cols,i,j,sum=0;
}
int a[10][10];
printf("How many rows : ");
scanf("%d",&rows); Output:
printf("How many columns : ");
How many rows : 3
scanf("%d",&cols); How many columns : 3
printf("Enter the elements of the matrix\n"); Enter the elements of the matrix
5 6 8 7 9 5 6 4 8
for(i=0;i<rows;i++)
{ Sum of all the elements = 58
for(j=0;j<cols;j++)
2D Array – Example
// To find the sum of diagonal elements of a
square matrix sum=sum+a[i][j];
}
#include<stdio.h> }
int main() }
{ printf("Sum of diagonal elements = %d\n",sum);
int rc,i,j,sum=0; return 0;
int a[10][10]; }
printf("How many rows & columns in a square matrix : ");
scanf("%d",&rc);
printf("Enter the elements of the matrix\n"); Output:
for(i=0;i<rc;i++)
{ How many rows & columns in a
for(j=0;j<rc;j++)
square matrix : 3
Enter the elements of the matrix
{
5 6 8 7 9 5 6 4 8
scanf("%d",&a[i][j]);
if(i==j) Sum of diagonal elements = 22
{
MULTI DIMENSIONAL
ARRAY
Multi Dimensional Array
Data_Type Array_Name[Tables][Row_size][Column-size];
• Data_type: It will decide the type of elements it will accept. For example,
If we want to store integer values then we declare the Data Type as int, If
we want to store Float values then we declare the Data Type as float etc
• Array_Name: This is the name you want to give it to Multi Dimensional
array in C.
3D Array – Declaration (Cont..)
• Tables: It will decide the number of tables an array can accept. Two
Dimensional Array is always a single table with rows and columns. In
contrast, Multi Dimensional array in C is more than 1 table with rows and
columns.
• Row_Size: Number of Row elements an array can store. For example,
Row_Size =10, the array will have 10 rows.
• Column_Size: Number of Column elements an array can store. For
example, Column_Size = 8, the array will have 8 Columns.
3D Array – Declaration (Cont..)
For Example:
int Employees[2][4][3];
• Here, we used int as the data type to declare an array. So, the above array
will accept only integers. If you try to add float values, it throws an error.
• Employees is the array name
• The number of tables = 2. So, this array will hold a maximum of 2 levels of
data (rows and columns).
• The Row size of an Array is 4. It means Employees array only accept 4
integer values as rows.
• If we try to store more than 4, it throws an error.
• We can store less than 4. For Example, If we store 2 integer values, the
remaining two will assign with the default value (Which is 0).
3D Array – Declaration (Cont..)
For Example:
int Employees[2][4][3];
• The Column size of an Array is 3. It means Employees array will only
accept 3 integer values as columns.
• If we try to store more than 3, it throws an error.
• We can store less than 3. For Example, If we store 1 integer values, the
remaining 2 values will assign with the default value (Which is 0).
• Finally, Employees array can hold a maximum of 24 integer values (2 * 4 *
3 = 24).
3D Array - Initialization
• We can initialize the C Multi Dimensional Array in multiple ways.
• First Approach of Multi Dimensional Array in C
• Here, We have 2 tables and the 1st table holds 4 Rows * 3 Columns, and the
2nd table also holds 4 Rows * 3 Columns
• The first three elements of the first table will be 1st row, the second three
elements will be 2nd row, the next three elements will be 3rdrow, and the
last 3 elements will be 4th row.
• Here we divided them into 3 because our column size = 3, and we
surrounded each row with curly braces ({}). It is always good practice to
use the curly braces to separate the rows.
3D Array – Initialization (Cont..)
• Second Approach of Multi Dimensional Array in C.
• Here, We did not mention the row size. But, the compiler is intelligent
enough to calculate the size by checking the number of elements inside the
row. We can also write
3D Array – Initialization (Cont..)
• Third Approach for Multi Dimensional Array in C
• Here, we declared Employees array with row size = 4 and column size = 3.
But we only assigned 1 column in the 1st row and 2 columns in the 2nd
row of the first table. In these situations, the remaining values will assign
to default values (0 in this case).
• The above Multi Dimensional array in C will be:
3D Array – Initialization (Cont..)
• Third Approach for Multi Dimensional Array in C
• Here, we declared Employees array with row size = 4 and column size = 3.
But we only assigned 1 column in the 1st row and 2 columns in the 2nd
row of the first table. In these situations, the remaining values will assign
to default values (0 in this case).
• The above Multi Dimensional array in C will be:
Accessing 3D Array
• We can access the C Multi Dimensional array elements using indexes.
• Index starts at 0 and ends at n-1, where n is the size of a row or column.
• For example, if an Array_name[4][8][5] will store 8-row elements and 5
column elements in each table where table size = 4.
• To access 1st value of the 1st table, use Array_name[0][0][0], to access 2nd
row 3rd column value of the 3rd table then use Array_name[2][1][2] and to
access the 8th row 5th column of the last table (4th table), use
Array_name[3][7][4].
Accessing 3D Array (Cont..)
3D Array – Example
// To read a 3D array as input and to print it for(i=0;i<tab;i++)
#include<stdio.h> { printf("\n\nTABLE %d\n\n",(i+1));
int main() { for(j=0;j<rows[i];j++)
int a[10][10][10],rows[10],cols[10],tab,i,j,k; { for(k=0;k<cols[i];k++)
printf("How many tables : "); { printf("%d\t",a[i][j][k]);
scanf("%d",&tab); } printf("\n");
for(i=0;i<tab;i++) } }
return 0;
Output:
{ How many tables : 2
printf("How many rows in table %d : ",(i+1)); } How many rows in table 1 :2
How many columns in table 1 :2
scanf("%d",&rows[i]); Enter 4 elements in Table 1 : 2 4 6 8
printf("How many columns in table %d : ",(i+1)); How many rows in table 2 :2
How many columns in table 2 :2
scanf("%d",&cols[i]); Enter 4 elements in Table 2 : 1 3 5 7
printf("Enter %d elements in Table %d : The table you’ve entered
",(rows[i]*cols[i]),(i+1));
Table 1
for(j=0;j<rows[i];j++)
2 4
{ for(k=0;k<cols[i];k++) 6 8
{ scanf("%d",&a[i][j][k]);
Table 1
} } } 1 3
5 7
printf("The tables you've entered\n");
3D Array – Example
// To get the total number of colleges in a university, name of all scanf("%s",studname[i][j][k]);
the colleges, courses offered, list of students registered and print
all the details } } }
scanf("%d",&n_cols); for(k=0;k<n_stud[i][j];k++)
for(i=0;i<n_cols;i++) } printf("\n");
scanf("%s",colname[i]);
printf("No of courses offered in %s : ",colname[i]);
scanf("%d",&n_course[i]);
printf("Give the details of all courses\n");
for(j=0;j<n_course[i];j++)
{ printf("Course Name : ");
scanf("%s",course[i][j]);
printf("No of students registered for %s",course[i][j]);
scanf("%d",&n_stud[i][j]);
printf("Give the names of all the students\n");
for(k=0;k<n_stud[i][j];k++)
{ printf("Name : ");
ARRAY CONTIGUOUS
MEMORY
Array Contiguous Memory
• It is better and convenient way of storing the data of same datatype with
same size.
• It allows us to store known number of elements in it.
• It allocates memory in contiguous memory locations for its elements.
• It does not allocate any extra space/ memory for its elements. Hence there
is no memory overflow or shortage of memory in arrays.
• Iterating the arrays using their index is faster compared to any other
methods like linked list etc.
• It allows to store the elements in any dimensional array - supports
multidimensional array.
Limitations of Array
A) Static Data
• Array is Static data Structure
• Memory Allocated during Compile time.
• Once Memory is allocated at Compile Time it Cannot be changed during
Run-time.
• Array Variable is Case Sensitive so A[2] does not print anything it Displays
Error Message : “Undefined Symbol A“
Applications of Array
• Arrays are used to Store List of values: In C Programming language,
single-dimensional arrays are used to store a list of values of the same
datatype.
• Arrays are used to Perform Matrix Operations: We use two-dimensional
arrays to create matrix. We can perform various operations on matrices
using two-dimensional arrays.
• Arrays are used to implement Search Algorithms: We use single-
dimensional arrays to implement search algorithms like Linear Search,
Binary Search
• Arrays are used to implement Sorting Algorithms: We use single-
dimensional arrays to implement sorting algorithms like Insertion Sort,
Bubble Sort, Selection Sort, Quick Sort, Merge Sort, etc.,
• Arrays are used to implement Data structures: We use single-dimensional
arrays to implement data structures like Stack Using Arrays and Queue
Using Arrays
18CSS101J
PROGRAMMING FOR
PROBLEM SOLVING
UNIT 3
Course Learning Outcome (CLO – 3)
• String basics
• String Declaration and initialization
• String Functions: gets(), puts(), getchar(), putchar(), printf()
• String Functions: atoi, strlen, strcat, strcmp
• String Functions: sprint, sscanf, strrev, strcpy, strstr, strtok
• Arithmetic Characters on Strings
STRING BASICS
String Basics
• The string can be defined as the one-dimensional array of characters
terminated by a null ('\0’).
• The character array or the string is used to manipulate text such as word
or sentences.
• Each character in the array occupies one byte of memory, and the last
character must always be 0.
• The termination character ('\0') is important in a string since it is the only
way to identify where the string ends.
• When we define a string as char s[10], the character s[10] is implicitly
initialized with the null in the memory.
• Any group of characters (except double quote sign) defined between
double quotation marks is a string constant.
String Basics (Cont..)
• Example:
“Man is obviously made to think.”
• If we want to include a double quote in the string to be printed, then we
may use it with a back slash as shown below.
“\” Man is obviously made to think,\” said Pascal.”
• For example,
printf (“\” Well Done !”\”); will output the string
“ Well Done !”
• while the statement
printf(“ Well Done !”); will output the string
Well Done!
String Basics (Cont..)
• Strings in C are represented by arrays of characters.
o If string contains the double quote as part of string then we can use
escape character to keep double quote as a part of string.
char string_name[size];
char city[10];
char name[30];
String Declaration and Initialization (Cont..)
Point Explanation
Significance We have declared array of character[i.e String]
Size of string 30 Bytes
Bound checking C Does not Support Bound Checking i.e if we store City with
size greater than 30 then C will not give you any error
Data type char
Maximum size 30
String Declaration and Initialization (Cont..)
Precautions to be taken while declaring Character Variable :
• String / Character Array Variable name should be legal C Identifier.
• String Variable must have Size specified.
char city[];
• Above Statement will cause compile time error.
• Do not use String as data type because String data type is included in later
languages such as C++ / Java. C does not support String data type
String city;
• When you are using string for other purpose than accepting and printing
data then you must include following header file in your code –
#include<string.h>
String Declaration and Initialization (Cont..)
• When the compiler assigns a character string to a character array, it
automatically supplies a null character (‘\0 ‘) at the end of the string.
• The size should be equal to the maximum number of characters in the
string plus one.
• character arrays may be initialized when they are declared.
• C permits a character array to be initialized in either of the following two
forms:
char city[9] = “NEW YORK”;
char city[9]= {‘N’,’E’,’W’,’ ‘,’Y’,’O’,’R’,’K’,’\0’};
• city had to be 9 elements long is that the string NEW YORK contains 8
characters and one element space is provided for the null terminator.
String Declaration and Initialization (Cont..)
• To initialize a character array without specifying the number of elements.
• The size of the array will be determined automatically, based on the
number of elements initialized.
• For example, the statement
• You can specify the format in which data must be displayed on the screen.
It returns the number of characters actually displayed.
• The function is included in <stdio.h> file.
Syntax : printf(“format specifier”, arg1, arg2,….., argn);
String Functions – printf() - Example
#include <stdio.h> //Write a C Program to Get Numeric
int main() Input from User
{ #include<stdio.h>
char item[]="ABC"; int main()
{
int partno=12345; int i;
float cost=0.50; printf("Enter a value: ");
printf("%s%d%f",item,partno,cost); scanf("%d",&i);
return 0; printf( "\nYou entered: %d",i);
} return 0;
}
Output: Output:
ABC12345.500000 Enter a value: 54
You entered: 54
STRING FUNCTIONS
atoi, strlen, strcat, strcmp,
strcpy
String Functions – atoi
• The atoi() function in C takes a string (which represents an integer) as an
argument and returns its value of type int.
• The function is used to convert a string argument to an integer.
Syntax: int atoi(const char strn);
• Parameters: The function accepts one parameter strn which refers to the
string argument that is needed to be converted into its integer equivalent.
• Return Value: If strn is a valid input, then the function returns the
equivalent integer number for the passed string number. If no valid
conversion takes place, then the function returns zero.
String Functions – atoi (Cont..)
Significance :
• Can Convert any String of Number into Integer Value that can Perform the
arithmetic Operations like integer
• Header File : stdlib.h
Ways of Using Atoi Function :
• Way 1 : Passing Variable in Atoi Function
int num;
char marks[3] = "98";
num = atoi(marks);
printf("\nMarks : %d",num);
• Way 2 : Passing Direct String in Atoi Function
int num;
num = atoi("98");
printf("\nMarks : %d",num);
String Functions – atoi (Cont..)
OTHER INBUILT TYPECAST FUNCTIONS IN C PROGRAMMING
LANGUAGE:
• Typecasting functions in C language performs data type conversion from
one type to another.
• atof() Converts string to float
• atoi() Converts string to int
• atol() Converts string to long
• itoa() Converts int to string
• ltoa() Converts long to string
String Functions – atoi - Example
#include <stdio.h> printf("Integer value = %d\n", val);
#include <stdlib.h> return (0);
#include <string.h> }
int main()
{ Output:
int val;
Integer value = 12546
char strn1[] = "12546";
val = atoi(strn1); String value = C Programming
printf("String value = %s\n", strn1); Integer value = 0
printf("Integer value = %d\n", val);
char strn2[] = "C Programming";
val = atoi(strn2);
printf("String value = %s\n", strn2);
String Handling Functions
• The C library supports a large number of string-handling functions that
can be used to carry out many of the string manipulations discussed so far.
• Following are the most commonly used string handling functions:
String Functions – strcat()
• The strcat function joins two strings together. It takes the following form:
Syntax: strcat(string1,string2);
• string1 and string2 are character arrays. When the function strcat is
executed, string2 is appended to string1.
• It does so by removing the null character at the end of string1 and placing
string2 from there.
• The string at string2 remains unchanged. For example, consider the
following three strings:
String Functions – strcat() (Cont..)
• Execution of the statement • We must make sure that the size of
strcat(part1,part2); string1 is large enough to
will result in: accommodate the final string.
• strcat function may also append a
string constant to a string variable.
The following is valid:
strcat(part1,”GOOD”);
While the statement will result in: • C permits nesting of strcat
functions. For example, the
statement
strcat(strcat(string1,string2), string3);
• is allowed and concatenates all the
three strings together. The
resultant string is stored in string1.
String Functions – strcat() (Cont..)
Ways of Using Strcat Function :
• Way 1 : Taking String Variable as Parameter
char str1[20] = “Don” , str2[20] = “Bosqo”;
strcat(str1,str2);
puts(str1);
• Our major concern is to determine whether the strings are equal; if not,
which is alphabetically above.
• The value of the mismatch is rarely important. For example, the statement
strcmp(“their”, “there”);
• will return a value of –9 which is the numeric difference between ASCII “i”
and ASCII “r”.
• That is, “i” minus “r” in ASCII code is –9.
• If the value is negative, string1 is alphabetically above string2.
String Functions – strcpy()
• The strcpy function works almost like a string-assignment operator. It
takes the following form:
strcpy(string1, string2);
• and assigns the contents of string2 to string1. string2 may be a character
array variable or a string constant.
• For example, the statement
strcpy(city, “DELHI”);
• will assign the string “DELHI” to the string variable city. Similarly, the
statement
strcpy(city1, city2);
• will assign the contents of the string variable city2 to the string variable
city1. The size of the array city1 should be large enough to receive the
contents of city2.
String Functions – strlen()
• This function counts and returns the number of characters in a string. It
takes the form
n = strlen(string);
• Where n is an integer variable, which receives the value of the length of
the string.
• The argument may be a string constant. The counting ends at the first null
character.
Point Explanation
No of Parameters 1
Parameter Taken Character Array Or String Return Type
Return Type Integer
Description Compute the Length of the String
Header file string.h
String Functions – strlen() (Cont..)
Different Ways of Using strlen() :
• There are different ways of using strlen function. We can pass different
parameters to strlen() function.
#include<stdio.h>
#include<string.h> Output:
int main() String before strrev():Hello
{ String after strrev(): olleH
char name[30] = "Hello";
printf("String before strrev() :%s\n",name);
printf("String after strrev():%s", strrev(name));
return 0;
}
String Functions – strstr
• It is a two-parameter function that can be used to locate a sub-string in a
string. This takes the following forms:
strstr (s1, s2);
strstr (s1, “ABC”);
• The function strstr searches the string s1 to see whether the string s2 is
contained in s1.
• If yes, the function returns the position of the first occurrence of the sub-
string. Otherwise, it returns a NULL pointer.
• Example:
if (strstr (s1, s2) == NULL)
printf(“substring is not found”);
else
printf(“s2 is a substring of s1”);
String Functions – strstr (Cont..)
• We also have functions to determine the existence of a character in a string.
• The function call
strchr(s1, ‘m’);
• will locate the first occurrence of the character ‘m’ and the call
strrchr(s1, ‘m’);
• will locate the last occurrence of the character ‘m’ in the string s1.
String Functions – strstr (Cont..)
// Parameters as String initialized // Passing Direct Strings
using Pointers #include<stdio.h>
#include<stdio.h> #include<string.h>
#include<string.h> void main()
int main(void) {
{ char *ptr;
char *str1 = "c4learn.blogspot.com", ptr =
*str2 = "spot", *ptr; strstr("c4learn.blogspot.com","spot");
ptr = strstr(str1, str2); printf("The substring is: %sn", ptr);
printf("The substring is: %sn", ptr); }
return 0;
} Output: Output:
The substring is: spot.com The substring is: spot.com
String Functions – strtok
• The strtok() function is used to split a string into a series of tokens based
on a particular delimeter.
• A token is a substring extracted from the original string.
• Syntax:
char *strtok(char *str, const char *delim)
where, str: The string which is to be split
delim: The character on the basis of which the split will be done
• The function performs one split and returns a pointer to the token split up.
A null pointer is returned if the string cannot be split.
String Functions – strtok - Example
// Extracting a single token // Extracting all possible tokens
#include<stdio.h>
#include<stdio.h>
#include <string.h>
#include <string.h> int main() {
int main() { char string[50] = "Hello! We are learn
ing about strtok";
char string[50] = "Hello world"; char * token = strtok(string, " ");
char * token = strtok(string, " "); while( token != NULL ) {
printf( " %s\n", token ); printf( " %s\n", token );
token = strtok(NULL, " ");
return 0; }
} return 0;
Output: }
Hello
ARITHMETIC
CHARACTERS ON
STRINGS
Arithmetic characters on strings
• C Programming Allows you to Manipulate on String.
• Whenever the Character is variable is used in the expression then it is
automatically Converted into Integer Value called ASCII value.
• All Characters can be Manipulated with that Integer Value.
(Addition,Subtraction)
• Examples :
• ASCII value of : ‘a’ is 97
• ASCII value of : ‘z’ is 121
Arithmetic characters on strings (Cont..)
Possible Ways of Manipulation :
UNIT 3
Course Learning Outcome (CLO – 3)
n! = n X (n-1)! 1! = 1
(n-1)! = (n-1) X (n-2)! 2! = 2 X 1! = 2 X 1 = 2
(n-2)! = (n-2) X (n-3)1 3! = 3 X 2! = 3 X 2 = 6
….. 4! = 4 X 3! = 4 X 6 = 24
2! = 2 X 1! ...
n! = n X (n-1)! = ...
• This reversal in the order of execution is a characteristic of all
functions executed recursively.
• If a recursive function contains local variables, a different set of
local variables will be created during each call. The names of the
local variables will, of course, always be the same, as declared
within the function. However, the variables will represent a
different set of values each time the function is executed.
Recursion Functions – The tower of hanoi
• The Towers of Hanoi is a well-known children’s game, played with three
poles and a number of different sized disks. Each disk has a hole in the
center, allowing it to be stacked around any of the poles.
• Initially, the disks are stacked on the leftmost pole in the order of
decreasing size, i.e., the largest on the bottom and the smallest on the top.
Recursion Functions – The tower of hanoi
• The object of the game is to transfer the disks from the leftmost pole to the
rightmost pole, without ever placing a larger disk on top of a smaller disk.
• Only one disk may be moved at a time and each disk must always e placed
around one of the poles.
• The general strategy is to consider one of the poles to be origin, and
another to be the destination. The third pole will be used for intermediate
storage, thus allowing the disks to be moved without lacing a larger disk
over a smaller one.
• Assume there are n disks, numbered from smallest to largest as shown in
the figure. The problem can be stated in the following recursive manner:
1. Move the top n-1 disks from the left pole to the center pole.
2. Move the nth disk (the largest disk) to the right pole.
3. Move the n-1 disks on the center pole to the right pole.
Recursion Functions – The tower of hanoi