-->

Program to swap two numbers using pointer.

using codeblocks
-------------------------------------------------------------------------------------------
//pointer to swap two numbers
#include <stdio.h>

int main()
{
    int num1,num2,t;                //variables declaration
    int *p1,*p2;                     //pointer to store address
    printf("enter two numbers\n");
    scanf("%d%d",&num1,&num2);      //gets input
    printf("before swapping\n");
    printf("num1=%d,num2=%d\n",num1,num2);//display of values before swap
    p1=&num1;                             //assignment of address to first pointer
    p2=&num2;                              // assignment of address to second pointer
    t=*p1;                                //assigning first value to third variable
    *p1=*p2;                              //assigning second value to first pointer
    *p2=t;                                 //assigning first  value to second pointer
     printf("after swapping\n");
    printf("num1=%d,num2=%d\n",num1,num2);//prints values after swapping
    return 0;
}

-------------------------------------------------------------------------------------
using turbo c++
-----------------------------------------------------------------------------------------------------
//pointer to swap two numbers
#include <stdio.h>
#include<conio.h>
int main()
{
    int num1,num2,t;                //variables declaration
    int *p1,*p2;                     //pointer to store address
    printf("enter two numbers\n");
    scanf("%d%d",&num1,&num2);      //gets input
    printf("before swapping\n");
    printf("num1=%d,num2=%d\n",num1,num2);//display of values before swap
    p1=&num1;                             //assignment of address to first pointer
    p2=&num2;                              // assignment of address to second pointer
    t=*p1;                                //assigning first value to third variable
    *p1=*p2;                              //assigning second value to first pointer
    *p2=t;                                 //assigning first  value to second pointer
     printf("after swapping\n");
    printf("num1=%d,num2=%d\n",num1,num2);//prints values after swapping
   getch();    
return 0;
}

No comments:

Post a Comment