Monday, January 28, 2008

Solution for the program to convert the positive integer to Roman Numbers

Today one of my friend came up with the question to write a program that gets inputs from the user dynamically and converts them into the Roman Numbers.. I came up with a solution which worked pretty well in Devc++ compiler... I am posting it here.. People working with Turbo c could include #include and use the necessary clrscr() functions...


/*
* Program to find the roman equivalent
*Input shud be below 4000 and max is 3999
*If given above the range prompts an out of range error
*/
#include <>
#include <>
#include <>
main()
{
//char *a[] = {"3999","2112","123","\0"};
char *a[5];
char temp[5];
int i = 0 , b = 0 , len = 0 , q = 0, j =0 ;
int num = 0, k = 0 ;
strcpy(temp,"");
printf("enter the value of n: ");
scanf("%d",&num);
for(i = 0 ; i < num ; i++)
{
printf("\nenter the value :");
scanf("%s",temp);
a[k] = (char *)malloc(strlen(temp));
strcpy(a[k],temp);
k++;
}
i = 0 ;
//printf("k = %d",k);

while( k > 0 )
{
b = atoi(a[j]);
if(b > 3999)
{
printf("\nout of range");
j++;
k--;
continue;
}
len = strlen(a[j]);
printf("\n");
//printf("len = %d\n",len);
while(b != 0)
{
if(len == 4)
{
q = b / 1000 ;
if( q > 3)
{
printf("INVALID");
break;
}
else
{
for(i = 0 ; i < q ; i++)
printf("%c",'M');
}
b = b - (q*1000);
len = len - 1 ;
i = 0 ;
}
else if(len == 3)
{
q = b / 100 ;
if(q > 0 && q < 4)
{
for(i = 0 ; i < q ; i++)
printf("%c",'C');
}
else if(q == 4)
{
printf("%s","CD");
}
else if(q == 5)
{
printf("%c",'D');
}
else if(q >5 && q < 9)
{
printf("%c",'D');
for(i = 0 ; i < q - 5 ; i++)
printf("%c",'C');
}
else if (q == 9)
printf("%s","CM");
else
;

b = b - (q*100);
len = len - 1 ;
i = 0 ;

}
else if (len == 2)
{

q = b / 10 ;
if(q > 0 && q < 4)
{
for(i = 0 ; i < q ; i++)
printf("%c",'X');
}
else if(q == 4)
{
printf("%s","XL");
}
else if(q == 5)
{
printf("%c",'L');
}
else if(q >5 && q < 9)
{
printf("%c",'L');
for(i = 0 ; i < q - 5 ; i++)
printf("%c",'X');
}
else if (q == 9)
printf("%s","XC");
else
;

b = b - (q*10);
len = len - 1 ;
i = 0 ;
}
else
{
q = b ;
if(q > 0 && q < 4)
{
for(i = 0 ; i < q ; i++)
printf("%c",'I');
}
else if(q == 4)
{
printf("%s","IV");
}
else if(q == 5)
{
printf("%c",'V');
}
else if(q >5 && q < 9)
{
printf("%c",'V');
for(i = 0 ; i < q - 5 ; i++)
printf("%c",'I');
}
else if (q == 9)
printf("%s","IX");
else
;

b = b - (q*1);
len = len - 1 ;
i = 0 ;
}

}
k--;
j++;
}
getch();
}

3 comments:

sathish kumar said...

just include stdio.h , string.h and conio.h header files.. if using turbo c++ then include alloc.h... it's not getting added to the post...

suresh said...

onnum puriale da

sathish kumar said...

Its just a code da.. Pretty simple only...