- #1
toforfiltum
- 341
- 4
Homework Statement
On a phone keypad, many of the numbers have letters associated with them. For instance, the letters A, B, and C are associated with the number 2. Write a program that accepts a number as input and prints all of the possible letter combinations associated with that number. For example, if the input is n=23, the possible letter combinations are AD, AE, AF, BD, BE, BF, CD, CE, and CF.
Homework Equations
The Attempt at a Solution
I know that between using loops and recursion, a simpler solution with loops exists. However, I can't seem to figure that out yet. So I started with recursion. And sadly, my attempt at it also isn't successful, haha. So here is my program:
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void recurse( char str[], char caller, char *array[] );
int main ()
{
char *array[8] = { "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" };
char str[100] = {NULL};
int temp;
char *ptr = NULL;
char* shortened_str = str + 1;
printf("Input number: ");
scanf("%s", str);
temp = str[0];
printf("%c\n", temp);
temp = str[0] - '0';
printf("%d\n", temp);
ptr = array[temp-2];
while ( ptr != NULL )
{
recurse ( shortened_str, *ptr, array );
ptr += 1;
}
return 1;
}
void recurse ( char str[], char caller, char *array[] )
{
char *ptr = NULL;
if ( strlen(str) == 1 )
{
int temp = 0;
temp = str[0] - '0';
ptr = array[temp-2];
while ( ptr != NULL )
{
printf("%c", caller);
printf("%c\n", *ptr);
ptr++;
}
return;
}
else if ( !strlen(str))
{
printf("%c\n", caller);
return;
}
else
{
recurse ( ++str, caller, array );
}
}
Problem is that my code seems to run infinitely, and I don't understand why. The reasoning behind my recursion is that I establish the base case to be when there is just one number left in the string. Hence, I joined the 'caller' that is from a previous number earlier on in the string with each individual letter associated with that last number in the string and terminate the function there. I don't know if the logic is sound; I haven't managed to get that far. Can anyone help me out on why my code seems to be running infinitely? I can't seem to figure out why. I had base cases that terminate. Could it be the pointers? I'm rather confused right now.