Map string to alphanumeric keypad in C

If you haven't understood the title, here is an explanation:
    Input a string
    The program will tell you what buttons you need to press how many times in an alpha numeric keypad.

Example:
    input: blog
    output: 22 55 666 4

Logic?
    - Initialise a 2D array which holds values of all buttons.
    - Get the input string.
    - Loop through each elements in the array and check it with the 2D array.
    - The row index will tell you which button should be pressed.
    - The column index will tell how many times to press it.
    - In each loop concat the row index with the result string and display it !!

2D array for keypad:















The 2D initialisation:
 
    10 rows and max number of characters in a button : 4

    char keys[10][4]={ "XXXX",
                       "XXXX",
                       "abcX",
                       "defX",
                       "ghiX,
                       "jklX",
                       "mnoX",
                       "pqrs",
                       "tuvX",
                       "wxyz"
                     };

We mark the places which does not have a character with "X" (capital X)
like:
 Button 0 and 1 have no characters.
 Button 2,3,4,5,6,8 have only 3 characters and hence last character is an X.

The code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include<string.h>

void main()
{
    char str[20],result[100]="";
    int i, j,k,l,count,isFound;
 char keys[10][4] = {"XXXX","XXXX","abcX","defX","ghiX","jklX","mnoX","pqrs","tuvX","wxyz"};

 printf("Enter number of elements max(10):\t");
 scanf("%d",&count);
 
    printf("\nEnter the string max(%d): \t",count);
    scanf("%s", str);
 strlwr(str);
 isFound = 0;
 
 for(i=0;i<count;i++) //loop through elements in array
 {
  for(j=2;j<10;j++) //loop through all buttons
  {
   for(k=0;k<4;k++) //loop through all char in the buttons
   {
    if (str[i] == keys[j][k])
    {
     isFound=1;
     for(l = 0;l<=k;l++) //loop the number of times the button should be pressed
     {
      sprintf(result,"%s%d",result,j);
     }
     
     sprintf(result,"%s%c",result,' ');
    }
    else
    {
     isFound=0;
    }
   }
   if(isFound == 1)
   {
    break;
   } 
  }
 }
    printf("\nButtons to be pressed: %s", result);
    getch();
}

Comments

Popular posts from this blog

Pure CSS responsive Navbar

Pure CSS Collpasible Accordion