Strings and Stack Operations (Arrays and Dynamic Memory)
Strings and Stack Operations (Arrays and Dynamic Memory)
1.5 Strings
A String is a sequence of characters terminated with a null character ‘\0’.
The C String is stored as an array of characters.
The difference between a character array and a C string is that the string in C is terminated
with a unique character ‘\0’.
To use string functions in c we should use <string.h> header file.
Syntax
Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char string_name[size];
In the above syntax string_name is any name given to the string variable and size is used
to define the length of the string, i.e the number of characters strings will store.
There is an extra terminating character which is the Null character (‘\0’) used to indicate
the termination of a string that differs strings from normal character arrays.
Initialization
A string in C can be initialized in 4 different ways.
int main() {
char str[50];
printf("Enter the String:”);
scanf("%s",str); // reading string
printf("%s",str); // print string
return 0;
}
Output: Enter the String: Data Structures Data
Enter the String: DataStructures DataStructures
Note: Here, the string is read only till the whitespace is encountered.
Array of Strings in C
In C programming String is a 1-D array of characters and is defined as an array of
characters.
But an array of strings in C is a two-dimensional array of character types. Each String is
terminated with a null character (\0). It is an application of a 2d array.
Syntax
char variable_name[r] = {list of string};
var_name is the name of the variable in C.
r is the maximum number of string values that can be stored in a string array.
c is the maximum number of character values that can be stored in each string array.
Example
#include <stdio.h>
int main()
{
// Declare an array of strings
char names[10][20];
int n;
strcat() It will append a copy of the char *strcat(char* dest, const char
String source string to the end of the *src);
Concatenation destination string. dest: Destination string
src: Source string
returns a pointer to the dest string.
strncat() Function appends not more char* strncat(char* dest, const char*
String Concatenation than n characters from the src, size_t n);
with number of string pointed to by src to the where n represents the maximum
characters to append end of the string pointed by number of characters to be appended
dest plus a terminating Null- size_t is a special unsigned integer
character.
int main()
{
//STRING CONCATINATION
char dest[50] = "This is an";
char src[50] = " example";
strcat(dest, src); // concatenating src at the end of dest
printf("String Concatenation Result: %s", dest);
//STRING n CONCATINATION
char dest1[50] = "This is an";
char src1[50] = " example";
strncat(dest1, src1, 5); // concatenating src at the end of dest
printf("\nString n Concatenation Result: %s", dest1);
//STRING LENGTH
char str[] = "DataStructures";
size_t length = strlen(str);
printf("\nString Length: %zu\n", length); //to print size_t result
//STRING COMPARE
char str1[] = "Hello";
char str2[] = "How";
char str3[] = "Hello";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str2, str3);
int result3 = strcmp(str1, str3);
printf("\nComparison of str1 and str2: %d\n", result1);
printf("Comparison of str2 and str3: %d\n", result2);
printf("Comparison of str1 and str1: %d\n", result3);
//STRING n COMPARE
int result11 = strncmp(str1, str2, 2);
int result12 = strncmp(str2, str3, 2);
int result13 = strncmp(str1, str3, 2);
printf("\nComparison of str1 and str2: %d\n", result11);
printf("Comparison of str2 and str3: %d\n", result12);
printf("Comparison of str1 and str1: %d\n", result13);
//STRING COPY
//STRING n COPY
char source1[] = "Data Structures";
char dest22[20];
strncpy(dest22, source, 6);
printf("Source: %s\t\t", source1);
printf("Destination: %s\n", dest22);
// STRING SEARCH
char s1[] = "Data Structures";
char s2[] = "ruct";
char *result5;
result5 = strstr(s1, s2);
if (result5 != NULL)
printf("Substring found: %s\n", result5);
else
printf("Substring not found.\n");
return 0;
Output:
String Concatenation Result: This is an example
String n Concatenation Result: This is an exam
String Length: 14
Comparison of str1 and str2: -10 Comparison of str2 and str3: 10
Comparison of str1 and str1: 0
int main() {
char myString[] = "Hello, World!";
int length = stringLength(myString);
return 0;
}
Output: Length of the string: 13
int main() {
char str1[20];
char str2[20];
if (stringCompare(str1, str2)) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
return 0;
}
Output:
Enter the first string : Hello Enter the second string : Hello
Strings are equal.
Enter the first string : Hello Enter the second string : hello
Strings are not equal.
int main() {
char source[20];
char destination[20];
printf("Enter the first string : ");
gets(source);
stringCopy(source, destination);
printf("Copied String: ");
puts(destination);
return 0;
}
Output: Enter the first string : Hello World
Copied String: Hello World
1.6 Stacks
1.6.1 Definition
A stack is a linear structure in which items may be added or removed only at one end called
the top of the stack (TOP). Stacks are sometimes known as LIFO (last in, first out) lists.
As the items can be added or removed only from the top i.e. the last item to be added to a
stack is the first item to be removed.
The two basic operations associated with stacks are:
o Push: is the term used to insert an element into a stack.
o Pop: is the term used to delete an element from a stack.
All insertions and deletions take place at the same end, so the last element added to the
stack will be the first element removed from the stack.
When a stack is created, the stack base remains fixed while the stack top changes as
elements are added and removed. The most accessible element is the top and the least
accessible element is the bottom of the stack.
1.6.2 Representation
Let us consider a stack with N elements capacity. This is called as the size of the stack.
The number of elements to be added should not exceed the maximum size of the stack.
If we attempt to add new element beyond the maximum size, we will encounter a stack
overflow condition.
Similarly, you cannot remove elements beyond the base of the stack. If such is the case,
we will reach a stack underflow condition (an empty stack).
When an element is added to a stack, the operation is performed by push.
The removal of an element is performed by the pop operation.
Algorithm:
Step 1: Check whether stack is FULL. (top == SIZE-1)
Step 2: If it is FULL, then display "Stack is FULL!!! Stack overflow!!!" and terminate the function.
Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).
Algorithm:
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate
the function.
Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).
Algorithm:
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i] value
and decrement i value by one (i--).
Step 3: Repeat above step until i value becomes '0'.
Example
Empty stack (Refer Fig. A)
Push element 1 (Refer Fig. B)
Push element 2 into stack (Refer Fig. C)
Push element 3 into stack (Refer Fig. D)
Pop (last element will be removed pointed by top) (Refer Fig. E)
A B C D E
Support the program with appropriate functions for each of the above operations
Program
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int stack[MAX];
int top = -1;
int pop()
{
if (top == -1)
{
printf("Stack Underflow! Cannot pop from an empty stack.\n");
return -1;
}
else
{
int ele = stack[top--];
return ele;
}
}
int isPalindrome()
{
int i, j;
for (i = top, j = 0; i >= j; i--, j++)
{
if (stack[i] != stack[j])
{
return 0; // Not a palindrome
}
}
return 1; // Palindrome
}
void displayStack()
{
if (top == -1) {
printf("Stack is empty.\n");
} else
{
printf("Stack elements: ");
for (int i = top; i >=0; i--)
printf("%d\t", stack[i]);
printf("\n");
}
}
int main()
{
int choice, element;
do {
printf("\n----- Menu -----\n");
switch (choice)
{
case 1:
printf("Enter the element to push: ");
scanf("%d", &element);
push(element);
break;
case 2:
int val=pop();
printf("%d popped from the stack.\n", val);
break;
case 3:
if (isPalindrome())
printf("The stack is a palindrome.\n");
else
printf("The stack is not a palindrome.\n");
break;
case 4:
displayStack();
break;
case 5:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice! Please enter a valid option.\n");
}
} while (choice != 5);
return 0;
}
Overflow/Underflow:
No limitation on the capacity of a linked stack and hence no overflow condition.
Underflow or empty condition occurs when top==NULL.
Example
struct node
{
int data;
struct node *link;
}*top = NULL;
void push(int);
int pop();
void Stack_Empty();
void Stack_Full();
void Display();
int Stack_Count();
void Destroy();
void Print_Top();
int main()
{
int choice, val;
while (1)
{
printf("\n1. PUSH an element \n");
printf("2. POP an element \n");
printf("3. Check if Stack is Empty \n");
printf("4. Check if Stack is Full \n");
printf("5. Display Elements present in Stack \n");
printf("6. Destroy Stack \n");
printf("7. Print Top of the Stack \n");
printf("8. Exit \n");
printf("Enter your choice: ");
scanf("%d",&choice); // Reading choice from keyboard
switch (choice)
{
case 1:
printf("\nEnter value to push into the stack : ");
scanf("%d",&val);
push(val);
break;
case 2:
val=pop();
printf("\nDeleted Node Value is %d : ", val);
break;
case 3:
Stack_Empty();
break;
case 4:
Stack_Full();
break;
case 5:
Display();
break;
case 6:
Destroy();
break;
case 7:
Print_Top();
break;
case 8: exit(0);
return val;
}
temp = top;
if (top == NULL)
printf("\n**Stack is Empty**\n");
else
{
printf("Contents of the Stack\n");
int Stack_Count()
{
int count = 0;
struct node *temp;
temp = top;
while (temp!= NULL)
{
temp = temp->link;
count++;
}
return count;
}