How to swap two numbers
// Method 1: With temporary variable
temp = A
A = B
B = temp
// without temporary variable
// Method 2: Addition and subtraction
A = A + B
B = A - B
A = A - B
// Method 3: Muitply and Divide
A = A * B
B = A / B
A = A / B
How to swap two numbers
// Method 1: With temporary variable
temp = A
A = B
B = temp
// without temporary variable
// Method 2: Addition and subtraction
A = A + B
B = A - B
A = A - B
// Method 3: Muitply and Divide
A = A * B
B = A / B
A = A / B
how to swap values in variables in c
#include <stdio.h>
#include <stdlib.h>
int main()
{
//initialize variables
int num1 = 10;
int num2 = 9;
int tmp;
//create the variables needed to store the address of the variables
//that we want to swap values
int *p_num1 = &num1;
int *p_num2 = &num2;
//print what the values are before the swap
printf("num1: %i\n", num1);
printf("num2: %i\n", num2);
//store one of the variables in tmp so we can access it later
//gives the value we stored in another variable the new value
//give the other variable the value of tmp
tmp = num1;
*p_num1 = num2;
*p_num2 = tmp;
//print the values after swap has occured
printf("num1: %i\n", num1);
printf("num2: %i\n", num2);
return 0;
}
Write a program to show swap of two numbers without using third variable.
#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b;//a=30 (10+20)
b=a-b;//b=10 (30-20)
a=a-b;//a=20 (30-10)
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
program to swap two numbers
#include<stdio.h>
int main()
{
int x = 20, y = 30, temp;
temp = x;
x = y;
y = temp;
printf("X = %d and Y = %d", x, y);
return 0;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us