05 02

Write a program that will swap two numbers

Using arithmetic operators + and -

#include<stdio.h> struct numbers { int num1; int num2; }; void swap(struct numbers *ptr); int main() { struct numbers original; printf("Enter any two numbers\n"); scanf("%d%d",&original.num1,&original.num2); swap(&original); printf("After swapping,the numbers are %d,%d\n",original.num1,original.num2); return 0; } void swap(struct numbers *ptr) { ptr->num1 = (ptr->num1) + (ptr->num2); ptr->num2 = (ptr->num1) - (ptr->num2); ptr->num1 = (ptr->num1) - (ptr->num2); }

Using bitwise XOR

#include<stdio.h> struct numbers { int num1; int num2; }; void swap(struct numbers *ptr); int main() { struct numbers original; printf("Enter any two numbers\n"); scanf("%d%d",&original.num1,&original.num2); swap(&original); printf("After swapping,the numbers are %d,%d\n",original.num1,original.num2); return 0; } void swap(struct numbers *ptr) { ptr->num1 = (ptr->num1) ^ (ptr->num2); ptr->num2 = (ptr->num1) ^ (ptr->num2); ptr->num1 = (ptr->num1) ^ (ptr->num2); }

Give some inputs to the above programs and check if the numbers are swapped.

write a program that will swap two numbers

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>