Q:

C program to swap adjacent characters of a string

belongs to collection: C String Programs

0

C program to swap adjacent characters of a string

Given a string and we have to swap its adjacent characters using C program.

Here, to swap adjacent characters of a given string - we have a condition, which is "string length must be EVEN i.e. string must contains even number of characters".

Example:

    Input:
    String: "help"
    Output:
    String: "ehpl"

    Input:
    String: "Hello"
    Output:
    The length of the string is Odd..

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to swap adjacent characters of a string in C

/** C program to swap adjacent characters 
* of a string but obly if it is of even 
* length
*/

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

// main function
int main()
{
	// Declare an integer pointer
	char string[30]={0};
	char c=0;
	int length=0,i=0;

	// Take string input from the user
	printf("\nEnter the string : ");
	fgest(string,30,stdin);//gets(string);

	// calculate the length of the string
	length = strlen(string);

	if(length%2==0)
	{
		for(i=0;i<length;i+=2)
		{
			c = string[i] ; 
			string[i] = string[i+1];  
			string[i+1] = c;
		}
		printf("\nAfter Swap String : %s",string);
	}
	else
	{
		printf("\nThe length of the string is Odd..\n");
	}
	
	return 0;
}

Output

    Run 1: 
    Enter the string : help
    After Swap String : ehpl

    Run 2:
    Enter the string : program
    The length of the string is Odd..

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to read time in string format and extrac... >>
<< C program to eliminate all vowels from a string...