Home »
Code Snippets »
C/C++ Code Snippets
[Solved] I made program to reverse a string, it runs but ads NULL at the end.
By: IncludeHelp, On 02 NOV 2016
This is a solution of a program; we published it after fix the issues; in this program we will learn how we can read a string character by character and print the string in reverse order (character by character)?
This program is asked from our regular reader Mr. SHAKTI TRIPATHI.
His question was:
I made program to reverse a string, it runs but adds '0' (string termination character) at the end. I don't want '0' to be displayed on output window.
Could It be removed in anyway?. I am sending you code below..
#include<stdio.h>
#include<conio.h>
int main(){
int ch,count=0,i;
char str[100] ;
ch=getchar();
while(ch!='\n'){
str[count]=ch;
count++;
ch=getchar();
}
i=count-1;
while(i>=0){
putchar(str[i] ); //print in reverse.
i=i-1;
}
printf("%s ",str[i] );
return 0;
}
Here is the solution of the above problem; let’s consider the following program
#include<stdio.h>
int main()
{
int ch,count=0,i;
char str[100] ;
printf("Enter string: ");
ch=getchar();
while(ch!='\n'){
str[count]=ch;
count++;
ch=getchar();
}
printf("Entered string is: ");
i=count-1;
while(i>=0){
putchar(str[i] ); //print in reverse.
i=i-1;
}
printf("\n");
return 0;
}
Output
Enter string: Hello World.
Entered string in reverse order is: .dlroW olleH
What was the problem?
- There is no need to print last character after the while loop body; so we removed printf("%s ",str[i] ); after the while loop.
- Added two print statement to understand program better.
- printf("Enter string: "); before reading characters.
- printf("Entered string is: "); before printing the string in reverse order.
- No need to include <conio.h> if there is no getch() or clrscr() function, so we removed this header file inclusion.