A Learning Platform

SUCCESS

Success = Discipline + Consistency + Sacrifice.
Discipline - in what you do.
Consistency - in what you do.
Sacrifice - for what you do.

                   -- Manjunatha C. P. --

Swap two numbers using functions - C program

 Swap 2 numbers using functions and pointers – C Program

Swap means exchanging of values of variables. We can use temporary third variable to swap or else without third variable also we can do it.

Swapping of 2 numbers can be done by passing parameters to a function.

Parameters can be passed to a function in two ways:
  1. Pass by value.
  2. Pass by pointer.

Pointers are derived data types in C.
Pointers are the variables which store memory addresses as their values.

Example:

int a;
int *p; // Pointer to integer
p = &a; // p stores address of variable a
Let’s write a C program to swap 2 numbers using the concept of pointers. Here we are using the function which takes 2 pointer arguments and swaps them using third variable.

Description:

x and y – integer variables.
temp – it is a temporary third variable used to swap numbers.
swap() – function which swaps x and y.

Algorithm to Swap 2 integer numbers using functions:

STEP 1: START
STEP 2: READ two numbers
              READ x, y
STEP 3: PRINT the values of x and y before swapping
              PRINT x, y
STEP 4: CALL swap() function and pass the arguments
              temp <- x
              x <- y
              y <- temp
STEP 5: PRINT the values of x and y after swapping
              PRINT x, y
STEP 6: END

C Program: Swap 2 integer numbers using pointers and functions (Pass by pointers)

#include<stdio.h>  
#include<conio.h>  
void swap(int *x, int *y);  
void main()  
{  
    int x, y;  
    printf("Enter 2 numbers to swap: ");  
    scanf("%d %d", &x, &y);  
    printf("Before swapping: x = %d and y = %d", x, y);  
    swap(&x, &y);  
    printf("\nAfter swapping: x = %d and y = %d", x, y);  
    getch();
}  
void swap(int *x, int *y)  
{  
    int temp;  
    temp = *x;  
    *x   = *y;  
    *y   = temp;  
 

Output:

Enter 2 numbers to swap: 4 9
Before swapping: x = 4 and y = 9
After swapping: x = 9 and y = 4

C Program: Swap 2 integer numbers using functions (Pass by value)

#include<stdio.h>  
#include<conio.h>  
void swap(int x, int y);  
void main()  
{  
    int x, y;  
    printf("Enter 2 numbers to swap: ");  
    scanf("%d %d", &x, &y);  
    printf("Before swapping: x = %d and y = %d", x, y);  
    swap(x, y);  
    getch();
}  
void swap(int x, int y)  
{  
    int temp;  
    temp = x;  
    x   = y;  
    y   = temp;  
    printf("\nAfter swapping: x = %d and y = %d", x, y);
}  

Output:

Enter 2 numbers to swap: 33 12
Before swapping: x = 33 and y = 12
After swapping: x = 12 and y = 33

QUIZ:

1] Pointers in C are.
  1. Fundamental data type.
  2. Derived data type.
  3. User defined data type.
  4. None.
2] Pointers store.
  1. Value of variable.
  2. Address of variable.
  3. data type of variable.
  4. None.