Write a program to swapping two numbers.

swap
#include<stdio.h>
#include<conio.h>
int main()
{
	int a,b,c;
	printf("Enter two numbers for A and B:");  //also use puts();
	scanf("%d %d", &a,&b);  //don't use gets();(string ke case me gets use kr skte hai)//
	c=a;
	a=b;
	b=c;
	printf("After swaping the values are: A=%d & B=%d.",a,b);
	getch();
}


/* Copy valu of in third variable c,value of b in a, and value of c in b*/

The above code is a C program that swaps the values of two variables a and b using a temporary variable c.

The program starts with the inclusion of the standard input/output header file stdio.h and the non-standard conio.h header file which provides the getch() function.

It then defines the main() function, which is the starting point of the program. Inside the main function, it declares three integer variables a, b, and c.

The program uses the printf() function to prompt the user to enter two numbers. The scanf() function is used to read the input and store it in the variables a and b.

The values of a and b are then swapped using a temporary variable c. The value of a is first stored in c, then the value of b is assigned to a, and finally the value of c (which is the original value of a) is assigned to b.

After the swapping, the program uses the printf() function to display the new values of a and b on the screen.

Finally, the program uses the getch() function which waits for the user to press a key before terminating the program. It’s important to note that the getch() function is not a part of the standard C library, it is provided by the non-standard conio.h header file and it’s use is not recommended in most cases.

It’s also good practice to use puts("Enter two numbers for A and B:") instead of printf("Enter two numbers for A and B:") as it automatically appends a newline character at the end of the string, which makes the output more readable. And scanf() is more secure than gets() as scanf() can be used to limit the input size and also format the input.

Another way to swap two numbers without the use of temporary variable is by using the mathematical operations like addition and subtraction.

#include <stdio.h>

int main() {
    int a, b;
    printf("Enter the value of a: ");
    scanf("%d", &a);
    printf("Enter the value of b: ");
    scanf("%d", &b);

    // Swapping the values
    a = a + b;
    b = a - b;
    a = a - b;

    printf("After swapping, the value of a is: %d\n", a);
    printf("After swapping, the value of b is: %d\n", b);
    return 0;
}

In this approach, we are using the mathematical operations like addition and subtraction to swap the values of two variables.

Thanks

Write a program to swapping two numbers.

Leave a Reply

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

Scroll to top