Sunday, July 12, 2009

Wanna to find a mistake in c program?

#include%26lt;stdio.h%26gt;


void main()


{


char s[15],a;


printf("\nEnter the string\t");


gets(s);


printf("\nEnter the character to be deleted\t");


scanf("%c",%26amp;a);


del(s,a);


}











void del(char t[15],char y)


{


int i;


char *p,*w;


p=t;


w=%26amp;y;


printf("\ncorrected string :");


for(i=0;i%26lt;15;i++)


{


if(p==w)


continue;


else


printf("%c",*p);





p++;


}


}

Wanna to find a mistake in c program?
The problem is that you are comparing **pointers**, not characters in your "del" function. You also did not need the two pointer variables in there. Getting rid of these two variables cleans the code up.





One additional point, the use of "continue" is often frowned upon in the manner in which you have used it (sorry, not trying to be mean here). Check out how it is implemented below and you will likely agree that it is clearer.





void del(char t[15],char y)


{


int i;


printf("\ncorrected string :");


for(i=0;i%26lt;15;i++)


{


if(t[i] != y)


printf("%c",*p);


}


}
Reply:void deal(char str[15],char d)


{


char *p;


for(p=str;*p!='\0';p++)


{


if(*p!=d)


printf("%c",*p);


}


}
Reply:#include %26lt;stdio.h%26gt;





void del(char txt[15], char chr)


{


   int i = -1;


   printf("Corrected string:");


   while(++i %26lt; 15 %26amp;%26amp; txt[i] != '\0')


   {


      if(txt[i] != chr)


      {


         printf("%c", txt[i]);


      }


   }


}








int main(int argc, const char* argv[])


{


   char s[15], a;


   printf("Enter the string: ");


   gets(s);


   printf("Enter the character to be deleted: ");


   scanf("%c", %26amp;a);


   del(s, a);





   return 0;


}


No comments:

Post a Comment