Computers in Engineering WWW Site - Example 14.3

Example 14.3


C Version

/*
  How swap functions affect variables.
*/

#include <stdio.h>

short i, j, m, n;    /*  Global variable Declaration  */

swap(i, j)       /*  Function Declaration  */
short *i, *j;      /*   '*' stands for pointer declaration  */
{
  short k;

  k = *i;
  *i = *j;
  *j = k;
  return(0);
}


main()
{
  /*  Assignment Statements  */
  printf("C63.C -> How swap functions affect variables.\n\n");
  printf("Enter Elements\n");
  printf("i = ");
  scanf("%hd", &i);    /*  Read element from keyboard entry  */
  printf("j = ");
  scanf("%hd", &j);

  swap(&i, &j);  /*  Exchange elements i and j using swap function  */

  /*  Print result  */
  printf("After First Swapping, the Elements are...\n");
  printf("i = %d, j = %d\n\n", i, j);

  /*  Same process for elements m and n : */

  printf("Enter Elements\n");
  printf("m = ");
  scanf("%hd", &m);
  printf("n = ");
  scanf("%hd", &n);

  swap(&m, &n);

  printf("After First Swapping, the Elements are...\n");
  printf("m = %d, n = %d\n\n", m, n);

  /*  Same process again for elements i and j :  */

  swap(&i, &j);

  printf("After Second Swapping, the Elements are...\n");
  printf("i = %d, j = %d\n\n", i, j);

  return(0);
}
/*  End of main Program C63  */
/*
INPUT :

5
7
3
4

OUTPUT :

C63.C -> How swap functions affect variables.

Enter Elements
i = 5
j = 7
After First Swapping, the Elements are...
i = 7, j = 5

Enter Elements
m = 3
n = 4
After First Swapping, the Elements are...
m = 4, n = 3

After Second Swapping, the Elements are...
i = 5, j = 7

*/

Last modified: 22/07/97