Bookmark and Share

free counters
Back to Problem list

Problem 4: Given a String, Write a program to reverse that String without using library function.

Solution:
This problem is very common and popular among beginners, lets try to solve it..

Assume the given String is: ABCD, its reverse form is: DCAB, if we carefully analyze these two String, position by position, we found that...

char at Position 0 ( first position) interchange(swap) with last the char at the last one. (which is D)
So, we get: DBCA

char at position 1(which is B) interchange(swap) with the 2nd last char( which is C)
So we get: DCBA

Finally we get the reversed string.

Source Code:

#include<stdio.h>
#include<string.h>

int main() {
	int pos_1, pos_2;
	char ch;
	char input[100];
	gets(input); // reading the String
	pos_1 = 0; // first position
	pos_2 = strlen(input) - 1;  // last position

	while(pos_1 < pos_2) {
		ch = input[pos_1];
		input[pos_1] = input[pos_2];
		input[pos_2] = ch;
		pos_1++;
		pos_2--;          
	}

	printf("%s\n",input);
	return 0;
}


Pop quiz:
Why pos_2 = strlen(input) - 1 ? but not pos_2 = strlen(input) ?


Back to Problem list