K L UNIVERSITY

Responsive Advertisement

C&Ds test-1 key

KL University, AP

Department of BES:FED
AY 2016-2017(Even Semester)
Subject: C& DS-II (15CS1201)
Test-1(17.01.2017) Answer Key

1. (a)
Write a C program to count characters at same position as in English alphabets given. Given a string of lower and upper case characters, the task is to find that how many characters are at same position as in English alphabets.
Examples:
Input : ABcED
Output :3
First three characters are at same position as in English alphabets.
Sol)
#include<stdio.h>
#include<conio.h>
#define size 26

int findCount(char str[size])
{
    int result = 0,i;
    for (i = 0 ; i < size; i++)
                if (i == (str[i] - 'a') || i == (str[i] - 'A'))
                    result++;
    return result;
}
int main()
{
    char str[size];
    clrscr();
    printf("Enter string");
    gets(str);
    printf("\n %d",findCount(str));
    return 0;
}

b) Find pair for given sum in a sorted singly Linked List.
Given a sorted singly linked list and a value X, the task is to find pair whose sum is equal to X.
Example :
Input : head=3à6à 7à 8à 9à 10à 11, X=17
Output : (6,11), (7, 10), (8,9).

Ans)
#include<stdio.h>
#include<conio.h>
// structure of node of doubly linked list
struct Node
{
    int data;
    struct Node *next, *prev;
};
// Function to find pair whose sum equal to given value x.
void pairSum(struct Node *head, int x)
{
    // Set two pointers, first to the beginning of DLL
    // and second to the end of DLL.
    struct Node *first = head;
    struct Node *second = head;
    int found=0;
    while (second->next != NULL)
             second = second->next;
    while (first != NULL && second != NULL &&
               first != second && second->next != first)
    {
             // pair found
             if ((first->data + second->data) == x)
             {
                  found = 1;
                  printf("(%d,%d)",first->data,second->data);
                  // move first in forward direction
                  first = first->next;
                  // move second in backward direction
                  second = second->prev;
              }
              else
              {
                  if ((first->data + second->data) < x)
                         first = first->next;
                  else
                         second = second->prev;
              }
      }
      // if pair is not present
      if (found ==0)
      printf("No pair found");
}
// A utility function to insert a new node at the
// beginning of doubly linked list
void insert(struct Node **head, int data)
{
    struct Node *temp = (struct Node *)malloc(sizeof(struct Node));//new Node;
    temp->data = data;
    temp->next = temp->prev = NULL;
    if (!(*head))
            (*head) = temp;
    else
    {
            temp->next = *head;
            (*head)->prev = temp;
            (*head) = temp;
    }
}
int main()
{
    struct Node *head = NULL;
    int x;
    clrscr();
    insert(&head, 11);
    insert(&head, 10);
    insert(&head, 9);
    insert(&head, 8);
    insert(&head, 7);
    insert(&head, 6);
    insert(&head, 3);
    x = 17;
    pairSum(head, x);
    return 0;
}

2.(a). C program to find a smallest word in a string
Ex. Enter string: Amazing programmers exists here.
output: The largest word is ‘programmers’ and The smallest word is ‘here’ in amazing programmers exists ‘here’.
solution:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char text[]="Amazing programmers exists here ";
char t1[10];
char str[10][20];
int i,j,k,c=0;
int l[20];
int min=0,r;
clrscr();
puts(text);
for(i=0;text[i]!='\0';i++)
{  if(text[i]==' '||text[i]=='\n')
    c++;
}
k=0;
j=0;
for(i=0;text[i]!='\0';i++)
{
if(text[i]==' ')
{
t1[j]='\0';
strcpy(str[k++],t1);
j=0;
}
else
{
t1[j++]=text[i];
}
}
for(i=0;i<k;i++)
{
l[i]=strlen(str[i]);
}
min=l[0];
for(i=0;i<k;i++)
if(l[i]<min)
{
min=l[i];
r=i;
}
printf("\nsmallest word in given string is: %s",str[r]);
getch();
}

2.(b) Write a function to insert a node at end of Double Linked list
void insert_end(struct node *start)
{
struct node *new_node,*ptr;
new_node=(struct node *)malloc(sizeof(struct node*));
printf("\n Enter value to insert into node");
scanf("%d",&new_node->data);
ptr=start;
while(ptr->next!='\0')
ptr=ptr->next;
ptr->next=new_node;
new_node->prev=ptr;
new_node->next='\0';
}

3(a) Given a line of text T and a pattern(substring) P. Write an algorithm that deletes 1st occurrence of P in T.
Algorithm
1.Start
2.Read the main string and the substring
3. For each character in main string until length of it or until ‘\0’ is reached
4. compare it with each character in substring
5. If a mismatch occurs then set found=0;
6. Finally if found=1, then move the characters from right to left
i.etext[j] = text[j + len1];
7. Stop
//Instead of steps 3 &4 one can use strstr() function in string.h to get the pointer to first occurrence of the  substring in the main string.
////SYNTAX:char *strstr(char * mainstring,char *substring)
Program
#include <stdio.h>
#include <string.h>
#define SIZE 100

void removeFirst(char *,char *);
void main()
{
    char text[SIZE];
    char substring[SIZE];
printf("Enter any string: ");
    gets(text);
printf("Enter string to be removed: ");
    gets(substring);
removeFirst(text, substring);
printf("\nFinal string after removing '%s' = %s", substring, text);
}


void removeFirst(char * text, char * substring)
{
inti, j;
intlen, len1;
int found = 0;

len = strlen(text);
    len1 = strlen(substring);

for(i=0; i<len; i++)
    {
        found = 1;
        for(j=0; j<len1; j++)
        {
            if(text[i+j] != substring[j])
            {
                found = 0;
                break;
            }
        }
//This finds the first occurrence of substring in a Main string

        if(found == 1)
        {
            for(j=i; j<len-len1; j++)
            {
                text[j] = text[j + len1];
            }

            text[j] = '\0';

            break;
        }
    }
}
3.(b) Write a program to create and print out the elements of a Single Linked List.

struct node
{
int data;
            struct node *link;
};
Typedef struct node * list;
//Use struct node * in place of list, if typedef is not used
//The below function takes start(or header) as argument and returns the same after creation is completed.

list create(list start)
{
int item;
list new1,ptr;  
printf("\nCreating the Single Linked List...");
printf("\nEnter the value:");
scanf("%d",&item);
 do
 {
  new1=(struct node *)malloc(sizeof(struct node));
  new1->data=item;
  new1->link=NULL;
  if(start==NULL)
  {
    start=new1;
ptr=new1;
  }
  else
  {
ptr->link=new1;
ptr=new1;
  }
printf("\nEnter the value:");
scanf("%d",&item);
 }while(item!=999);   //Loop stops if 999 is entered.. This value can be any other thing like 0.
return start;
}

void display(list start)
{
            if(start==NULL)
            {
printf("\nThe list is empty.So no elements to display.");
            }
            else
            {
list ptr=start;
printf("\nThe elements in the list are:");
                        while(ptr!=NULL)
                        {
printf("%d\t",ptr->data);
ptr=ptr->link;
                        }
            }
}

4.(a) Write and Test a Function hydroxide that returns a 1 for true if its string argument ends in the substring "OH". Try the function hydroxide on the following data:   KOH,H2O2,Nacl,NaOH,MgOH.

#include<stdio.h>
#include<conio.h>
#include<string.h>
int hydroxide();
void main()
{
            int res=0;
 clrscr();
            res=hydroxide();
 if(res==1)
                        printf("\nFound");
            else
 printf("\n Not Found");
getch();
}
int hydroxide()
{
            char str[10];
            printf("\n Enter a String");
            gets(str);
 if(str[strlen(str)-2]=='O'&&str[strlen(str)-1]=='H')
                        return 1;
            else
 return 0;
}
4.(b) Write a function to sort the given DLL.
void sort()
{
    int i, j, x;
    temp2 = h;
    temp4 = h;

    if (temp2 == NULL)
    {
        printf("\n List empty to sort");
        return;
    }

    for (temp2 = h; temp2 != NULL; temp2 = temp2->next)
    {
        for (temp4 = temp2->next; temp4 != NULL; temp4 = temp4->next)
        {
            if (temp2->n > temp4->n)
            {
                x = temp2->n;
                temp2->n = temp4->n;
                temp4->n = x;
            }
        }
    }
   
}

5(a) Define a structure data type named date containing three integer members day, month, year. Write a function to read the data into structure members and print the date in the following format using pointers:            January 09, 2001.      {5 Marks}
            #include<stdio.h>
            struct  date
            {
                        int dd,mm,yyyy;
           
} *d;

void main()
{
            printf(“Enter the date with day, month and year as dd, mm, yyyy format ”);
            scanf(“%d%d%d”, &d->dd, &d->mm, &d->yyyy);
            switch(d->mm)
            {
                        case 1: printf(“January”); break;
                        case 2: printf(“February”); break;
                        case 3: printf(“March”); break;
                        case 4 printf(“April”); break;
                        case 5: printf(“May”);break;
                        case 6: printf(“June”);break;
                        case 7: printf(“July”);break;
                        case 8: printf(“August”); break;
                        case 9: printf(“September”); break;
                        case 10: printf(“October”); break;
                        case 11: printf(“November”); break;
                        case 12: printf(“December”); break;
}
printf(“  %d    %d”, d->dd, d->yyyy);
}

5(b) Given an integer k, write an algorithm that deletes the kth element in doubly linked list.  Program:                                                                                                        {5 marks}
struct node
{
            int data;
            struct node *next, *prev;

} * head= NULL,*temp, *t,*p;

void   delete_element_at_any_Position()
{
            int  i,k,ele;
            printf(“Enter the position to be deleted”);
            scanf(“%d”,&k);

            for(i=1,p=head ; i < k ; i++, p=p->next )
{
            t=p;
}
t->next = p->next;
p->next -> prev = t;

ele = p->data;
free(p);
            printf(“The deleted data from the list is = %d ”,ele);
}

Algorithm:
1)      Define the structure node for three fields 1)data 2) next 3) prev
2)      Get the position of the node to be deleted.
3)      Stop the pointer  “p” at the position of the node to be deleted and pointer “t” at previous to the “p” pointer.
4)      Make the “t” pointer to be pointing to next to the “p” pointer.
5)      Make the  “p -> next” of  “prev” to point to “t” pointer.
6)      Display the deleted value on the screen.
7)       Finally delete the node totally from memory.
8)      Stop the operation.



6 a) C program to remove all characters in a string except alphabet.
Output: Enter a string: p2’r-0@gram84iz./
Output string: programiz
This program takes a string from the user and stored in the variable line. Then within the for loop,  each character in the string is checked if it’s an alphabet or not. If any character inside a string is not an alphabet all characters after it including the NULL character is shifted by 1 position to the left.

#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
int i,l,j;
printf(“enter a string”);
scanf( “%s”,str);
l=strlen(str);
for(i=0;str[i]!=\0’i++)
{
            if(isalpha(str[i]))==0)
            {
                   for(j=i;j<l;j++)
                      {
                                str[j]=str[j+1];
                        }
              }
 }
printf(“output string is %s”,str);
}

b) Write a function find() that returns a pointer to the node containing a specific key. The function should take single linked list as input parameter.
#include <stdio.h>
struct node
{
            int data;
            struct node *next;
};
struct node *start=NULL;
struct node  * find(struct node *temp, int key)
{
            while(temp!=NULL)
            {
                        if(temp->data==key)
                        {
                                    return(temp);
                        }
            }
            return(NULL);
}
void main()
{
            int key;
          printf(“enter key”);
          scanf(“%d”,&key);
          if(find(start)==NULL)
            printf(“key is not in the list”);
         else
            printf(“key is in the list”);
}
           


Post a Comment

0 Comments