Tuesday, 7 April 2026

DATA STRUCTURE LAB PROGRAMS

 

1) Write a C Program to find the GCD using recursive function

#include <stdio.h>

int hcf(int n1, int n2);

int main() {

    int n1, n2;

    printf("Enter two positive integers: ");

    scanf("%d %d", &n1, &n2);

    printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));

    return 0;

}

int hcf(int n1, int n2) {

    if (n2 != 0)

        return hcf(n2, n1 % n2);

    else

        return n1;

}

===================================================

2) Write a C Program to implement dynamic array, find the smallest and largest of the array.

#include <stdio.h>

#include <stdlib.h>

void main()

{

  int n,i;

  double *data;

  printf("Enter the total number of elements: ");

  scanf("%d", &n);

  // Allocating memory for n elements

  data = (double *)calloc(n, sizeof(double));

  if (data == NULL) {

    printf("Error!!! memory not allocated.");

    exit(0);

  }

  // Storing numbers entered by the user.

  for (i = 0; i < n; ++i) {

    printf("Enter number%d: ", i + 1);

    scanf("%lf", data + i);

  }

  // Finding the largest number

  for ( i = 1; i < n; ++i) {

    if (*data < *(data + i)) {

      *data = *(data + i);

    }

  }

  printf("Largest number = %.2lf", *data);

  free(data);

getch();

}

===================================================

3) Write a C Program to search an element using linear search technique.

/*C program to implement linear search */

#include<stdio.h>

void main()

{

int a[20],i,x,n;

clrscr();

printf("how many elements!");

scanf("%d",&n);

printf("enter the arrray elements:n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("enter elements to search:");

scanf("%d",&x);

for(i=0;i<n;i++)

if(a[i]==x)

break;

if(i<n)

printf("elements found at index %d",i);

else

printf("elements not found");

getch();

}

 

  

 

 ===================================================


4) Write a C program to implement binary search

/* C program to implement the binary search */

#include < stdio.h >  

void main()  

    int c, first, last, middle, n, search, array[100]; 

    printf("Enter number of elements\n"); 

    scanf("%d", &n); 

    printf("Enter %d integers\n", n); 

    for (c = 0; c < n; c++) scanf("%d", & array[c]); 

    printf("Enter value to find\n"); 

    scanf("%d", & search); 

    first = 0; 

    last = n - 1; 

    middle = (first + last) / 2; 

    while (first <= last) 

    { 

        if (array[middle] < search) first = middle + 1; 

        else if (array[middle] == search)

       { 

            printf("%d found at location %d.\n", search, middle + 1); 

            break; 

        } else last = middle - 1; 

        middle = (first + last) / 2; 

    } 

    if (first > last) printf("Not found! %d is not present in the list.\n", search); 

  getch();

}


No comments:

Post a Comment