Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a C program to print the message in reverse order using for loop in strings
Here we write a program to reverse the sentence without predefined functions. By using for loop, we can easily print statement in reverse order.
Syntax
for(initialization; condition; increment/decrement) {
// Read characters
}
for(reverse_initialization; reverse_condition; reverse_increment) {
// Print characters in reverse
}
Method 1: Character-by-Character Input Using getchar()
This approach reads each character individually using getchar() and stores them in an array. Then it prints the characters in reverse order −
#include <stdio.h>
int main() {
char stmt[100];
int i;
printf("Enter the message:
");
for(i = 0; i < 99; i++) {
stmt[i] = getchar(); /* reading each char from console till enter or newline char is pressed */
if(stmt[i] == '
')
break;
}
printf("The reverse statement is:
");
for(i--; i >= 0; i--) /* printing each char in reverse order */
putchar(stmt[i]);
putchar('
');
return 0;
}
Enter the message: Hi welcome to my world The reverse statement is: dlrow ym ot emoclew iH
Method 2: Using fgets() for Safe Input
Here, we use fgets() instead of getchar() for safer string input handling −
#include <stdio.h>
#include <string.h>
int main() {
char string[100];
int length, i;
printf("Enter string to be reversed: ");
fgets(string, sizeof(string), stdin);
length = strlen(string);
/* Remove newline character if present */
if(string[length - 1] == '
') {
string[length - 1] = '\0';
length--;
}
printf("The reversed string is: ");
for(i = length - 1; i >= 0; i--) {
putchar(string[i]);
}
putchar('
');
return 0;
}
Enter string to be reversed: Hi welcome to tutorials Point The reversed string is: tnioP slairotut ot emoclew iH
Key Points
- Method 1 uses
getchar()for character-by-character input without any string functions. - Method 2 uses
fgets()which is safer thangets()as it prevents buffer overflow. - Both methods use for loops to reverse the string without using library functions like
strrev(). - Time complexity is O(n) where n is the length of the string.
Conclusion
String reversal using for loops provides a fundamental understanding of array manipulation and character handling in C. The fgets() method is recommended for production code due to its safety features.
Advertisements
