C Programming Examples Tutorial Index

C String Programs

This is an example C program uses a temporal variable to swap the values of two variables with each other. This type of program is used quite commonly when developing software.



Example C Program:
#include <stdio.h>
#include <string.h> /* Header file to support string functions */

void main() {
  /* Declaration of variables used within this program. */
  char first[100], second[100], temp[100];

  /* Take input from the user and save it to the first variable. */
  printf("Enter first string:\n");
  gets(first);

  /* Take input from the user and save it to the second variable. */
  printf("Enter second string:\n");
  gets(second);

  /* Printing the user input before swapping. */
  printf("\nBefore Swapping\n");
  printf("First string: %s\n", first);
  printf("Second string: %s\n\n", second);

  /* Swapping the variables. */
  strcpy(temp, first); /* Copying the first variable to the flag variable. */
  strcpy(first, second); /* Copying the second variable to the first variable. */
  strcpy(second, temp); /* Copying the flag variable to the second variable. */

  /* Printing the variables after the swapping. */
  printf("After Swapping:\n");
  printf("First string: %s\n", first);
  printf("Second string: %s\n", second);
}

Program Output:

Enter first string:
Hello
Enter second string:
World

Before Swapping
First string: Hello
Second string: World

After Swapping:
First string: World
Second string: Hello


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram