C Program to swap the first and last character of a string

Write a program to swap the first and last character of a string in C.

Example,

Input: HelloWorld
Output: delloWorlH

Let str[] be the input string of size n. The first character of str[] is given by str[0]. The last character of str[] is given by str[n-1]. We can find the value of n using strlen() function. Now, we will simply use a temporary variable to swap str[0] and str[n-1]. See the program given below.

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

int main() {

	char temp, str[100];
	int n;

	printf("Enter String: ");
	gets(str);

	n = strlen(str);

	// swap str[0] and str[n-1]
	temp = str[0];
	str[0] = str[n - 1];
	str[n - 1] = temp;

	printf("Output String: %s", str);

}

Output

Enter String: HelloWorld
Output String: delloWorlH

Swap the first and last character of a string using function

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

void swap_first_and_last(char* str) {

	char temp;
	int n;

	n = strlen(str);

	// swap str[0] and str[n-1]
	temp = str[0];
	str[0] = str[n - 1];
	str[n - 1] = temp;

}

int main() {

	char str[100];

	printf("Enter String: ");
	gets(str);

	swap_first_and_last(str);

	printf("Output String: %s", str);

}

Output

Enter String: JognSmith
Output String: hognSmitJ

Leave a Comment

Your email address will not be published. Required fields are marked *