C Programming: Print individual characters of string in reverse order
Write a program in C to print individual characters of a string in reverse order.
Sample Solution:
C Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char str[100]; /* Declares a string of size 100 */
int l, i; // Declare variables for string length and loop iteration
printf("\n\nPrint individual characters of string in reverse order :\n"); // Display information about the task
printf("------------------------------------------------------\n");
printf("Input the string : ");
// Read a string from the standard input (keyboard) using fgets()
fgets(str, sizeof str, stdin);
l = strlen(str); // Calculate the length of the string
printf("The characters of the string in reverse are : \n");
// Loop to print each individual character of the string in reverse order
for (i = l - 1; i >= 0; i--) {
printf("%c ", str[i]); // Print each character in reverse order
}
printf("\n");
return 0; // Return 0 to indicate successful execution of the program
}
The program can also be written as below:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str[100]; /* Declares a string of size 100 */
int l=0;
printf("\n\nPrint individual characters of string in reverse order :\n");
printf("------------------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
l=strlen(str);
printf("The characters of the string in reverse are : \n");
for(str[l]='\0';l>=0;l--)
{
printf("%c ", str[l]);
}
printf("\n");
return 0; // Return 0 to indicate successful execution of the program
}
Sample Output:
Print individual characters of string in reverse order : ----------------------------------------------------------- Input the string : w3resource.com The characters of the string in reverse are : m o c . e c r u o s e r 3 w
Flowchart :
C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to separate the individual characters from a string.
Next: Write a program in C to count the total number of words in a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics