Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C program to convert a positive number given in one base to another base

ID: 3930466 • Letter: W

Question


Write a C program to convert a positive number given in
one base to another base. For this problem,
assume that both bases are less
than or equal to 10. Consider the sample data:
number = 2010, base = 3, and new base = 4.
In this case, first convert 2010 in base 3 into the equivalent number in base
10 as follows:
(2) * (3^3) + (0 * 3^2) + (1 * 3) + (0) = 54 + 0 + 3 + 0 = 57
To c
onvert 57 to base 4, you need to find the remainders obtained by
dividing by 4, as shown in the
following:
57 % 4 = 1, quotient = 14
14 % 4 = 2, quotient = 3
3 % 4 = 3, quotient = 0.
Therefore, 57 in base 4 is 321

Explanation / Answer

#include <stdio.h>
#include <math.h>

int main()
{
    int converted_number[100];
   long int number_to_convert;
   int next_digit, base,newbase, number10=0,rem=0,count=-1;

   /* get the number */
   printf("Enter number to convert :");
   scanf("%ld", &number_to_convert);

   /* get the base */
   printf("Enter base of number :");
   scanf("%d", &base);

   /* get the new base */
   printf("Enter new base of number :");
   scanf("%d", &newbase);

   //convert number frm provided base to base 10
int tmp = number_to_convert;
//fetch each digit of number by dividing it with base
   while (tmp != 0)
   {
      count++;
      //fetch each digit
      rem = tmp % 10;
      //multiply each digit with the equivalent base
      number10+=rem * pow(base,count);
      tmp = tmp / 10;
   }

   //convert base 10 number into required base
   //initialize tmp variables
   tmp=number10;
   count=-1;
   //fetch each digit by dividing with new base
   while(tmp!=0)
   {
       //get count of no of digits
       count++;
       //assign remainder of number when divided by new base
       converted_number[count]=tmp%newbase;
       tmp=tmp/newbase;
   }
   //print the mnumber in new base
   printf("%d in base %d is ",number_to_convert,newbase);
   //iterate in reverse order and display the no
   for(int i=count;i>=0;i--)
   {
       printf("%d",converted_number[i]);
   }


}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote