C program to reverse the digits of a number ? [ In 3 Steps ]

January 11, 2025 4 Comments » Hits : 546





C program to reverse the digits of a number ? [ In 3 Steps ]


Problem Statement : Reversing the digits of number without using mod (%) Operator ?

Prerequisite :

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
 int num1, num2;
 char str[10];
 clrscr();
    printf("\nEnte the Number : ");
    scanf("%d",&num1);
    sprintf(str,"%d",num1);
    strrev(str);
    num2 = atoi(str);
    printf("\nReversed Number : ");
    printf("%d\n",num2);
    getch();
}

Output :

Enter the Number : 123
Reversed Number : 321

Explain Logic :
Step 1 : Store Number in the Form of String

  • Sprintf function sends formatted output to string variable specified
  • Number will be stored in String variable “str”
sprintf(str,"%d",num1);

Step 2 : Reverse the String Using Strrev Function

  • Strrev will reverse String
  • eg “1234″ will be reversed as “4321″
strrev(str);

Step 3 : Convert String to Number

  • [A to I ] = [ Alphabet to Integer ] = atoi
  • Atoi function Converts String to Integer
num2 = atoi(str);

Incoming search terms:

  • Ricky

    // ReverseDigitsofNumber.cpp : This program takes 4 digit integer for reversing the digits of an Integer.
    //

    #include "stdafx.h"
    #include "iostream"
    #include "conio.h"

    using namespace std;

    int _tmain(int argc, _TCHAR* argv[])
    {
    int i ;
    i = 1234; //Taken 4 digits

    char a[4];
    char b[4];

    char x = 49;
    memset(a,'',4);
    memset(b,'',4);

    sprintf(a,"%d",i);

    for(int x = 0;x<4;x++)
    b[4-(x+1)] = a[x];

    i = atoi(b);

    cout<<i;

    getch();
    return 0;
    }

  • Priteh Taral

    @Ricky
    Thank you for your Valuable Contribution
    Ya its Correct , but This Code is only applicable for Microsoft VC++ Comipler .

    [Borland Version]If We want to Accept 4 digits -

    #include
    #include
    #include
    #include

    void main()
    {
    long num1, num2;
    char str[10];
    clrscr();

    printf("nEnte the Number : ");
    scanf("%ld",&num1);

    sprintf(str,"%ld",num1);

    strrev(str);

    num2 = atol(str);

    printf("nReversed Number : ");
    printf("%ldn",num2);
    getch();
    }

    /************************
    Changes :
    1.atoi to atol because atol = alphabet to long
    2.replace %d using %ld to accept long number

  • RAJ

    Thank u…………. Very much

  • World is Round

    A version which takes care of negatives:
    http://layerinside.blogspot.com/2011/01/some-programming.html