Powered By Blogger

Friday, April 27, 2012

Program : 13


PROGRAM - 13

a) 2’s compliment of a number is obtained by scanning it from right to left and the complementing all the bits after is 00100. Write a program to find the 2’s complement of a given binary number using functions.

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20];
int i,n,k;
clrscr();
puts("enter the string\n");
gets(str1);
n=strlen(str1);
for(i=n-1;i>=0;i--)
{
if(str1[i]=='1')
{
k=1;
break;
}
}
if(k==1)
{
for(i=i-1;i>=0;i--)
{
if(str1[i]=='1')
str1[i]='0';
else
str1[i]='1';
}
}
printf ("2's complement is:   ");
puts(str1);
getch();
}

 
b) Write a program to convert a roman number 
  in to its decimal equivalent using functions.

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char r[10];

void roman(char []);
clrscr();
printf("enter roman no.:");
scanf("%s",&r);
roman(r);
getch();
}

void roman(char rom[])
{
int i,k,len,a[20],count=0;
len=strlen(rom);
for(i=len-1;i>=0;i--)
{
  if(rom[i]=='I')
   {
     count++;
   }

  if((rom[i-1]=='I')&&(rom[len-1]>rom[i-1]))
   {
    count++;
   }
 }
 if(count>=4)
 {
   printf("invalild");
   getch();
   exit();
  }
else
{
for(i=0;i<len;i++)
{
if(rom[i]=='I')
a[i]=1;
else if(rom[i]=='V')
a[i]=5;
else if(rom[i]=='X')
a[i]=10;
else if(rom[i]=='L')
a[i]=50;
else if(rom[i]=='C')
a[i]=100;
else if(rom[i]=='D')
a[i]=500;
else if(rom[i]=='M')
a[i]=1000;
}
k=a[len-1];
for(i=len-1;i>0;i--)
{
if(a[i]>a[i-1])
k=k-a[i-1];
else if(a[i]==a[i-1]||a[i]<a[i-1])
k=k+a[i-1];
}
}
printf("decimal is:");
printf("%d",k);
}

No comments:

Post a Comment