#include<stdio.h>
void input(char ar[]);
int lenght(char ar[]);
void disp(char ar[]);
void strrev(char ar[]);
void main()
{ int n1,n2;
char str1[20],str2[20];
input(str1);
input(str1);
n1=lenght(str1);
n2=lenght(str2);
if(n1%2==0)
{
disprev(str1);
}
else
disp(str1);
if(n2%2==0)
{
disprev(str2);
}
else
disp(str2);
}
void input(char ar[20])
{
int i=0;
for(i=0;ar[i]!=’\0’;i++)
{
scanf("%c",&ar[i]);
}
}
void disp(char ar[20])
{
int i=0;
for(i=0;ar[i]=’\0’;i++)
{
printf("%c",ar[i]);
}
}
int lenght(char ar[20])
{ int i;
while(ar[i]!=’\0’)
{
i++;
}
return i;
}
void disprev(char ar[20])
{
int n;
n=lenght(ar);//possible error
int i;
for(i=n;ar[i]!=’\0’;i–)
{
printf("%c",ar[i]);
}
}
It seems you are new to coding. Enjoy Coding…!!
First of all your string is not read in this program because the way you are trying to read a string is wrong. You can use scanf("%s",&str1); to read a string from stdin. Coming to the problem part, the problem with the logic is in disprev function you are running the loop from i=n whereas the string will end at n-1 and at index n it contains null character (i.e \0), thus it will not print anything.
You can use this code corrected code:-
#include<stdio.h>
#include<string.h> //to import string functions
/*This function (i.e. void check(char s[]) )
checks the length of string and if it is
even it is printed in reverse or else printed
as it is */
void check(char s[])
{
int i;
if(strlen(s)%2==0) //strlen(s) returns the length of the string
{
for(i=strlen(s)-1;i>=0;i--) //prints the string in reverse
printf("%c",s[i]);
}
else
printf("%s",s); //prints the string as it is
printf("\n");
return;
}
int main(void) {
char s1[100],s2[100];
scanf("%s",&s1); //reads string1
scanf("%s",&s2); //reads string2
check(s1); //checks string1
check(s2); //checks string2
return 0;
}