Wednesday, 4 July 2012

Swapping of numbers without using a temporary variable in C


Code - 


//_________Swap 2 Numbers without using a temporary variable _________

//________________Include Header Files_____________

#include<stdio.h>

#include<conio.h>

//_Header field included mainly for the getch() function__

int main()

//_______Function from where program execution starts_________________

{
int first_number = 0, second_number = 0;

printf("\n\n\t\t   ______Program will Swap 2 Numbers_______");

printf("\n\n\n Enter the First Number  - ");

//_________Prompting the user to enter First Number_________

scanf("%d",&first_number);

//___Reading the user_input and storing input in variable first_number__

printf("\n Enter the Second Number - ");

//_________Prompting the user to enter Second Number_________

scanf("%d",&second_number);

//_________Reading the user_input and storing input in variable second_number________

//______________Displaying the user input once again________________

printf("\n\n\t Numbers before swapping :- \n\n\t\t First  - %d \n\n\t\t Second - %d", first_number, second_number);

//____________Swapping of two numbers________________

/* logic changes here instead of taking a temporary variable add the numbers and assign the value to the first variable */

first_number = first_number + second_number;

/* from the new number subtract the second number and assign it to second number as

the second number is still the same as entered by the user */

second_number = first_number - second_number;

/* Repear the same step for first number subtract second number from first as now the second number has been changed */

first_number = first_number - second_number;


//__________Displaying the numbers after swapping____________

printf("\n\n\t Numbers after swapping :- \n\n\t\t First  - %d \n\n\t\t Second - %d", first_number, second_number);

printf("\n\n________________________________________________________________________________");

getch();

return 0;

//__return 0 tells the compiler that program has executed succesfully without any error__


}


No comments:

Post a Comment