This is a C Program to accept an array & swap elements using pointers.
The program will implement an array and will swap the elements of the array. Swapping is done using pointers.
1. Declare an array and define all its elements.
2. Create a function with two parameters i.e. two pointer variables.
3. Inside this function, first create a temporary variable. Then this temporary variable is assigned the value at first pointer.
4. Now, value at first pointer changes to the value at second pointer.
5. And value at second pointer changes to the value of temporary variable.
6. This way swapping is done and in main() function, we need to pass two pointer variables pointing the element which we need to swap.
Here is source code of the C program to accept an array & swap elements using pointers. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
/*
* C program to accept an array of 10 elements and swap 3rd element
* with 4th element using pointers and display the results.
*/
#include <stdio.h>
void swap34(float *ptr1, float *ptr2);
void main()
{
float x[10];
int i, n;
printf("How many Elements...\n");
scanf("%d", &n);
printf("Enter Elements one by one\n");
for (i = 0; i < n; i++)
{
scanf("%f", x + i);
}
/* Function call:Interchanging 3rd element by 4th */
swap34(x + 2, x + 3);
printf("\nResultant Array...\n");
for (i = 0; i < n; i++)
{
printf("X[%d] = %f\n", i, x[i]);
}
}
/* Function to swap the 3rd element with the 4th element in the array */
void swap34(float *ptr1, float *ptr2 )
{
float temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
1. Declare an array and define all the elements according to its size taken from users.
2. Now create a function passing two pointer variables of float type as parameters to this function.
3. Inside a function a variable temp is declared of float type, which will store the value pointed by first pointer variable.
4. Now value pointer by first pointer variable is changed to the value pointed by second pointer variable, and value pointer by second variable is change to the value of temp variable.
5. Exit the function.
6. In the main() method, call this function with pointers pointing to those two element which you want to swap.
How many Elements... 4 Enter Elements one by one 23 67 45 15 Resultant Array... X[0] = 23.000000 X[1] = 67.000000 X[2] = 15.000000 X[3] = 45.000000
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
- Check Computer Science Books
- Check C Books
- Practice BCA MCQs
- Practice Computer Science MCQs
- Watch Advanced C Programming Videos