Tuesday, February 17, 2015

Sample C Questions & Answers

C Questions & Answers

Binary search implementation using C language

#include<stdio.h>
#include<conio.h>
#define MAX 20

int bsearch(int [],int,int,int);

void main()
{
int a[10],i,t,f=0,n,l,k;
int bsearch(int[],int,int,int);
clrscr();
printf("\n\nEnter the size of an array: ");
scanf("%d",&n);

if (n>MAX)
{
printf("\nInvalid Index\n");
}
else
{
printf("\nEnter the array elements:\n");
}

    for(i=0;i<n;i++)
    {
    scanf("%d",&a[i]);
    }

printf("\n\n Enter element for search: ");
scanf("%d",&t);
l=n-1;
k=bsearch(a,f,l,t);

    if(k==-1)
    {
    printf("\n Element is not found\n");
    }
    else
    {
    printf("\n\nElement is found at location: %d",k);
    }

getch();
}

int bsearch(int list[],int f,int l,int t)//Binary Search function implementation
{
int m;
    while(f<=l)
    {
    m=(f+l)/2;
       
        if(list[m]==t)
        {
        return m;
        }
            else if(t<list[m])
            {
            l=m-1;
            }
                else if(t>list[m])
                {
                f=m+1;
                }
    }
return(1);
}


Linear Search Implementation Using C language

#include <stdio.h>
int linearsearch(int*,int,int);

int main()
{
int array[50],search,c,n,position;
clrscr();
printf("Enter thE number of elements in array\n");
scanf("%d",&n);
printf("Enter %d numbers\n",n);

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

printf("Enter the number to search\n");
scanf("%d",&search);

position=linersearch(array,n,search);
    if(position==-1)
    {
    printf("%d is not present in array\n",search);
    }
    else
    {
    printf("%d is present at location %d\n",search,position+1);
    }
getch();
return 0;
}

int linersearch(int *pointer,int n,int find)//Implementation of linersearch

function
{
int c;
    for(c=0;c<n;c++)
    {
        if(*(pointer+c)==find)
    {
    return c;
    }
}
return -1;
}