• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 596
  • Last Modified:

Palindrome without Library functions

Hi I am new to programming and need to write a palindrome without using a main() or global variables, as well as no library functions.  I have to have a ToUpper function that acts like the standard library function toupper (first checking that the given character is a lower case alphabetical character before performing a transformation). Then I need to write a string named ToUpperStr which converts all alphabetical characters of a given string to uppercase. (The function expects the original string and the resulting conversion overwrites the original string.  The function returns a pointer of the resulting string). Next  I must write a function named ReverseStr which reverses the string front to back. (The function expects the original string and the address to place the resulting string in that order.  The function returns a pointer of the resulting string.  Assume that the two blocks of memory don't over lap). Next I have to write a function named "CleanStr" which removes all characters which are not alphanumeric.  The function expects the following parameters in the folowing order: original string, address to place the resulting string, address to place the length of the resulting string. (The function returns a pointer of the resulting string.  Again assume no two blocks overlap).  Next I must write a function named IsPalindrome which returns 1 if the given string is a palindrome and 0 if returns false.  This function expects the string to be checked.  This function must make use of the other functions specified.  Also the function should assume that the maximum length of a given string is the #define'd const STRMAXLEN.  This const should be defined in my header file as 80.  Someother basic rules for this program are that the original string givin in any function should remain unchanged unless specifically stated in the requirments.  Keyword const should be used appropriatly in all functions.  Thank you very much to whom ever can help me.  
0
freakf_1999
Asked:
freakf_1999
  • 4
  • 3
  • 2
  • +4
4 Solutions
 
Jaime OlivaresSoftware ArchitectCommented:
So, what is the specific question? If you don't have no idea, you have to read some basic C Language book before doing your homework, then post your advanced code to review and help you.
0
 
freakf_1999Author Commented:
well my basic question is how do i do this.  throughout the entire year we having been going over C and using library functions and such and until now i have understood most of it.  but this recent assignment is a drastic change to what i am use to what i am asking for is helping in wirting these functions and getting them to do what they are suppose to do.  
0
 
Jaime OlivaresSoftware ArchitectCommented:
Well, it is forbidden to make a homework for you, so usual procedure is to expect the author to send some code to work on.
A typical operation on a C string is almost always something like this:

char buffer[STRMAXLEN];
int i;

for (i=0; buffer[i]=='\0'; i++) {     /* Loop until a null character is reached, not up to STRMAXLEN
     /* some operation on buffer[i]  */
}

But this could be abreviated as:

for (i=0; buffer[i]; i++) {
     /* some operation on buffer[i]  */
}

So, many operations you will do will need you to scan string, this is a template. Some other functions will need you to scan just up to middle of string, so I guess you have to make your own strlen() function to invoke first.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
freakf_1999Author Commented:
Ok, I am sorry as soon as i am done with some of my code i will post it.
0
 
freakf_1999Author Commented:
When I read the general instructions I managed (along with the help of a friend) to come up with this:

int palindrome(char *string)
{
    char *beg;
    char *end;
 
    beg = string;
    end = string + strlen(string) - 1;
 
    for (;;)
    {
        while ((beg < end) && (*beg == ' '))
            beg++;
        while ((beg < end) && (*end == ' '))
            end--;
        if (beg <= end)
            return(1);      
        if (*beg != *end)
            return(0);      
    }
}

my question now is how do I incorpoarate the rest of the functions, and how should i make the functions.  I am very new to programming so try not to get too technical.
0
 
Jaime OlivaresSoftware ArchitectCommented:
Well it is really a strange implementation. Let's start again, it is a matter of simple logic.
A palindrome application could be something like:

main()
{
     char buffer1[80];
     char buffer2[80];

     printf("Enter a word or phrase: ");
     gets(buffer1, 80);
     
     printf("String entered %s a palindrome\n\r", IsPalindrome ? "is" : "is not");
}

int IsPalindrome(char *buf)
{
       char buffer1[80];
       char buffer2[80];

     strcpy(buffer1, buf);
     ToUpperStr(buffer1);  /* convert all to upper case */
     CleanStr(buffer); /* remove undesired characters */

     strcpy(buffer2, buffer1); /* make a copy */
     ReverseStr(buffer2);   /* reverse cleaned buffer1 copy */

     if (!strcmp(buffer1, buffer2))
           return 1;
     else
           return 0;  
}

BUT THIS IS NOT YOUR HOMEWORK, YOU HAVE TO IMPLEMENT AT LEAST:
ToUpper
CleanStr
ReverseStr

AND POSIBLY TOO, AN CLONE OF:
strcpy
strcmp

Most of these functions will need the template I've posted you earlier.
0
 
manav_mathurCommented:
>Hi I am new to programming and need to write a palindrome without using a main()

And how are you planning to do this?? The standard entry point for a C program is main().

Manav
0
 
prakashagrCommented:
Hi  jaime_olivares

he is describing that the  code should not contain main() and global variables and library functions,
library functions we can implement instead of global variables we can use pointers, but without main how is it possible

prakash
0
 
WoodsterCommented:
For the toupper function you will probably want to write 2 functions.  One that will return that converted character and one that will call the first function for each character within a string.  If you called these 2 functions MyToUpper and MyToUpperStr (for example) they could be something like this.

char MyToUpper(char charToConvert)
{
  char resultChar;

  // Test the ASCII code of charToConvert.

  // If char is a character then assign the upper case equivalent of charToConvert to resultChar.

  return resultChar;
}

char *MyToUpperStr(char*stringToConvert)
{
  char *resultString;

  // Allocate enough memory for resultString to store the contents of stringToConvert

  // Loop here to loop through all characters within stringToConvert.

    // Call MyToUpper for each individual character and assign the returned value to the next character in resultString.

  return resultString;
}

If you need to write your own strcmp function to compare 2 strings as mentioned above, once you have coded the above it should be relatively simple by using the basics of what you have got in MyToUpperStr.  You would need to pass in an additional char * parameter as the string you are comparing to and then loop through each character in the first string and compare it to the corresponding character in the 2nd string.  If all characters match and the 2nd string does not have any additional characters in it then the strings are the same.

A ReverseString function (again as mentioned above) will again be similar to the MyToUpperStr function but instead of converting characters to uppercase, your loop would startat the end of the string and copy characters from one string to the other.

Just remember that the character from terminating a string is '\0'
0
 
manav_mathurCommented:
prakashagr,

sorry for going off topic. But main() is the standard entry point that the C compiler understands.
A program has to have main().

Why does the initial author give such a request. and this looks like a homework question, and I belive enuf has been clarified for the author to come up with a first-cut code.

Manav
0
 
grg99Commented:
Sounds like you need some hints about upper and ower case conversion.

You can do it two ways:

(1)  Build a table that maps case:

    char   UpToLow[ 256 ];  
   
    for(...)  UpToLow[c] = c;   // initialize all chars to themselves

    UpToLow[ 'A'] = 'a';    // and so on for 25 more letters.

Then converting upper to lower case is easy:    Out = UpToLow[ In ]

(2)  Or you can make use of some helpful coincidences:
      the letters 'A' to 'Z' are contiguous in numerical order, as are 'a' to 'z'.
      If you subtract 'A' from an upper case letter, you get the index of the letter (zero-based)
      If you add 'a' to a index (zero-based), you get a lower case letter.

Hope this helps.

0
 
freakf_1999Author Commented:
Hey everyone thanks for all the help.  About the main() I am not suppose to use one because when my professor checks it he runs it through his program which has the main() in it thats why i cant use it.  well here is what i got so far:

#include "mknapp.h"
int ToUpper(int ch)
{
      if (ch > 96 && ch < 123)
            ch -= 32;
      return ch;
}
char * ToUpperStr(char str[])
{
      char *p = str;
      for (;*p != '\0'; p++)
      {
            *p = (char) ToUpper(*p);
      }
      return str;
}
char * ReverseStr(char str[],char *q)
{
      char *p = str;
      char *o;
      o = q;
      while (*p != '\0')
      {
            p++;
      }
      p--;
      for (;p >= str;p--)
      {
            *q = *p;
            q++;
      }
      *q = '\0';
      return o;
}
int IsPalindrome(char inputstr[])
{
      char str1[STRMAXLEN];
      char str2[STRMAXLEN];
      char *p;
      char *q;
      int len = 0;
      int *l = &len;
      int r = 1;
      p = str1;
      q = str2;
      p = CleanStr(inputstr, p,l);
      p = ToUpperStr(str1);
      q = CleanStr(inputstr, q,l);
      q = ToUpperStr(str2);
      q = ReverseStr(str2,q);
      for (;*p != '\0';p++)
      {
            if (*q != *p)
            {
                  r = 0;
            }
      q++;
      }
      return r;
}
0
 
WoodsterCommented:
I would make your string parameters char * rather than char [].

While not being the most elegant way of doing it, As long as your CleanStr function is correct then the code you have should achieve the desired result.

If you have not yet written the CleanStr function, that will just be a matter of looping through each character in a string and  if it is a valid character, write it in a second string which will containg the result (cleaned string).


0
 
PaulCaswellCommented:
Just a few little suggestions:

In:

     if (ch > 96 && ch < 123)
          ch -= 32;

This isnt terribly clear or portable. Try:

     if (ch >= 'a' && ch <= 'z')
          ch += 'A' - 'a';


In:

     for (;p >= str;p--)
     {
          *q = *p;
          q++;
     }

it might be neater to use:

     for (;p >= str;p--, q++) *q = *p;

In:

     for (;*p != '\0';p++)
     {
          if (*q != *p)
          {
               r = 0;
          }
     q++;
     }
 
it might be neater to use:

     for (;*p != '\0' && r == 1;p++, q++) r = *p == *q;

 
Also, put some comments in:

     char str1[STRMAXLEN]; // Temp storage for main string.
     char str2[STRMAXLEN]; // Temp storage for reversed version.
     char *p; // A pointer.
     char *q; // Another pointer.
     int len = 0; // Length is zero to begin with.
     int *l = &len; // A pointer to the length.
     int r = 1; // Result.
     p = str1; // p points into str1
     q = str2; // q points into str2
     p = CleanStr(inputstr, p,l); // Take a clean copy of the input into str1 (p)
     p = ToUpperStr(str1); // Convert it to uppercase.
     q = CleanStr(inputstr, q,l); // Another clean copy into str2.
     q = ToUpperStr(str2); // In uppercase again.
     q = ReverseStr(str2,q); // Reversed.
     // Are they the same?
     for (;*p != '\0' && r == 1;p++, q++) r = *p == *q;

Also, using p, q and l are just misleading. It would be much clearer to use something like:

     char str1[STRMAXLEN]; // Temp storage.
     char str2[STRMAXLEN]; // More temp storage.
     int len = 0; // Length is zero to begin with.
     int r = 1; // Result.
     CleanStr(inputstr, str1,&l); // Take a clean copy of the input into str1
     ToUpperStr(str1); // Convert it to uppercase.
     CleanStr(inputstr, str2,&l); // Another clean copy into str2.
     ToUpperStr(str2); // In uppercase again.
     ReverseStr(str2,str2); // Reversed.

This then highlights a potential problem which was hidden by the excessive use of temporary variables. Can ReverseStr work when both source and destination are the same? Lets avoid the problem with the even more efficient:

     CleanStr(inputstr, str1,&l); // Take a clean copy of the input into str1
     ToUpperStr(str1); // Convert it to uppercase.
     ReverseStr(str1,str2); // Take a reversed copy into str2.

Generally, however, this is good code. You seem to have pointers pretty clear which is one of the more difficult parts of C. The loop tricks I've used just come with time and experience. Two main hints overall: use more comments; use less variables.

Good luck.

Paul
0
 
PaulCaswellCommented:
And finally:

Chosing good names for your variables is good practice. Something like:

    char forward[STRMAXLEN]; // Temp storage for forward version.
     char reverse[STRMAXLEN]; // Temp storage for reversed version.
     int length = 0; // Length is zero to begin with.
     int result = 1; // Result.
     CleanStr(inputstr, forward,&length); // Take a clean copy of the input.
     ToUpperStr(forward); // Convert it to uppercase.
     ReverseStr(forward,reverse); // Take a reversed copy.

As a challenge exercise, how could you change your algorithm to use even less variables, e.g. dont have a 'reverse'.

Paul
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
  • 2
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now