Program To Reverse String

String reversing is an essential concept in string related programming. There are various approaches that use different logic to reverse a string. In this chapter, you will know how to implement two different concepts and logic of reversing a string manually without using any specific predefined function.

Reversing a string means the string that will be given by the user to your program in a specific sequence will get entirely reversed when the reverse of a string algorithm gets implemented in that particular input string. In the below-mentioned example, two approaches have been used to reverse a string in C language.

Reverse the Given String by Printing It Backward

Output:

Using Swapping Concept

Output:

Using For Loop

Output:

Explanation:

str[] = Hello
j = 0
len = strlen(Str) = 5.

The strlen is a string function used to find the string length. Let us the programming flow of reverse a string

For Loop First Iteration: for (i = len – 1; i >= 0; i–)
=> for (i = 5 – 1; 4 >= 0; 4–)
The condition (4 >= 0) is True.
RevStr[j++] = Str[i]
RevStr[0] = Str[4] = 0

Second Iteration: for (i = 4 – 1; 3 >= 0; 3–)
The condition (3 >= 0) is True.
RevStr[1] = Str[3] = l

Third Iteration: for (i = 3 – 1; 2 >= 0; 2–)
The condition (2 >= 0) is True.
RevStr[2] = Str[2] = l

Fourth Iteration: for (i = 2 – 1; 1 >= 0; 1–)
The condition (1 >= 0) is True.
RevStr[3] = Str[1] = e

Fifth Iteration: for (i = 1 – 1; 0 >= 0; 0–)
The condition (0 >= 0) is True.
RevStr[4] = Str[0] = H

Next, the condition inside the For Loop will fail

Using strrev()

Output:

Top Book Suggestion

The two books on C Programming Language that I Personally Recommend. I really loved reading these books. These books are listed for quality content, easy steps, and affordable price. You can get it from Amazon and Flipkart. 

 

Check The Price On Amazon:

1. C Programming Beginner’s Guide

2. Head First C: A Brain-Friendly Guide

Check The Price On Flipkart:

1. Introduction to C Programming 

2. Head First C: A Brain-Friendly Guide

Buy Premium Courses At Lowest Price. Become A Certified Developer Today!

Important C Programs

Pin It on Pinterest

Share This