Hexadacimal To Octal Program In C


Finding that a given number is even or odd, is a classic C program. We shall learn the use of conditional statement if-else in C.

Algorithm

Algorithm of this program is very easy −

START
      
   Step 1 → Take integer variable A
          
   Step 2 → Assign value to the variable

   Step 3 → Perform A modulo 2 and check result if output is 0
   
   Step 4 → If true print A is even
   
   Step 5 → If false print A is odd

STOP

Flow Diagram

We can draw a flow diagram for this program as given below −

FlowDiagram Even Odd

Pseudocode

procedure even_odd()
   
   IF (number modulo 2) equals to 0
      PRINT number is even
   ELSE
      PRINT number is odd
   END IF

end procedure

Implementation

Implementation of this algorithm is given below −

#include <stdio.h>

int string_length(char s[])
{
	int i=0;

	while(s[i]!='\0')
		i++;
		
return i;	
}

void string_reverse(char s[])
{
  char *t;
	for(t=s+string_length(s)-1;s<t;++s,--t) {
		char temp=*s; *s=*t; *t=temp;
	}	
}

int getHexValue(char d)
{
	if(d>='0' && d<='9') return d-48;
	else return d-'A'+10;
}

int binary2decimal(char n[])
{
	int i,decimal,mul=0;

	for(decimal=0,i=string_length(n)-1;i>=0;--i,++mul)
		decimal+=(n[i]-48)*(1<<mul);

	return decimal;
}

int main()
{   char n[10],bits[100],temp[10];
	int i,j,k,v;
	
	printf("Enter a hexa number :");
	scanf("%s",n);

	string_reverse(n);
		
	for(j=k=0;n[j]!='\0';j++)
	{
	  v=getHexValue(n[j]);
	  
		for(i=0;i<4;i++,k++) {
			bits[k]=v%2+48;
			v/=2;
		}
	}
	bits[k]='\0';

	string_reverse(bits);

	puts(bits);
	printf("Octal equivalent is : ");
	
	for(i=j=0;i<string_length(bits)%3;++i,++j)
		temp[j]=bits[i];
		temp[j]='\0';
	
	v=binary2decimal(temp);
	if(v!=0) printf("%d",v);
	
	while(bits[i]!='\0')
	{
		for(j=0;j<3;++i,++j)
			temp[j]=bits[i];
			temp[j]='\0';
			
		v=binary2decimal(temp);
		printf("%d",v);
	}
return 0;
}


Output

Output of the program should be −

24 is even
31 is odd
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements