Object

Write a program that swaps two values using pointers.

Algorithm

  1. Declare a function void swap(int *x, int *y) that accepts two integer pointer arguments and returns no value.
    The Function main
  2. Declare integer variables a and b.
  3. Set a = 10 and b = 20.
  4. Write values of a and b.
  5. Call the function swap(&a, &b) considering a and b as actual arguments.
  6. Write swapped values of a and b.
  7. Exit.
    Defining the Function void swap(int *x, int *y)
    where *x and *y are the formal integer pointer arguments
  8. Declare integer variable temp.
  9. temp = *x.
  10. *x = *y.
  11. *y = temp.
  12. Exit.

Flowchart

C++ Source Code

// program 103
#include<iostream>
using namespace std;

void swap(int *x, int *y);

int main()
{
  int a = 10, b = 20;
  cout << "Values of a and b before swapping are: " << endl;
  cout << "a = " << a << " and b = " << b << endl;

  swap(&a, &b);

  cout << "\nValues of a and b after swapping are: " << endl;
  cout << "a = " << a << " and b = " << b << endl;

  return 0;
}

void swap(int *x, int *y)
{
  int temp;
  temp = *x;
  *x = *y;
  *y = temp;
}

C Source Code

/*program 103*/
#include<stdio.h>

void swap(int *x, int *y);

int main()
{
  int a = 10, b = 20;
  printf("\nValues of a and b before swapping are: ");
  printf("\na = %d and b = %d", a,b);
  swap(&a, &b);
  printf("\n\nValues of a and b after swapping are: ");
  printf("\na = %d and b = %d", a,b);
  
  return 0;
}

void swap(int *x, int *y)
{
  int temp;

  temp = *x;
  *x = *y;
  *y = temp;
}

Output

Values of a and b before swapping are:
a = 10 and b = 20

Values of a and b after swapping are:
a = 20 and b = 10

Design a site like this with WordPress.com
Get started