0% found this document useful (0 votes)
6 views27 pages

Practicals 1

The document contains multiple C programming exercises covering string operations, pattern matching, linear search, sorting algorithms, and data structures like stacks and queues. Each section includes code snippets, input/output examples, and explanations of the implemented algorithms. The exercises also demonstrate the use of recursion and linked lists.

Uploaded by

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

Practicals 1

The document contains multiple C programming exercises covering string operations, pattern matching, linear search, sorting algorithms, and data structures like stacks and queues. Each section includes code snippets, input/output examples, and explanations of the implemented algorithms. The exercises also demonstrate the use of recursion and linked lists.

Uploaded by

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

1.

Write a menu driven C program to perform the following string operations


without using string functions: (i) String Length (ii) String Concatenation
#include <stdio.h>
// Function to calculate string length
int string_length(char str[]) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}

// Function to concatenate two strings


void string_concatenation(char str1[], char str2[], char result[]) {
int i = 0, j = 0;
// Copy first string to result
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
// Append second string to result
while (str2[j] != '\0') {
result[i] = str2[j];
i++;
j++;
}
// Null terminate the result string
result[i] = '\0';
}

int main() {
int choice;
char str1[100], str2[100], result[200];

do {
printf("\nMenu:\n");
printf("1. String Length\n");cl
printf("2. String Concatenation\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // To consume newline left by scanf
switch (choice) {
case 1:
printf("Enter a string: ");
gets(str1);
printf("Length of the string: %d\n", string_length(str1));
break;

case 2:
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
string_concatenation(str1, str2, result);
printf("Concatenated String: %s\n", result);
break;
case 3:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice! Please enter a valid option.\n");
}
} while (choice != 3);

return 0;
}
Output:
Menu:
1. String Length
2. String Concatenation
3. Exit
Enter your choice: 1
Enter a string: Hello World
Length of the string: 11
Menu:
1. String Length
2. String Concatenation
3. Exit
Enter your choice: 2
Enter first string: Hello
Enter second string: World
Concatenated String: HelloWorld
Menu:
1. String Length
2. String Concatenation
3. Exit
Enter your choice: 3
Exiting the program.
2.Write a C program to find a pattern in a given text using pattern matching
algorithm.
.#include<stdio.h>
#include<string.h>
void patternMatching(char text[], char pattern[])
{
int textLen = strlen(text); // Length of text
int patternLen = strlen(pattern); // Length of pattern
int found = 0;
// Loop through text to check each character
for(int i = 0; i <= textLen - patternLen; i++) {
int j;
// Check if pattern matches at index i
for(j = 0; j < patternLen; j++) {
if(text[i + j] != pattern[j]) {
break; // If characters don't match, break loop
}
}
if(j == patternLen) { // If full pattern matches
printf("Pattern found at index %d\n", i);
found = 1;
}
}

if(found == 0) {
printf("Pattern not found.\n");
}
}

int main() {
char text[100], pattern[50];
printf("Enter the text: ");
gets(text); // Input the text
printf("Enter the pattern to search: ");
gets(pattern); // Input the pattern
patternMatching(text, pattern); // Function call
return 0;
}
Input:
Enter the text: welcome to coding
Enter the pattern to search: coding
Output:
Pattern found at index 11
3. Write a program to search for an element in an array using linear search.
#include <stdio.h>
int main() {
int n, i, key, found = 0;
// Input number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n]; // Array declaration
// Input array elements
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input the element to search
printf("Enter element to search: ");
scanf("%d", &key);
// Linear Search algorithm
for (i = 0; i < n; i++) {
if (arr[i] == key) {
printf("Element found at index %d\n", i);
found = 1;
break; // Exit loop when element is found
}
}

// If element is not found


if (!found) {
printf("Element not found in the array\n");
}
return 0;
}
Output:
Enter number of elements: 5
Enter 5 elements: 10 20 30 40 50
Enter element to search: 30
Element found at index 2

4. Write a program to sort list of n numbers using Bubble Sort algorithms.


#include <stdio.h>
int main() {
int n, i, j, temp;
// Input number of elements
int arr[n];
// Array declaration
printf("Enter the number of elements: ");
scanf("%d", &n);
// Input array elements
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Bubble Sort algorithm
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Print the sorted array
printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

Output:
Enter number of elements: 5
Enter 5 elements: 5 3 8 1 2
Sorted array: 1 2 3 5 8
5.Perform the Insertion sort on the input {75,8,1,16,48,3,7,0} and display the
output in descending order.
#include <stdio.h>
int main()
{
int arr[] = {75, 8, 1, 16, 48, 3, 7, 0};
// Insertion Sort in descending order
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] < key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}

// Print sorted array


printf("Sorted Array in Descending Order: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Sorted Array in Descending Order: 75 48 16 8 7 3 1 0

6.Write a program for Towers of Honoi problem using recursion.


#include <stdio.h>
// Function to solve the Towers of Hanoi problem
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
// Base case: If only one disk is left, move it from source to destination
if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, destination);
return;
}

// Step 1: Move n-1 disks from source to auxiliary using destination as


auxiliary
towerOfHanoi(n - 1, source, destination, auxiliary);

// Step 2: Move the nth disk from source to destination


printf("Move disk %d from %c to %c\n", n, source, destination);

// Step 3: Move the n-1 disks from auxiliary to destination using source as
auxiliary
towerOfHanoi(n - 1, auxiliary, source, destination);
}

int main() {
int n;
// Input the number of disks
printf("Enter the number of disks: ");
scanf("%d", &n);
// Call the function to solve the problem
printf("\nSteps to solve the Towers of Hanoi for %d disks:\n", n);
towerOfHanoi(n, 'A', 'B', 'C'); // A is the source, B is the auxiliary, C is the
destination

return 0;
}
Output:
Enter the number of disks: 3
Steps to solve the Towers of Hanoi for 3 disks:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
7 .Write a Program to implement stack using array
#include <stdio.h>
#define MAX 5 // Maximum size of the stack
int stack[MAX];
int top = -1; // Stack is initially empty
// Function to check if the stack is full
int isFull() {
return top == MAX - 1;
}

// Function to check if the stack is empty


int isEmpty() {
return top == -1;
}
// Push operation to add an element to the stack
void push(int value) {
if (isFull()) {
printf("Stack Overflow\n");
}
else
{
stack[++top] = value;
printf("%d pushed to stack\n", value);
}
}
// Pop operation to remove an element from the stack
int pop() {
if (isEmpty()) {
printf("Stack Underflow\n");
return -1;
}
else
{
return stack[top--];
}
}
// Display the stack
void display() {
if (isEmpty()) {
printf("Stack is empty\n");
}
else
{
printf("Stack elements: ");
for (int i = 0; i <= top; i++)
{
printf("%d ", stack[i]);
}
printf("\n");
}
}
int main() {
// Basic operations to demonstrate stack functionality
display();
push(10);
push(20);
push(30);
push(40);
push(50);
push(60); // Will overflow
display();
printf("%d popped from stack\n", pop());
printf("%d popped from stack\n", pop());
display();
push(60);
display();
return 0;
}
Output:
Stack is empty
10 pushed to stack
20 pushed to stack
30 pushed to stack
40 pushed to stack
50 pushed to stack
Stack Overflow
Stack elements: 10 20 30 40 50
30 popped from stack
20 popped from stack
Stack elements: 10 40 50
60 pushed to stack
Stack elements: 10 40 50 60

8.Write a program to insert the elements {45, 34, 10, 63,3} into linear queue
and delete three elements from the list. Display your list after each insertion
and deletion.
#include <stdio.h>
#define SIZE 10

int queue[SIZE];
int front = -1, rear = -1;

// Function to insert an element


void enqueue(int value) {
if (rear == SIZE - 1)
{
printf("Queue is full.\n");
return;
}
if (front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("Inserted %d -> ", value);
display();
}

// Function to delete an element


void dequeue() {
if (front == -1 || front > rear)
{
printf("Queue is empty.\n");
return;
}
printf("Deleted %d -> ", queue[front]);
front++;
display();
}

// Function to display the queue


void display() {
if (front == -1 )
{
printf("Queue is empty.\n");
return;
}
printf("Queue: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
int main() {
// Insert elements
enqueue(45);
enqueue(34);
enqueue(10);
enqueue(63);
enqueue(3);
// Delete three elements
dequeue();
dequeue();
dequeue();
return 0;
}

Output:
Inserted 45 -> Queue: 45
Inserted 34 -> Queue: 45 34
Inserted 10 -> Queue: 45 34 10
Inserted 63 -> Queue: 45 34 10 63
Inserted 3 -> Queue: 45 34 10 63 3
Deleted 45 -> Queue: 34 10 63 3
Deleted 34 -> Queue: 10 63 3
Deleted 10 -> Queue: 63 3

PART B
11.Given S1={“Flowers”} ; S2={“are beautiful”} I. Find the length of S1 II.
Concatenate S1 and S2 III. Extract the substring “low” from S1 IV. Find “are” in
S2 and replace it with “is” .
#include <stdio.h>
#include <string.h>
int main()
{
// Define the strings
char S1[] = "Flowers";
char S2[] = "are beautiful";
char substring[] = "low"; // Substring we want to extract from S1
char temp[100]; // To store the result of replacement

// I. Find the length of S1


int lengthS1 = strlen(S1);
printf("Length of S1: %d\n", lengthS1);

// II. Concatenate S1 and S2


char concatenated[200]; // To store the concatenated result
strcpy(concatenated, S1); // Copy S1 to concatenated
strcat(concatenated, " "); // Add a space between S1 and S2
strcat(concatenated, S2); // Concatenate S2 to concatenated
printf("Concatenated S1 and S2: %s\n", concatenated);

// III. Extract the substring "low" from S1


// Use strstr to find the substring in S1
char *sub = strstr(S1, substring); // Finds the first occurrence of "low" in S1
if (sub != NULL) {
printf("Extracted substring 'low': %.s\n", sub);
}
else
{
printf("Substring 'low' not found in S1\n");
}

// IV. Find "are" in S2 and replace it with "is"


// Use strstr to find "are" in S2 and replace it
strcpy(temp, S2); // Copy S2 into temp
char *pos = strstr(temp, "are");
if (pos != NULL) {
// Replace "are" with "is"
strncpy(pos, "is", 3); // Replace the first two characters with "is"
printf("Replaced 'are' with 'is' in S2: %.3s\n", temp);
} else {
printf("'are' not found in S2\n");
}
return 0;
}
Output:
Length of S1: 7
Concatenated S1 and S2: Flowers are beautiful
Extracted substring 'low': low
Replaced 'are' with 'is' in S2: is beautiful

12 Write a C program to count the number of nodes in a linked list.


#include <stdio.h>
// Define the Node structure
struct Node {
int data;
struct Node* next;
};
int main() {
// Manually creating a linked list of 3 nodes
struct Node n1, n2, n3;

// Initializing the nodes


n1.data = 10;
n1.next = &n2;

n2.data = 20;
n2.next = &n3;

n3.data = 30;
n3.next = NULL; // Last node points to NULL

// Head points to the first node


struct Node* head = &n1;

// Count the number of nodes


int count = 0;
struct Node* temp = head;

// Traverse the linked list and count nodes


while (temp != NULL) {
count++;
temp = temp->next;
}
// Output the result
printf("Number of nodes in the linked list: %d\n", count);
return 0;
}
Output:
Number of nodes in the linked list: 3
13 Write a program to convert an infix expression x^y/(5*z)+2 to its postfix
expression
#include <stdio.h>
#include <ctype.h>
int main() {
char infix[] = "x^y/(5*z)+2";
char stack[100], postfix[100];
int top = -1, i = 0, j = 0;

while (infix[i] != '\0') {


char ch = infix[i];

if (isalnum(ch)) {
postfix[j++] = ch;
}
else if (ch == '(') {
stack[++top] = ch;
}
else if (ch == ')') {
while (top != -1 && stack[top] != '(') {
postfix[j++] = stack[top--];
}
top--; // pop '('
}
else { // operator
// precedence manually checked for simplicity
while (top != -1 && stack[top] != '(' &&
((ch != '^' && (stack[top] == '^' || stack[top] == '*' || stack[top] == '/'
|| stack[top] == '+' || stack[top] == '-')) || (ch == '+' || ch == '-') && (stack[top]
== '*' || stack[top] == '/' || stack[top] == '^') || (ch == '*' || ch == '/') &&
(stack[top] == '^')))
{
postfix[j++] = stack[top--];
}
stack[++top] = ch;
}
i++;
}
while (top != -1) {
postfix[j++] = stack[top--];
}
postfix[j] = '\0';
printf("Postfix Expression: %s\n", postfix);
return 0;
}
Output:
Postfix Expression: xy^5z*/2+

14 Write a program to evaluate a postfix expression 5 3+8 2 - *.


#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main() {
char postfix[] = "5 3 + 8 2 - *";
int stack[100];
int top = -1;
int i = 0;

while (postfix[i] != '\0') {


char ch = postfix[i];

if (ch == ' ') {


i++;
continue;
}

if (isdigit(ch)) {
int num = ch - '0';
stack[++top] = num;
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
int val2 = stack[top--];
int val1 = stack[top--];
int result;

if (ch == '+')
result = val1 + val2;
else if (ch == '-')
result = val1 - val2;
else if (ch == '*')
result = val1 * val2;
else
result = val1 / val2;
stack[++top] = result;
}
i++;
}
printf("Result of the postfix expression: %d\n", stack[top]);
return 0;
}

Output:
Result of the postfix expression: 48
15 Write a C program to simulate the working of Linear Queue using an array.
#include <stdio.h>
#define SIZE 5 // Size of the queue
int queue[SIZE];
int front = -1, rear = -1;

// Function to insert an element into the queue


void enqueue(int value) {
if (rear == SIZE - 1) {
printf("Queue is full.\n");
} else {
if (front == -1) {
front = 0; // If queue is empty, set front to 0
}
rear++;
queue[rear] = value;
printf("Inserted %d\n", value);
}
}

// Function to delete an element from the queue


void dequeue() {
if (front == -1 || front > rear) {
printf("Queue is empty.\n");
}
else
{
printf("Deleted %d\n", queue[front]);
front++;
}
}

// Function to display the elements of the queue


void display() {
if (front == -1 || front > rear) {
printf("Queue is empty.\n");
} else {
printf("Queue: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}

int main() {
// Inserting elements into the queue
enqueue(10);
enqueue(20);
enqueue(30);
// Displaying the queue
display();
// Deleting an element from the queue
dequeue();
dequeue();
// Displaying the queue again
display();
return 0;
}
Output:
Inserted 10
Inserted 20
Inserted 30
Queue: 10 20 30
Deleted 10
Deleted 20
Queue: 30

You might also like