Tags

May 29, 2012

How to print multi-digit numbers like a 7-segment display

During an interview , many interviewers like to ask very simple coding questions. This is usually to check how fast the interviewee can do a context switch in her mind, her ability to think about some very basic problem, etc.
So, let’s tackle a few of such coding problems in this post. I am using Java as the programming language in this example,

The idea was to help some people which started preparing for interview. I hope you find some value in it.

This is simple java program to display number in 7 segment format

Example :123 should be display in following format, and in one line.
_ _
| _| _|
| |_ _|

1 - Set up your initial data for each number. You could do this as a 2d array (dimension 1: digit, dimension 2: line)
For example:
numbers[0][0] = "|-|"
numbers[0][1] = "| |"
numbers[0][2] = "|_|"

numbers[1][0] = "  |"
numbers[1][1] = "  |"
numbers[1][2] = "  |"

2 - For each line that makes up the character, scan across each digit in your input and write the appropriate string. This will build up the characters line by line.
        public class DigitalDisplay {
            /**
             * @param args
             */
        public static void main(String[] args) {
        String [][] num=new String[4][3];
        num[0][0]="|-|";  //this will display complete "0"
        num[0][1]="| |";
        num[0][2]="|_|";

        num[1][0]=" |";
        num[1][1]=" |";
        num[1][2]=" |";

        num[2][0]=" -|";
        num[2][1]=" _|";
        num[2][2]=" |_";

        num[3][0]=" -|";
        num[3][1]=" _|";
        num[3][2]=" _|";
        int[] input = {2,1,3}; 
        for (int line = 0; line < 3; line++)
        {          
            for (int inputI=0; inputI < input.length; inputI++)
            {
                int value = input[inputI];
                System.out.print(num[value][line]);
                System.out.print("  ");
            }          
            System.out.println();
        }
    }
}

**OUTPUT**

 -|   |   -|  
 _|   |   _|  
 |_   |   _|  

No comments:

Post a Comment