Amazon Prime




 
Tagged
  • Flow Chart
  •  

    Extract Digits of a Number

    Problem Statement

    1Problem Description :
    2Given a number, print all digits present in the number
    3
    4Example 1 :
    5 Input : n = 153
    6 Output : 1, 5, 3
    7 Explanation : 1, 5 and 3 are digits present in number 153
    8
    9Example 2 :
    10 Input : n = 121
    11 Output : 1, 2, 1
    12 Explanation : 1, 2 and 1 are digits present in number 121.

    Procedure

    To understand the logic, lets consider given number as 153. For given number, we can easily find out the digit present at units place by dividing the number by 10.

    Step 1: number = 153

    Step 2: when we divide the number by 10, we get remainder as 3 which is the digit at 1’s place and 15 is the quotient after dividing the number by 10.

    Step 3: Now we need to get remaining digits other than 3, so we can update number as number/10 (i.e., quotient which we got in step2) and we again divide the number by 10 which will give remainder as 5 and quotient as 1.

    Step 4: Now we consider the number as 1 and again we divide the number by 10, we get remainder as 1 and quotient as 0. i.e., so the procedure gets stopped here and we have extracted all digits of the given number.

    Extracting Digits of a Number Process - Flowchart

    Algorithm

    1Input : An Integer n
    2Step 1: Start
    3Step 2: Read number n
    4Step 3: If number not equal to 0 Go to Step 4 , else Go to Step 8
    5Step 4: digit = number % 10
    6Step 5: number = number / 10
    7Step 6: print digit
    8Step 7: Repeat Step 3
    9Step 8: Stop
    10Output: All digits of the given number should be printed

    Flowchart

    Extracting Digits of a Number - Flowchart

    Code Implementation

    1. Java
    2. C

    1import java.util.Scanner;
    2
    3public class ExtractDigitsOfANumber {
    4
    5 public static void main(String[] args) {
    6 Scanner sc = new Scanner(System.in);
    7
    8 System.out.print("Enter number : ");
    9 int number = sc.nextInt();
    10
    11 while(number != 0){
    12 int digit = number % 10;
    13 number = number /10;
    14 System.out.printf("%d ", digit);
    15 }
    16 System.out.println();
    17 }
    18}

    Output 1 :

    1Enter Number : 635
    2Digits are : 5, 3, 6
     

    Output 2 :

    1Enter Number : 121
    2Digits are : 1, 2, 1
     

  • Flow Chart
  •  
    ...