Extracting digits of a number using C program without using modules and divide operator

Learn: How to extract digits of a number using C program without using modules and divide operator? Here, we will use a shortcut method to extract all digits of a number.

Given a number and we have to extract all digits without using loop.

The code to extract digits using modules and divide operator:

Here, we are getting the digits by moulding the number with 10 and then dividing the number by 10 to get next digit. Digits will be printed in reverse order.

void extractDigits(unsigned int num)
{
    int i,dig;
    while(num>0)
    {
        dig = num%10;
        printf("%d",dig);
        num = num/10;
    }
}

Now, here we are using another method to extract all digits which will be in correct order (not in reverse order) and even we are not using divide and modules operator.

Steps:

  1. Declare a character array.
  2. Assign number as string using sprintf() function in character array.
  3. Extract the digits now by using simple loop from 0 to string length -1.
  4. Print the each digit.

Consider the program:

#include <stdio.h>
#include <string.h>


void extractDigits(unsigned int num)
{
    int i,len;
    //char pointer declaration
    char temp[5];
    //assig number as string in char pointer
    sprintf((char*)temp,"%u",num);
    
    //extract and print each digits
    len= strlen(temp);
    for(i=0; i<len; i++)
        printf("%c",temp[i]);
    
    printf("\n");
}

//main program 
int main()
{
    unsigned int number=12345;
    //function calling
    extractDigits(number);
    return 0;
}

Output

12345



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.