Jump to content

How to swap integer values without using a function in C++?


SubhanUllah

Recommended Posts

  • 5 months later...
On 10/31/2022 at 9:31 AM, SubhanUllah said:
int a = 6; 
int b = 2; 
std::cout << "a=" << a << " b=" << b << "\n"; 
int temp = a; 
a = b; 
b = temp; 
std::cout << "a=" << a << " b=" << b << "\n";

https://locksmith365nv.com/

This code swaps the values of the variables a and b using a temporary variable called temp. Here's how the code works step by step:

 

  1. The value 6 is assigned to the variable a, and the value 2 is assigned to the variable b.
  2. The std::cout statement outputs the values of a and b to the console.
  3. The value of a (which is 6) is assigned to the temporary variable temp.
  4. The value of b (which is 2) is assigned to a.
  5. The value of temp (which is 6) is assigned to b.
  6. The second std::cout statement outputs the new values of a and b to the console, which will be 2 and 6, respectively.

So, after the code is executed, the values of a and b have been swapped, with a now equal to the original value of b and b now equal to the original value of a.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...