Showing posts with label c programming. Show all posts
Showing posts with label c programming. Show all posts

Thursday, 25 January 2018

DECIMAL-TO-BINARY CPP PROGRAMMING

Output:
Enter Decimal Value:4

Binary value =100

Enter Decimal Value:15
Binary value =1111

Code for Decimal to Binary:

#include <iostream>
#include <cmath>
using namespace std;
 int main()
{
int a,b=0,c=1;
long bin=0;
cout<<"Enter Decimal Value:";
cin>>a;
while(a>0)
{
    b=a%2;
    a/=2;
    bin=bin+(b*c);
    c=c*10;
}
cout<<"Binary value ="<<bin;

}

BINARY-SEARCH 'C' PROGRAMMING

Output :

Enter the no.of  elements:5
Enter the 5 numbers:1 5 8 6 3
Enter number to be searched:8

Number Found

Enter the no.of  elements:5
Enter the 5 numbers:1 5 8 6 3
Enter number to be searched:9
Number Not Found

Code for Binary Search:

#include<stdio.h>
#include<stdlib.h>
int main ()
{
int *a;
int x,n,i=0,temp=0;
int mid=0,lowerb=0,upperb=0;
printf("enter the no.of  elements:");
scanf("%d",&n);
a=malloc(sizeof(int)*n);
printf("enter the %d numbers:",n);
for(i=0;i<n;i++)
{
    scanf("%d",&a[i]);
}
printf("enter number to be searched:");
scanf("%d",&x);
lowerb=0;upperb=n-1;
while(lowerb<=upperb)
{ mid=lowerb+((upperb-lowerb)/2);
    if(a[mid]==x)
    {temp++;
      printf("number found");
      break;
    }
    else if(a[mid]>x)
    {
        upperb=mid-1;
    }
    else
    {   lowerb=mid+1;

    }
}
if(temp==0)
{
    printf("number not found");
}


}

Wikipedia

Search results