Results 1 to 4 of 4

Thread: What is the program to swap two numbers?

  1. #1
    Join Date
    Nov 2009
    Posts
    1,191

    What is the program to swap two numbers?

    Hi Friends,

    I am studying in BSC(IT). I have to write the program to swap the two numbers (Integer or float). I have tried to write this program, but when I run the program it goes into the indefinite looping. I am getting frustrated because of this. If you are able to provide me the program code for swapping the two numbers, then it will be better for me. Simple logic will also works for me.
    Your help will be greatly appreciated...

  2. #2
    Join Date
    May 2008
    Posts
    2,297

    Re: What is the program to swap two numbers?

    Hi friend,

    Try the below program code to swap two numbers. This program is successfully running on my computer:

    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    int x,y;
    printf("Enter two numbers");
    scanf("%d%d",&x,&y);

    x=x+y;
    y=x-y;
    x=x-y;

    printf("\n X = %d \n Y = %d\n");
    getch();
    }

  3. #3
    Join Date
    Oct 2005
    Posts
    2,393

    Re: What is the program to swap two numbers?

    I don't think it's too difficult to write program for swapping two numbers. It's very simple logic, you have to first store value of the one number into the one variable. For reference see below code:

    #include<stdio.h>
    int main()
    {
    int p,q;
    printf("Enter values for two numbers i.e p & q\n");

    scanf("%d %d",&p,&q);

    q = q+p;
    p= q-p;
    q=q-p;

    printf("p = %d,q = %d",p,q);

    }

  4. #4
    Join Date
    May 2008
    Posts
    2,389

    Re: What is the program to swap two numbers?

    Have you tried below logic to swap to numbers??

    //M and N are the two variable which we have to swap
    M=M+N;
    N=M-N;
    M=M-N;

    Please implements this logic and let me know if it is working or not.

Similar Threads

  1. How to swap two numbers without using a third temporary variable?
    By Rick Dees in forum Software Development
    Replies: 7
    Last Post: 30-08-2011, 09:36 AM
  2. Program to print GCD of given numbers
    By Bhavesh_seth in forum Software Development
    Replies: 5
    Last Post: 15-03-2011, 08:03 PM
  3. C Program to print Combination of numbers
    By Prashobh Mallu in forum Software Development
    Replies: 6
    Last Post: 26-03-2010, 09:21 PM
  4. Need C program code to count numbers of negative & positive numbers
    By Sarfaraj Khan in forum Software Development
    Replies: 5
    Last Post: 16-01-2010, 02:00 PM
  5. Program to print odd and even numbers
    By roodiii in forum Software Development
    Replies: 3
    Last Post: 30-11-2009, 02:13 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,751,885,467.88427 seconds with 16 queries