Write a C program to convert integer into octal and hexadecimal formats. Accept the integer from the user.

In this example, you will learn how to convert the integer (decimal) number into octal and hexadecimal formats.

There are two methods to solve this problem. One is, you can simply display an integer in octal and hexadecimal formats by using their format specifiers, %o for octal and %x for hexadecimal representation. Another one is, you can create your own logic to convert integer into octal and hexadecimal formats.

convert Integer into Octal and Hexadecimal formats

Tutorial πŸ“Ί

Watch the tutorial and understand how to solve this problem πŸ˜‰

Steps πŸͺœ

To Convert Integer into Octal and Hexadecimal

  1. Accept a number from the user and store it in a variable num.
  2. First, display the value entered by user and then display the octal and hexadecimal representation with the help of format specifiers. That’s it. 😎

Code πŸ’»

#include <stdio.h>
#include <conio.h>

void main()
{
  int num;
  clrscr();
  // Display a message and accept a number from the user
  printf("Please enter a number: ");
  scanf("%d", &num);
  // Display the accepted integer value
  printf("\n\nEntered value: %d", num);
  // Display in octal format
  printf("\nOctal value: %o", num); // %o for Octal
  // Display in hexadecimal format
  printf("\nHexadecimal value: %x", num); // %x for Hexadecimal
  getch();
}

Examples 😍

Let’s assume, the user enters the number: 12

Output will be:

Entered value: 12
Octal value: 14
Hexadecimal value: c

Let’s take another example where the user enters 90

Output will be:

Entered value: 90
Octal value: 132
Hexadecimal value: 5a

This is how we convert integer into octal and hexadecimal format. 😎
For more C programs, click here.

Categorized in: