Wednesday, April 30, 2025

C Program - Swap Two Numbers using Multiplication and Division

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

#include <stdio.h>

int main()
{

    int num1 = 6;
    int num2 = 3;

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

    num1 = num1 * num2;     //num1 = 6 * 3 = 18
    printf("Number 1: %d \n", num1);

    num2 = num1 / num2;     //num2 = 18 / 3 = 6 FINAL
    printf("Number 2: %d \n", num2);

    num1 = num1 / num2;     //num1 = 18 / 6 = 3 FINAL
    printf("Number 1: %d \n", num1);

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

    return 0;
}

Result: 

Initial State: 6, 3
Number 1: 18
Number 2: 6
Number 1: 3
Final State: 3, 6

Process returned 0 (0x0)   execution time : 0.031 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 = 6;
    int num2 = 3;

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 = 6 * 3 = 18
    printf("Number 1: %d \n", num1);

These two lines multiply num1 and num2 and assign the result to num1. As a result, the value of num1 becomes 18. The new value of num1 is then printed. 

    num2 = num1 / num2;     //num2 = 18 / 3 = 6 FINAL
    printf("Number 2: %d \n", num2);

These two lines divide num1 by num2 and assign the result to num2. As a result, the value of num2 becomes 6. The new value of num2 is then printed. 

    num1 = num1 / num2;     //num1 = 18 / 6 = 3 FINAL
    printf("Number 1: %d \n", num1);

These two lines divide num1 by the new value of num2 and assign the result to num1. As a result, the value of num1 becomes 3. The new value of num1 is then printed. 

    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 .  ...