A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

C program to swap adjacent characters of a string
Q:

C program to swap adjacent characters of a string

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)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now