• C program to swap two numbers using functions temporary variable.
  • We can swap two numbers by using temporary variable.
  •  Lets see an example C program to swap two numbers without using any function.
  • C program to swap two numbers using third variable


Program #1: Write a C program to swap two numbers using temporary variable without using any function and by using third variable.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6.   int a,b, temp;
  7.   printf("Please enter two integer number to swap\n");
  8.   scanf("%d%d",&a,&b);
  9.   printf("before swapping\n");
  10.   printf("a=%d\n",a); 
  11.   printf("b=%d",b);   
  12.   temp=a;
  13.   a=b;
  14.   b=temp;
  15.   printf("\nafter swapping\n");
  16.   printf("a=%d\n",a); 
  17.   printf("b=%d",b);        
  18.   
  19.  return 0;
  20.   
  21. }
     

 Output:


swap numbers in c.png


Program #2: Write a C program to swap two numbers using temporary variable with using  function and using third variable.

  • C program to swap two numbers using functions call by value

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void swap(int a, int b);
  4. int main(int argc, char *argv[])
  5. {
  6.   int a,b;
  7.   printf("Please enter two integer numbers to swap\n");
  8.   scanf("%d%d",&a,&b);
  9.   printf("before swapping\n");
  10.   printf("a=%d\n",a); 
  11.   printf("b=%d",b);   
  12.   
  13.   swap(a,b);   
  14.     
  15.   return
  16.   
  17. }
  18.  
  19. void swap(int a, int b){
  20.     
  21.   int temp=a;
  22.   a=b;
  23.   b=temp;
  24.   printf("\nafter swapping\n");
  25.   printf("a=%d\n",a); 
  26.   printf("b=%d",b); 
  27.     
  28. }

Output:

  1. Please enter two integer numbers to swap
  2. 10
  3. 20
  4. before swapping
  5. a=10
  6. b=20
  7. after swapping
  8. a=20
  9. b=10

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu