You are on page 1of 9

Lakshay Gupta

CSE – A
04020802718

PRINCIPLES OF PROGRAMMING LANGUAGES LAB

1. Implement all major functions of string.h in single C


program using switch case to select specific function from
user choice (like strlen, strcat, strcmp, strrev)

#include <stdio.h>
#include <string.h>

int stringcompare(char *a,char *b)


{
int flag=0;
while(*a!='\0' && *b!='\0')
{
if(*a!=*b)
{
flag=1;
}
a++;
b++;
}

if(flag==0)
return 0;
else
return 1;
}

int main()
{
char str[50];
printf (" Enter the string: ");
gets("%s", &str);

char str2[50];
printf (" Enter the string: ");
gets("%s", &str2);

char str3[100];

int x;

printf("Enter your choice : ");


scanf("%d", &x);
switch (x) {
case 1:
printf("\nString Length : ");
int i;
for (i = 0; str[i] != '\0'; ++i);
printf("Length of Str is %d", i);
break;

case 2:
int i = 0, j = 0;
printf("\nString Concatenation : ");
while (str[i] != '\0') {
str3[j] = str[i];
i++;
j++;
}

i = 0;
while (str2[i] != '\0') {
str3[j] = str2[i];
i++;
j++;
}
str3[j] = '\0';
printf("\nConcatenated string: %s", str3);
break;

case 3:
printf("\nString Compare : ");
int compare=stringcompare(str1,str2);
if(compare==0)
printf("strings are equal");
else
printf("strings are not equal");
break;

case 4:
int i, len, temp;
len = strlen(str1);

for (i = 0; i < len/2; i++)


{
temp = str1[i];
str1[i] = str1[len - i - 1];
str1[len - i - 1] = temp;
}

printf("\nReverse string: %s", str3);


break;
default:
printf("Choice other than 1, 2, 3 and 4");
break;
}
}
2. Write a program (WAP) in C to reverse a linked list
iterative and recursive.
#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node* next;
};

static void iterativeReverse(struct Node** head_ref)


{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}

void recursiveReverse(struct Node** head_ref)


{
struct Node* first;
struct Node* rest;

if (*head_ref == NULL)
return;

first = *head_ref;
rest = first->next;

if (rest == NULL)
return;

recursiveReverse(&rest);
first->next->next = first;

first->next = NULL;

*head_ref = rest;
}

void push(struct Node** head_ref, int new_data)


{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;
}

void printList(struct Node *head)


{
struct Node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}

void main()
{
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);

printf("Given linked list\n");


printList(head);
iterativeReverse(&head);
printf("\nReversed Linked list \n");
printList(head);
recursiveReverse(&head);
printf("\Normal Linked list \n");
printList(head);
getchar();
}

You might also like