Wednesday, April 30, 2025

C Program - Swap Two Numbers WITHOUT using the Third Variable

This C program swaps the values of two variables num1 and num2 without using a temporary variable. 

#include <stdio.h>

int main()
{

    int num1 = 10;
    int num2 = 30;

    printf("Initial State: %d, %d \n", num1, num2);

    //Swap
    num1 = num1 - num2;                          //num1 = 10 - 30 = -20
    //printf("Number 1: %d \n", num1);

    num2 = num1 + num2;                          //num2 = -20 + 30 = 10   FINAL
    //printf("Number 2: %d \n", num2);

    num1 = num2 - num1;                          //num1 = 10 - (-20) = 30 FINAL
    //printf("Number 1: %d \n", num1);

    printf("Final State: %d, %d \n", num1, num2);


    return 0;
}

Result: 

Initial State: 10, 30
Final State: 30, 10

Process returned 0 (0x0)   execution time : 0.023 s
Press any key to continue.

Here's a line-by-line explanation of the program: 

#include <stdio.h>

This line is a preprocessor directive that includes the standard input/output library in the program. This library contains functions for reading input and writing output. 

int main()
{

This is the starting point of the program. The main() function is the entry point of the program where the execution begins. The int before main() indicates that the function returns an integer value. 

    int num1 = 10;
    int num2 = 30;

These lines declare and initialize two integer variables named num1 and num2

    printf("Initial State: %d, %d \n", num1, num2);

This line prints out the initial state of the num1 and num2 variables. 

    num1 = num1 - num2;  // num1 = 10 - 30 = -20
    num2 = num1 + num2;  // num2 = -20 + 30 = 10
    num1 = num2 - num1;  // num1 = 10 - (-20) = 30

These three lines perform the swapping operation without using a temporary variable. The value of num1 is updated to the difference between num1 and num2, i.e., num1 = 10 - 30 = -20. Then, the value of num2 is updated to the sum of num1 and the original value of num2, i.e., num2 = -20 + 30 = 10. Finally, the value of num1 is updated to the difference between num2 and the new value of num1, i.e., num1 = 10 - (-20) = 30. As a result, the values of num1 and num2 are swapped. 

    printf("Final State: %d, %d \n", num1, num2);

This line prints out the final state of the num1 and num2 variables after the swapping operation. 

    return 0;
}

This line indicates the end of the main() function and returns an integer value of 0 to the operating system, indicating that the program has executed successfully.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...