You are on page 1of 6

Pointers – Programs

1) Write a program to print the address of an integer variable using pointer

#include <stdio.h>

int main() {

int num = 10; // Integer variable

int *ptr; // Pointer to an integer

ptr = &num; // Assigning the address of num to ptr

// Printing the address of the integer variable

printf("Address of num: %p\n", ptr);

return 0;

2)Write a program to swap two numbers using pointer.

#include <stdio.h>

// Function to swap two numbers using pointers

void swap(int *ptr1, int *ptr2) {

int temp = *ptr1;

*ptr1 = *ptr2;

*ptr2 = temp;

}
int main() {

int num1, num2;

// Input the numbers

printf("Enter first number: ");

scanf("%d", &num1);

printf("Enter second number: ");

scanf("%d", &num2);

// Displaying numbers before swapping

printf("Before swapping: \n");

printf("First number = %d\n", num1);

printf("Second number = %d\n", num2);

// Call the swap function

swap(&num1, &num2);

// Displaying numbers after swapping

printf("\nAfter swapping: \n");

printf("First number = %d\n", num1);

printf("Second number = %d\n", num2);

return 0;

}
3)WAP To add two numbers using pointers.

#include <stdio.h>

void add(int *num1, int *num2, int *result) {

*result = *num1 + *num2;

int main() {

int num1, num2, result;

printf("Enter first number: ");

scanf("%d", &num1);

printf("Enter second number: ");

scanf("%d", &num2);

add(&num1, &num2, &result);

printf("Sum of %d and %d is %d\n", num1, num2, result);

return 0;

}
4)WAP To read and Display values in 1D arrays using pointer.

#include <stdio.h>

#define MAX_SIZE 100

int main() {

int array[MAX_SIZE], size, i;

int *ptr;

// Input size of the array

printf("Enter the size of the array: ");

scanf("%d", &size);

// Input elements of the array using pointer

printf("Enter %d elements in the array:\n", size);

ptr = array; // Point ptr to the first element of the array

for (i = 0; i < size; i++) {

scanf("%d", ptr);

ptr++; // Move the pointer to the next element

// Display elements of the array using pointer

printf("Elements of the array are: ");

ptr = array; // Reset ptr to the first element of the array


for (i = 0; i < size; i++) {

printf("%d ", *ptr);

ptr++; // Move the pointer to the next element

printf("\n");

return 0;

5)WAP to find the factorial of a given number using Pointers.

#include <stdio.h>

void findFactorial(int num, unsigned long long *factorial);

int main() {

int number;

unsigned long long factorial = 1;

printf("Enter a number: ");

scanf("%d", &number);

findFactorial(number, &factorial);

printf("Factorial of %d = %llu\n", number, factorial);


return 0;

void findFactorial(int num, unsigned long long *factorial) {

int i;

*factorial = 1;

// Calculate factorial using pointers

for (i = 1; i <= num; ++i) {

*factorial *= i;

You might also like