Wednesday, January 5, 2011

Reverse the string in C programming without using temp variable

Coding:

#include<stdio.h>
#include<conio.h>
void main()
{
char s[100];
int i,j;
clrscr();
printf("\nEnter the string : ");
gets(s);
i=0;
j=strlen(s)-1;
while(i < j) 


s[i]=s[i]+s[j];
s[j]=s[i]-s[j];
s[i]=s[i]-s[j--];
i++;

// using built-in function: 
//n=strrev(s);
printf("\nReverse string is : %s",s);
getch();
}


Output:






Reverse the string in C programming with temp variable

Coding:
 
#include<stdio.h>
#include<conio.h>
void main()
{
char s[100],temp;
int i,j;
clrscr();
printf("\n Enter the string :");
gets(s);
i=0;
j=strlen(s)-1;
while(i < j)

{
temp=s[i]; 
s[i]=s[j];
s[j--]=temp;
i++;
}
// using built-in function:
//n=strrev(s); 
printf("\nReverse string is : %s",s);
getch();
}

Output:

 

Program for reversing the string and Palindrome in C Programming

Coding: 
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50],a[50];
int i,len,j,n;
clrscr();
printf( "\n\nEnter the string to be reversed : " );
gets(str);


//copy one string to another without using the inbuilt function:
for(i=0;str[i]!='\0';i++)
a[i] = str[i];
a[i]='\0';


//using built-in function
//strcpy(a,str);


printf( "\nInput String : %s\n",str);
len=strlen(str)-1;
for(i=0;i < len;i++) 

{
str[i]=str[i]+str[len];
str[len]=str[i]-str[len];
str[i]=str[i]-str[len--];
}
j=strlen(str);
printf( "\nReversed String : %s\n",str); 
printf("\nLength of the string is %d\n",j);
//string compare using without built-in function: 
for(i=0;str[i]!='\0' &&a[i]!='\0';i++) 
if(str[i]!=a[i])
n=1;
//n=strcmp(str,a);------>>>Built-in function
// if you r using built function,change if condition as n==0
if(n!=1)
{
printf("\nThe Given String(or)Number is Palindrome");
}
else
{
printf("\nThe Given String(or)Number is not a Palindrome");
}
getch();
}



Output: