In this tutorial you will learn about the C Program to Swap Two Strings and its application with practical example.
C Program to Swap Two Strings
In this tutorial, we will learn to create a C program that will Swap Two Strings in C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Conditional statements in C programming.
- String functions of c programming.
Program to Swap Two Strings
As we all know the String is a collection of character data types. In strings, only one variable is declared which can store multiple values. First, we will take the input string from the user. Then we will Swap Two Strings using the third variable that will help to swap.
With the help of this program, we can Swap Two Strings.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declare the variables for the program. 2. Take the input string from the user. 3. <strong>Swap Two Strings</strong>. 4. Print the output. 5. End the program. |
Program to Swap Two Strings:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <stdio.h> /* Including the header file for the suuport the string functions */ #include <string.h> int main() { /* declaring the variables for the program */ char first[100], second[100], flag[100]; /* Taking input from the user string 1 */ printf("Enter first string\n"); gets(first); /* Taking input from the user string 2 */ printf("Enter second string\n"); gets(second); /* Printing string before swapping */ printf("\nBefore Swapping\n"); printf("First string: %s\n", first); printf("Second string: %s\n\n", second); /* Swapping the strings */ strcpy(flag, first); strcpy(first, second); strcpy(second, flag); /* Printing string after swapping */ printf("After Swapping\n"); printf("First string: %s\n", first); printf("Second string: %s\n", second); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- first[100] = it will hold the string value.
- second[100] = it will hold the string value.
- flag[100] = it will hold the integer value.
Taking the input string 1 from the user.