Skip to main content

Practical-15

Write a program to use of pointer in arithmetic operation.

Introduction

In this program, we will learn to use pointer in arithmetic operation.

Algorithm

  1. Start
  2. Declare two integer variables.
  3. Declare two pointer variables.
  4. Initialize the pointer variables.
  5. Print the initial value of integer variables.
  6. Use pointer arithmetic operation.
  7. Print the updated value of integer variables.
  8. End

Code

Practical-15.c
#include<stdio.h>

//Use main function
void main()
{
//Declare integers
int a = 5, b = 4;

//Declare pointer integer variable
int *ptr1, *ptr2;

//Initialize pointer
ptr1 = &a;
ptr2 = &b;

//Print initial integer
printf("The initial value of a = %d and b = %d \n", a, b);

// Use '*' operator for pointer pointing
*ptr1 = *ptr1 + 1;
*ptr2 = *ptr2 + 5;

//Print updated integer
printf("The modified value of a = %d and b = %d \n", a, b);
}

Output

The initial value of a = 5 and b = 4
The modified value of a = 6 and b = 9
Explanation

In this program, we have declared two integer variables and two pointer variables. We have initialized the pointer variables with the address of integer variables. Then we have printed the initial value of integer variables. Then we have used pointer arithmetic operation to update the value of integer variables. Finally, we have printed the updated value of integer variables.