Knowee
Questions
Features
Study Tools

Write a C++ program that takes two integers as input and swaps their values without using a temporary variable. sample input and output Enter two integers: 10 20 Before swapping: num1 = 10, num2 = 20After swapping: num1 = 20, num2 = 10

Question

Write a C++ program that takes two integers as input and swaps their values without using a temporary variable. sample input and output Enter two integers: 10 20 Before swapping: num1 = 10, num2 = 20After swapping: num1 = 20, num2 = 10

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple C++ program that swaps two integers without using a temporary variable:

#include <iostream>
using namespace std;

int main() {
    int num1, num2;

    cout << "Enter two integers: ";
    cin >> num1 >> num2;

    cout << "Before swapping: num1 = " << num1 << ", num2 = " << num2 << endl;

    // Swapping values without using a temporary variable
    num1 = num1 + num2;
    num2 = num1 - num2;
    num1 = num1 - num2;

    cout << "After swapping: num1 = " << num1 << ", num2 = " << num2 << endl;

    return 0;
}

In this program, we first take two integers as input from the user. We then print the values of the integers before swapping. To swap the values, we use the formula num1 = num1 + num2, num2 = num1 - num2, and num1 = num1 - num2. Finally, we print the values of the integers after swapping.

This problem has been solved

Similar Questions

Arun is working on a program to swap the values of two variables, a and b, without using a temporary variable. Write a program to help Arun accomplish this task.Input format :The first line of input is an integer value a.The second line of input is an integer value b.Output format :The output prints the values of a and b after swapping. Refer to the sample output for the formatting specifications.

12345678910111213141516#include <stdio.h>void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; printf("%d %d", *x, *y);}int main() { int a = 120; int b = 121; printf("%d %d\n", a, b); swap(&a, &b); return 0;}

Using pointers write a program to swap two numbers using a user definedfunction(Call by reference)

Swapping of two numbers is an intermediate step in any sorting algorithm, In the lecture we use a temporary variable to swap two elements in the list.Can swapping of two numbers be done without using a temporary variable? Yes No Depends on size of list Depends on nature of elements in the list

Arun is working on a program to swap the values of two variables, a and b, without using a temporary variable. Write a program to help Arun accomplish this task.

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.