×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to swap elements of two integer arrays using user define function

In this C program, we are going to swap the elements of two one dimensional integers arrays? Here, we are passing two integer arrays along with its total number of elements to the function.
Submitted by IncludeHelp, on March 20, 2018

Problem statement

Given two integer arrays and we have to swap their elements by creating our own function (User Define Function) using C program.

Note: Total number of elements of both arrays should be same.

Function Declaration

Here is the function that we have used in the program,

void swapElements(int *arr1 , int *arr2 , int n)

Here,

  • void is the return type of the function i.e. function will return nothing.
  • swapElements is the function name that is going to be used to swap the elements.
  • int *arr1 , int *arr2 integer pointers that will store the base addresses of the array which will be passed through the main() function.
  • int n is the total number of elements (both arrays have same number of elements).

Function Calling

Function calling statement,

swapElements(array_1,array_2,5);

Here,

  1. swapElements name of the function, which we declared and defined above the main() function.
  2. array_1 is the name of the first array which has 5 elements.
  3. array_2 is the name of the second array which has 5 elements.
  4. 5 is the total number of elements which is common for both array.

Program to swap elements of two integer arrays using user define function in C

/*  
* C program to swap elements of two integer arrays
*/

#include <stdio.h>

// funtion to swap the elements of the two arrays
void swapElements(int *arr1 , int *arr2 , int n)
{
    int i=0,temp=0;
    
    for(i=0 ; i<n ; i++)
    {
        temp    = arr1[i];
        arr1[i] = arr2[i];
        arr2[i] = temp;
    }
}

// main function
int main()
{
    int i=0;
    
    // define two 1d-arrays
    int array_1[6] = {0,1,2,3,4};
    int array_2[6] = {5,6,7,8,9};
    
    // Passing two arrays and the number of 
    // elements to Function
    swapElements(array_1,array_2,5);
	
    printf("\nThe arrays after swap are..\n");
	
    for(i=0 ; i<5 ; i++)
    {
        printf("\narra_1 [%d] : %d",i,array_1[i]);
    }
    
    printf("\n");
    
    for(i=0 ; i<5 ; i++)
    {
	printf("\narray_2 [%d] : %d",i,array_2[i]);
    }
	
    return 0;
}

Output

The arrays after swap are..

arra_1 [0] : 5
arra_1 [1] : 6
arra_1 [2] : 7
arra_1 [3] : 8
arra_1 [4] : 9

array_2 [0] : 0
array_2 [1] : 1
array_2 [2] : 2
array_2 [3] : 3
array_2 [4] : 4

C User-defined Functions Programs »


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.