Practice Programs in C: Swap Numbers Using Pointers and Dynamic Array


This tutorial provides practical C programming exercises for pointers, including swapping numbers using pointers and dynamic array allocation and manipulation. These examples help beginners understand memory addresses, pointer operations, and dynamic memory usage.

1. Swap Numbers Using Pointers

Program Description: Swaps two numbers by passing their addresses to a function using pointers.


#include <stdio.h>

// Function to swap two numbers using pointers
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x, y;

printf("Enter two numbers: ");
scanf("%d %d", &x, &y);

printf("Before swap: x = %d, y = %d\n", x, y);

swap(&x, &y); // passing addresses

printf("After swap: x = %d, y = %d\n", x, y);

return 0;
}

Sample Output:


Enter two numbers: 10 20
Before swap: x = 10, y = 20
After swap: x = 20, y = 10

Key Point: Using pointers allows the function to modify the original variables.

2. Dynamic Array Program

Program Description: Creates a dynamic array using malloc, allows user input, and displays the elements.


#include <stdio.h>
#include <stdlib.h>

int main() {
int n;
int *arr;

printf("Enter the number of elements: ");
scanf("%d", &n);

// Allocate memory dynamically
arr = (int*) malloc(n * sizeof(int));
if(arr == NULL) {
printf("Memory not allocated.\n");
return 1;
}

// Input elements
for(int i = 0; i < n; i++) {
printf("Enter element %d: ", i+1);
scanf("%d", &arr[i]);
}

// Display elements
printf("Array elements: ");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");

free(arr); // free allocated memory
return 0;
}

Sample Output:


Enter the number of elements: 4
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Array elements: 10 20 30 40

Key Point: Dynamic memory allows arrays to adjust size at runtime instead of using fixed size.

Key Points to Remember

  1. Pointers are essential for swapping variables and dynamic arrays
  2. malloc and free are used to allocate and release memory
  3. Dynamic arrays are useful when array size is unknown at compile time
  4. Always check if memory allocation is successful