Program to swap two numbers |C Program|

Introduction

     Swapping two numbers is a fundamental operation in programming, and understanding how to perform this task efficiently is crucial for any budding programmer. In this blog post, we'll explore a simple C program that swaps two numbers and gain insights into the underlying logic.          

Code

    
     
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    int a,b;
    clrscr();
    printf("before swapping");
    scanf("%d%d",&a,&b);
    swap(a,b);
    getch();
    }
    swap(int m,int n)
    {
    int t;
    t=m;
    m=n;
    n=t;
    printf("after swapping %d\t%d",m,n);
    }
       
     


Output

    
        // Output
        before swapping 5   6
        after swapping 6    5
       



Explanation

1. Header Files:
The program includes the standard input/output header <stdio.h> and the console I/O header <conio.h>.
2. Main Function:
The main function initiates the program. Two integer variables, a and b, are declared to store the numbers to be swapped. 
Users are prompted to enter values for a and b using scanf.
3. Swapping Function:
The swap function is called from the main function to perform the swapping.
The function takes two parameters, m and n, representing the numbers to be swapped.
A temporary variable t is used to store the value of m.
The values of m and n are then exchanged, and the result is printed.
4. User Interaction:
Users are provided with feedback before and after the swapping operation.

Conclusion

     This C program demonstrates a basic yet essential concept in programming: swapping two numbers. Understanding this process is foundational, as it forms the basis for more complex algorithms and data manipulation operations. While the provided code achieves its goal, it's worth noting that there are more concise ways to swap numbers in C using pointers.

Post a Comment

0 Comments