Convert decimal to octal using One Dimensional Array in C


This program is written in C programming language and it does the following:

  • It first includes two libraries, stdio.h and math.h.
  • It defines a function called decimalToOctal which takes an integer input decimalnum as an argument.
  • Inside the function, it declares three variables, octalnum, temp, and initializes octalnum to 0 and temp to 1.
  • It uses a while loop to iterate until the value of decimalnum is not equal to 0.
  • Inside the while loop, it uses arithmetic operations to convert the decimal number to octal number by using the logic of repeated division by 8 and taking remainder each time, and adding it to the variable octalnum.
  • It also updates the temp variable by multiplying it with 10 each time.
  • The function then returns the octal number.
  • In the main function, it declares a variable decimalnum and prompts the user to enter a decimal number.
  • It then calls the decimalToOctal function passing the entered decimal number as an argument.
  • Finally, it prints the equivalent octal number returned by the function and returns 0 as the value of the main function.

Source Code

#include <stdio.h>
#include <math.h>
/* This function converts the decimal number "decimalnum"
 * to the equivalent octal number
 */
int decimalToOctal(int decimalnum)
{
   int octalnum = 0, temp = 1;
   while (decimalnum != 0)
   {
   	 octalnum = octalnum + (decimalnum % 8) * temp;
   	 decimalnum = decimalnum / 8;
     temp = temp * 10;
   }
   return octalnum;
}
int main()
{
  int decimalnum;
  printf("Enter a Decimal Number: ");
  scanf("%d", &decimalnum);
  printf("Equivalent Octal Number: %d", decimalToOctal(decimalnum));
  return 0;
}
To download raw file Click Here

Output

Enter a Decimal Number: 436
Equivalent Octal Number: 664

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C