Palindrome
Palindrome
http://codepad.org/z6DPqBXm
Link: http://codepad.org/z6DPqBXm [ raw code | output | fork ] arefin - C, pasted just now: private (make public)
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 48 49 50 51 52 53 54 55 //Syed Arefin(sra663) //Mitch Hinrichs (mfh 537) //*************** HW 6 Part 1 ******************** // The C Program that does the same thing as Exam 2A,2B. // You have to write the code for ChkPalind // You may call the routine PtrLast inside ChkPalind #include <stdio.h> unsigned char * PtrLast(unsigned char *);
const struct TestCase{ unsigned char *Buffer; // String to check; Null terminated signed char check; // +1 or -1 according as Buffer is or is not a palindrome }; typedef const struct TestCase TestCaseType; TestCaseType Tests[5]={ { "Madam\0",-1 }, { "risetovotesir\0",1 }, { "raceCar\0",-1 }, { "NeveroddoreveN\0",1 }, { "\0",1 }}; //This is the only subroutine you are expected to write. // It is not necessary that you understand the rest of the code. // What you need to know is what this subroutine is supposed to do., // that is, check if the given string is a palindrome and return a 1 if // it is OR a -1 if it is not // Input: Pointer to a null-terminated string of characters // Output: 1 or -1 depending on whether the given string is a palindrome // or not unsigned char ChkPalind(unsigned char *string){ unsigned char x,y,result=0 ; // values unsigned char n, *last ; //pointers ; if(*string==0) return(1); // special case size '0' last = PtrLast(string) ; // get pointer to last char while(last > string ){ // as long as they do not cross mid point keep checking x = (*string) ; y = (*last) ; if (x==y) result = 1; else return -1;// do not have pal. string++ ;// next char last-- ; }
1 of 3
10/31/2011 10:31 PM
http://codepad.org/z6DPqBXm
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
// This routine is given to you // It takes a pointer to a string and returns the // pointer to the last (non-null) character in the string unsigned char * PtrLast(unsigned char *string){ unsigned char *work; work = string; while(*work != '\0'){ work++;} if (work != string) { work--; // want the ptr to the last char so decrement } return(work); } int main(void){ signed char i,result; unsigned char errors=0; for (i = 0; i < 5; i++){ result = ChkPalind(Tests[i].Buffer); if (result != Tests[i].check){ errors++; printf("Error Case: i=%d, String= %s, result=%d\n",i, Tests[i].Buffer, result); } } if (errors==0){ printf("Program works\n"); } else { printf("Does not work\n"); } return 0; }
Output:
1 Program works
2 of 3
10/31/2011 10:31 PM
http://codepad.org/z6DPqBXm
Private [?]
Run code
Comments:
3 of 3
10/31/2011 10:31 PM