Header

Friday 6 September 2013

IGNOU BCA 2nd sem Solved Assignment - Write an algorithm, draw a corresponding flowchart and write an interactive program to convert a binary number to its octal equivalent.

Write an algorithm, draw a corresponding flowchart and write an interactive program to convert
a binary number to its octal equivalent.
Ans
Algorithm
Program

N = the number to convert
p() = array of indices for output to fill in with "1" (array indexed from 0)
k = number of entries in p

Example using N = 65:
p(0) = 6
p(1) = 0
Binary created is: 1000001
In terms of the p() this is: p(0)00000p(1)


Create the array for the binary representation:
N = number

k = 0
do while N >0
p(k) = int(log(N)/log(2))
N = N - 2^(p(k))
k = k + 1
end do

Create a string that is p(0)+1 in length and fill with "0"s

string = "00000..." of lenfth p(0) + 1

Loop through p and replace "0"s with "1"s for each index in p. The index to replace must be adjusted since the string representation needs the large values on the left and decreasing to the right whereas the method involved does it the opposite way.
n = index in string to replace = p(0) - p(i)

for i = 0 to k-1
n = p(0) - p(i)
string(n) = "1"
next i

#include<stdio.h>
int main(){
   
    long int binaryNumber,octalNumber=0,j=1,remainder;

    printf("Enter any number any binary number: ");
    scanf("%ld",&binaryNumber);

    while(binaryNumber!=0){
         remainder=binaryNumber%10;
        octalNumber=octalNumber+remainder*j;
        j=j*2;
        binaryNumber=binaryNumber/10;
    }

    printf("Equivalent octal value: %lo",octalNumber);

    return 0;
}


 C code for how to convert large binary to octal

#include<stdio.h>
#define MAX 1000

int main(){
   
    char binaryNumber[MAX],octalNumber[MAX];
    long int i=0,j=0;

    printf("Enter any number any binary number: ");
    scanf("%s",binaryNumber);

    while(binaryNumber[i]){
      binaryNumber[i] = binaryNumber[i] -48;
      ++i;
    }

    --i;
    while(i-2>=0){
    octalNumber[j++] = binaryNumber[i-2] *4 +  binaryNumber[i-1] *2 + binaryNumber[i] ;
    i=i-3;
    }

    if(i ==1)
      octalNumber[j] = binaryNumber[i-1] *2 + binaryNumber[i] ;
    else if(i==0)
      octalNumber[j] =  binaryNumber[i] ;
    else
      --j;

    printf("Equivalent octal value: ");
    while(j>=0){
      printf("%d",octalNumber[j--]);
    }

    return 0;
}

No comments:

Post a Comment