Write a program that prints the reverse of a given string.
Program in C
C
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int length = strlen(str);
for (int i = length - 1; i >= 0; i--) {
printf("%c", str[i]);
}
printf("\n");
}
int main() {
char str[] = "EasyExamNotes";
printf("Original string: %s\n", str);
printf("Reversed string: ");
reverseString(str);
return 0;
}
Explanation:
- In this program, the reverseString function takes a character array str as a parameter.
- It calculates the length of the string using the strlen function.
- Then, it iterates through the characters of the string in reverse order and prints them one by one.
- Finally, it prints a new line character to complete the reversed string.
- In the main function, a character array str is declared with the example string “EasyExamNotes”.
- The original string is printed to the console, and then the reverseString function is called with the string as the argument.
- The reversed string is printed by the reverseString function.
Output:
Output
Original string: EasyExamNotes
Reversed string: setoNmaxEysaE
Program in Java
Java
public class ReverseString {
public static void reverseString(String str) {
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
public static void main(String[] args) {
String str = "EasyExamNotes";
System.out.println("Original string: " + str);
System.out.print("Reversed string: ");
reverseString(str);
}
}
Explanation:
- The program defines a public class named ReverseString.
- Inside the class, the program defines a static method named reverseString that takes a String parameter named str.
- The length of the string is obtained using the length() method of the String class, and it is stored in the variable length.
- The method then enters a for loop that iterates from length – 1 (the last character index) down to 0 (the first character index).
- Inside the loop, the method uses the charAt(i) method of the String class to access the character at the current index i in the string str. This character is printed using System.out.print().
- After the loop finishes, a newline character is printed using System.out.println() to move the output to the next line.
- The program also defines a main method, which is the entry point of the program.
- Inside the main method, a string str is declared and initialized with the value “EasyExamNotes”.
- The original string is printed to the console using System.out.println().
- The reverseString method is called with the str string as an argument to reverse the string and print the reversed version.
Output
Original string: EasyExamNotes
Reversed string: setoNmaxEysaE