Introduction to pointers:

Pointers are a data-type offered by C++ to store the memory address of other datatypes.

Syntax:

<data_type> pointer_name;

Here data-type is the data-type of the variable whose value a pointer will hold.

*’ asteric operator is used to access the value whose address a pointer is storing.

Example,

int *a;

int b=12;

cout<<a<<”\n”;

cout<<*a;

In this program, the third line will print the address of b in memory whereas the fourth line will print the value of b(I.e.12). Read More.

Approaching the given problem:

To swap two numbers using pointers, we will first store the values in normal variables and declare two pointers to them. Then we will declare a pointer temp. Then, with the help of ’*’ operator, we will store the value of first pointer in temp. Then we will change the value in first pointer equal to the value in second pointer and then we set the value of second pointer equal to the value in temp.

Algorithm:

  1. Input two numbers from the user and store them in a and b.
  2. Declare three-pointers x,y, and temp.
  3. Set the value in ‘x’ to ‘temp’.
  4. Set the value in ‘y’ to ‘x’.
  5. Set the value in ‘temp’ to ‘x’.
  6. Display the numbers after swapping by using pointers ‘x’ and ‘y’.

Code:

#include <iostream>

using namespace std;

int main()

{   int a,b;

cout << "Enter two numbers\n"; //taking input from the user

cin>>a>>b;

int *x,*y,temp;

x=&a; //setting pointers to store the address of

y=&b; // variables containing entered values

temp=*x; //swapping

*x=*y;

*y=temp;

cout<<"Numbers after swapping:"; //displaying the numbers after swapping

cout<<"\nfirst number="<<a;

cout<<"\nsecond number="<<b;

return 0;

}

Output:

Enter two numbers: 
14 16

Number after swapping:
first number=16
second number=14

 

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2020

CopyRight © 2020