Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
C Program to count the number of zeros from 0 to N
Next article icon

Program to print the given digit in words

Last Updated : 28 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number N, the task is to convert every digit of the number into words.

Examples: 

Input: N = 1234 
Output: One Two Three Four 
Explanation: 
Every digit of the given number has been converted into its corresponding word.

Input: N = 567 
Output: Five Six Seven 

Approach: The idea is to traverse through every digit of the number and use switch-case. Since there are only ten possible values for digits, ten cases can be defined inside a switch block. For each digit, its corresponding case block will be executed and that digit will get printed in words.

Below is the implementation of the above approach: 

CPP




// C++ implementation of the above approach
 
#include "bits/stdc++.h"
using namespace std;
 
// Function to return the word
// of the corresponding digit
void printValue(char digit)
{
 
    // Switch block to check for each digit c
    switch (digit) {
 
    // For digit 0
    case '0':
        cout << "Zero ";
        break;
 
    // For digit 1
    case '1':
        cout << "One ";
        break;
 
    // For digit 2
    case '2':
        cout << "Two ";
        break;
 
    // For digit 3
    case '3':
        cout << "Three ";
        break;
 
    // For digit 4
    case '4':
        cout << "Four ";
        break;
 
    // For digit 5
    case '5':
        cout << "Five ";
        break;
 
    // For digit 6
    case '6':
        cout << "Six ";
        break;
 
    // For digit 7
    case '7':
        cout << "Seven ";
        break;
 
    // For digit 8
    case '8':
        cout << "Eight ";
        break;
 
    // For digit 9
    case '9':
        cout << "Nine ";
        break;
    }
}
 
// Function to iterate through every
// digit in the given number
void printWord(string N)
{
    int i, length = N.length();
 
    // Finding each digit of the number
    for (i = 0; i < length; i++) {
 
        // Print the digit in words
        printValue(N[i]);
    }
}
 
// Driver code
int main()
{
    string N = "123";
    printWord(N);
    return 0;
}
 
 

Java




// Java implementation of the above approach
class GFG
{
 
// Function to return the word
// of the corresponding digit
static void printValue(char digit)
{
 
    // Switch block to check for each digit c
    switch (digit)
    {
 
    // For digit 0
    case '0':
        System.out.print("Zero ");
        break;
 
    // For digit 1
    case '1':
        System.out.print("One ");
        break;
 
    // For digit 2
    case '2':
        System.out.print("Two ");
        break;
 
    // For digit 3
    case '3':
        System.out.print("Three ");
        break;
 
    // For digit 4
    case '4':
        System.out.print("Four ");
        break;
 
    // For digit 5
    case '5':
        System.out.print("Five ");
        break;
 
    // For digit 6
    case '6':
        System.out.print("Six ");
        break;
 
    // For digit 7
    case '7':
        System.out.print("Seven ");
        break;
 
    // For digit 8
    case '8':
        System.out.print("Eight ");
        break;
 
    // For digit 9
    case '9':
        System.out.print("Nine ");
        break;
    }
}
 
// Function to iterate through every
// digit in the given number
static void printWord(String N)
{
    int i, length = N.length();
 
    // Finding each digit of the number
    for (i = 0; i < length; i++)
    {
 
        // Print the digit in words
        printValue(N.charAt(i));
    }
}
 
// Driver code
public static void main(String[] args)
{
    String N = "123";
    printWord(N);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 implementation of the above approach
 
# Function to return the word
# of the corresponding digit
def printValue(digit):
 
    # Switch block to check for each digit c
 
    # For digit 0
    if digit == '0':
        print("Zero ", end = " ")
 
    # For digit 1
    elif digit == '1':
        print("One ", end = " ")
 
    # For digit 2
    elif digit == '2':
        print("Two ", end = " ")
 
    #For digit 3
    elif digit=='3':
        print("Three",end=" ")
 
    # For digit 4
    elif digit == '4':
        print("Four ", end = " ")
 
    # For digit 5
    elif digit == '5':
        print("Five ", end = " ")
 
    # For digit 6
    elif digit == '6':
        print("Six ", end = " ")
 
    # For digit 7
    elif digit == '7':
        print("Seven", end = " ")
 
    # For digit 8
    elif digit == '8':
        print("Eight", end = " ")
 
    # For digit 9
    elif digit == '9':
        print("Nine ", end = " ")
 
# Function to iterate through every
# digit in the given number
def printWord(N):
    i = 0
    length = len(N)
 
    # Finding each digit of the number
    while i < length:
         
        # Print the digit in words
        printValue(N[i])
        i += 1
 
# Driver code
N = "123"
printWord(N)
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# implementation of the above approach
using System;
 
class GFG
{
 
    // Function to return the word
    // of the corresponding digit
    static void printValue(char digit)
    {
     
        // Switch block to check for each digit c
        switch (digit)
        {
     
        // For digit 0
        case '0':
            Console.Write("Zero ");
            break;
     
        // For digit 1
        case '1':
            Console.Write("One ");
            break;
     
        // For digit 2
        case '2':
            Console.Write("Two ");
            break;
     
        // For digit 3
        case '3':
            Console.Write("Three ");
            break;
     
        // For digit 4
        case '4':
            Console.Write("Four ");
            break;
     
        // For digit 5
        case '5':
            Console.Write("Five ");
            break;
     
        // For digit 6
        case '6':
            Console.Write("Six ");
            break;
     
        // For digit 7
        case '7':
            Console.Write("Seven ");
            break;
     
        // For digit 8
        case '8':
            Console.Write("Eight ");
            break;
     
        // For digit 9
        case '9':
            Console.Write("Nine ");
            break;
        }
    }
     
    // Function to iterate through every
    // digit in the given number
    static void printWord(string N)
    {
        int i, length = N.Length;
     
        // Finding each digit of the number
        for (i = 0; i < length; i++)
        {
     
            // Print the digit in words
            printValue(N[i]);
        }
    }
     
    // Driver code
    public static void Main()
    {
        string N = "123";
        printWord(N);
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
 
      // JavaScript implementation of
      // the above approach
 
      // Function to return the word
      // of the corresponding digit
      function printValue(digit) {
        // Switch block to check for
        // each digit c
        switch (digit) {
          // For digit 0
          case "0":
            document.write("Zero ");
            break;
 
          // For digit 1
          case "1":
            document.write("One ");
            break;
 
          // For digit 2
          case "2":
            document.write("Two ");
            break;
 
          // For digit 3
          case "3":
            document.write("Three ");
            break;
 
          // For digit 4
          case "4":
            document.write("Four ");
            break;
 
          // For digit 5
          case "5":
            document.write("Five ");
            break;
 
          // For digit 6
          case "6":
            document.write("Six ");
            break;
 
          // For digit 7
          case "7":
            document.write("Seven ");
            break;
 
          // For digit 8
          case "8":
            document.write("Eight ");
            break;
 
          // For digit 9
          case "9":
            document.write("Nine ");
            break;
        }
      }
 
      // Function to iterate through every
      // digit in the given number
      function printWord(N) {
        var i,
          length = N.length;
 
        // Finding each digit of the number
        for (i = 0; i < length; i++) {
          // Print the digit in words
          printValue(N[i]);
        }
      }
 
      // Driver code
      var N = "123";
      printWord(N);
       
</script>
 
 
Output
One Two Three 

Time Complexity: O(L), Here L is the length of the string
Auxiliary Space: O(1), As constant extra space is used.

Recursive Approach

The idea is to recursively call the function till the number becomes zero by dividing it by 10 and storing the remainder in a variable. Then we print the digit from the string array as the digit will store the index of the number to be printed from the array.  

we print the number after the recursive call to maintain the order of digits in the input number, if we print before the recursive function call the digit name will be printed in reversed order. Since we are dividing n by 10 in each recursive call the recurrence relation will be  T(n) = T(n/10) + 1

Below is the implementation of the above approach: 

C++




//C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
void ToDigits(int n, string arr[])
{
 
    // base case
    if (n == 0) {
        return;
    }
 
    // storing the last digit of the number and updating
    // number
    int digit = n % 10;
    n = n / 10;
 
    // recursive call
    ToDigits(n, arr);
 
    // printing the digits form the string array storing name
    // of the given index
    cout << arr[digit] << " ";
}
 
int main()
{
 
    string arr[10]
        = { "zero", "one", "two",   "three", "four",
            "five", "six", "seven", "eight", "nine" };
    int n;
    n = 123;  //it can be changed to take user input
 
    ToDigits(n, arr);
 
    return 0;
}
//This code is contributed by rahulpatel43433
 
 

Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG {
  static void ToDigits(int n, String[] arr)
  {
 
    // base case
    if (n == 0) {
      return;
    }
 
    // storing the last digit of the number and updating
    // number
    int digit = n % 10;
    n = n / 10;
 
    // recursive call
    ToDigits(n, arr);
 
    // printing the digits form the string array storing name
    // of the given index
    System.out.print(arr[digit]);
    System.out.print(" ");
  }
 
  // Driver Code
  public static void main(String args[])
  {
    String[] arr = { "zero", "one", "two",   "three", "four",    "five", "six", "seven", "eight", "nine" };
    int n = 123;  //it can be changed to take user input
 
    ToDigits(n, arr);
  }
}
 
// This code is contributed by shinjanpatra
 
 

Python3




# Python implementation of above approach
def ToDigits(n, arr):
 
    # base case
    if (n == 0):
        return
 
    # storing the last digit of the number and updating
    # number
    digit = n % 10
    n = n // 10
 
    # recursive call
    ToDigits(n, arr)
 
    # printing the digits form the string array storing name
    # of the given index
    print(arr[digit] , end = " ")
 
 
# driver code
arr = [ "zero", "one", "two", "three", "four",
            "five", "six", "seven", "eight", "nine" ]
n = 123 #it can be changed to take user input
 
ToDigits(n, arr)
 
# This code is contributed by shinjanpatra
 
 

C#




//c# implementation of above approach
using System;
  
public class GFG {
     
    static void ToDigits(int n, String[] arr)
    {
        // base case
        if (n == 0) {
            return;
        }
         
        // storing the last digit of the number and updating
        // number
        int digit = n % 10;
        n = n / 10;
         
        // recursive call
        ToDigits(n, arr);
         
        // printing the digits form the string array storing name
        // of the given index
        Console.Write(arr[digit]+" ");
    }
      
    // Driver program to test above
    public static void Main()
    {
        String[] arr = new string[10]{ "zero", "one", "two",   "three", "four", "five",
        "six", "seven", "eight", "nine" };
         
        int n;
        n = 123;  //it can be changed to take user input
         
        ToDigits(n, arr);
    }
}
// This code is contributed by aditya942003patil
 
 

Javascript




<script>
 
// JavaScript implementation of above approach
function ToDigits(n, arr)
{
 
    // base case
    if (n == 0) {
        return;
    }
 
    // storing the last digit of the number and updating
    // number
    let digit = n % 10;
    n = Math.floor(n / 10);
 
    // recursive call
    ToDigits(n, arr);
 
    // printing the digits form the string array storing name
    // of the given index
    document.write(arr[digit] , " ");
}
 
// driver code
let arr = [ "zero", "one", "two", "three", "four",
            "five", "six", "seven", "eight", "nine" ]
let n = 123; //it can be changed to take user input
 
ToDigits(n, arr);
 
// This code is contributed by shinjanpatra
 
</script>
 
 
Output
one two three 

Time Complexity: O(log10 n)
Auxiliary Space: O(log10 n) for recursive call stack

Approach 3 : By using Python Dictionary. 

Algorithm –

  1. Create a dictionary named digits, assign key-value pairs of numbers to words respectively, as shown in code below.
  2. Iterate the string character one by one and print the value of the dictionary, key associated with it.

C++




#include <iostream>
#include <string>
#include <map>
 
using namespace std;
 
// Function to iterate through every digit in the given number
void printWord(string N) {
    map<char, string> digits {
        {'1', "One"}, {'2', "Two"}, {'3', "Three"}, {'4', "Four"},
        {'5', "Five"}, {'6', "Six"}, {'7', "Seven"}, {'8', "Eight"},
        {'9', "Nine"}, {'0', "Zero"}
    };
     
    for (char number : N) {
        cout << digits[number] << " ";
    }
}
 
// Driver code
int main() {
    string N = "123";
    printWord(N);
    return 0;
}
 
 

Java




import java.util.HashMap;
import java.util.Map;
 
public class Main {
    // Function to iterate through every digit in the given number
    public static void printWord(String N) {
        Map<Character, String> digits = new HashMap<Character, String>() {{
            put('1', "One");
            put('2', "Two");
            put('3', "Three");
            put('4', "Four");
            put('5', "Five");
            put('6', "Six");
            put('7', "Seven");
            put('8', "Eight");
            put('9', "Nine");
            put('0', "Zero");
        }};
 
        for (char number : N.toCharArray()) {
            System.out.print(digits.get(number) + " ");
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        String N = "123";
        printWord(N);
    }
}
 
 

Python3




# Python3 Code implementation using dictionary
 
# Function to iterate through every
# digit in the given number
def printWord(N):
    digits = {'1':'One','2':'Two','3':'Three','4':'Four','5':'Five','6':'Six','7':'Seven','8':'Eight','9':'Nine','0':'Zero'}
    for number in N:
        print(digits[number] , end = ' ')
       
# Driver code
N = "123"
printWord(N)
 
# This code is contributed by Pratik Gupta (guptapratik)
 
 

C#




using System;
using System.Collections.Generic;
 
class Program {
    static void Main(string[] args)
    {
        string N = "123";
        PrintWord(N);
    }
 
    // Function to iterate through every digit in the given
    // number
    static void PrintWord(string N)
    {
        // Dictionary to store the word representation of
        // each digit
        Dictionary<char, string> digits
            = new Dictionary<char, string>{
                  { '1', "One" },   { '2', "Two" },
                  { '3', "Three" }, { '4', "Four" },
                  { '5', "Five" },  { '6', "Six" },
                  { '7', "Seven" }, { '8', "Eight" },
                  { '9', "Nine" },  { '0', "Zero" }
              };
 
        // Iterate through each digit in the number and
        // print its word representation
        foreach(char number in N)
        {
            Console.Write(digits[number] + " ");
        }
    }
}
 
 

Javascript




// Function to iterate through every
// digit in the given number
function printWord(N) {
    const digits = {'1':'One','2':'Two','3':'Three','4':'Four','5':'Five','6':'Six','7':'Seven','8':'Eight','9':'Nine','0':'Zero'};
    for (let number of N) {
        console.log(digits[number] + ' ');
    }
}
 
// Driver code
const N = "123";
printWord(N);
 
 
Output
One Two Three 

Time Complexity: O(n), where n is the length of string
Auxiliary Space: O(1)

Related Article: Print individual digits as words without using if or switch



Next Article
C Program to count the number of zeros from 0 to N

A

Akshita33Patwal
Improve
Article Tags :
  • C Programs
  • DSA
  • Mathematical
  • School Programming
  • Strings
  • Technical Scripter
  • number-digits
  • Technical Scripter 2019
Practice Tags :
  • Mathematical
  • Strings

Similar Reads

  • C Program to Print all digits of a given number
    Given a number N, the task is to write a C program to print all digits of the number N in their original order. Examples: Input: N = 12 Output: 1, 2 Input: N = 1032 Output: 1, 0, 3, 2 Method 1: The simplest way to do is to extract the digits one by one and print it. Extract the last digit of the num
    3 min read
  • C program to Count the digits of a number
    Given a number N, write a C program to find the count of digits in the number N. Examples: Input: N = 12345 Output: 5 Explanation: The count of digit in 12345 = 5 Input: N = 23451452 Output: 8 Explanation: The count of digits in 23451452 = 8Methods to Count Digits of a NumberThere are a few methods
    4 min read
  • C Program To Write Your Own atoi()
    The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer. Syntax: int atoi(const char strn) Parameters: The function accepts one parameter strn which refers to
    5 min read
  • C Program For Char to Int Conversion
    Write a C program to convert the given numeric character to integer. Example: Input: '3'Output: 3Explanation: The character '3' is converted to the integer 3. Input: '9'Output: 9Explanation: The character '9' is converted to the integer 9. Different Methods to Convert the char to int in CThere are 3
    3 min read
  • C Program to count the number of zeros from 0 to N
    Given a number N, the task is to write C program to count the number of zeros from 0 to N. Examples: Input: N = 10 Output: 2 Explanation: The number with zeros are 0, 10 till 10. Hence the count of zeros is 2. Input: N = 20 Output: 3 Explanation: The number with zeros are 0, 10, 20 till 20. Hence th
    2 min read
  • C Program to Print the Length of a String Using %n Format Specifier
    In C, strings are arrays of characters terminated by a null character ('\0') and the length of a string is the number of characters before this null character. In this article, we will learn how to find the length of the string using %n format specifier. The %n is a special format specifier for prin
    1 min read
  • C Program To Remove Leading Zeros
    Here, we will build a C Program to Remove leading zeros with the following 2 approaches: Using for loopUsing strspn To remove all leading zeros from a number we have to give the input number as a string. Input: a = "0001234" Output: 12341. Using for loop C/C++ Code // C Program to Remove leading zer
    2 min read
  • C Program to Print Armstrong Numbers Between 1 to 1000
    Armstrong numbers are those numbers in which the sum of digits raised to the power of a number of digits in that number will be equal to the number itself. Here will see how to build a C Program to Display Armstrong numbers between 1 to 1000. Example: 153 13 + 53 + 33 1 + 125 + 27 = 153Approach 1:Co
    3 min read
  • Reverse Number Program in C
    The reverse of a number means reversing the order of digits of a number. In this article, we will learn how to reverse the digits of a number in C programming language. For example, if number num = 12548, the reverse of number num is 84521. Algorithm to Reverse an IntegerInput: num (1) Initialize re
    2 min read
  • C Program to Find Armstrong Numbers Between Two Integers
    Prerequisite: Program for Armstrong Numbers A positive integer of n digits is called Armstrong number of order n (order is the number of digits) if abcd… = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + …. Here, we will build a C Program to print Armstrong Numbers between two integers. Example: 153 is
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences