Aug 14, 2020

C Program to Print Array Elements Using Pointers

Ex: Write a C program to print array elements using pointers. How to write a C program to print array elements using pointers. C program to print array elements using pointers.


Input from user:

Enter how many elements you are going to enter: 5

Enter elements:

10

20

30

40

50


Expected output:

Array elements are:

10

20

30

40

50




  Step by step logic of the given program:


1. Accept limit from user declare variable say no.


2. Accept elements using pointer variable ptr and move pointer to next location by using ptr++.


3. After that set pointer back to first array element by using:

ptr=arr;


4. Last, print pointed values by using  dereference operator (*):

 *ptr.





  C Program to Print Array Elements Using Pointers:


#include<stdio.h>

int main()

{

int arr[100],i,no;

int *ptr=arr;//declare pointer to arr[0]

printf("Enter how many elements you are going to enter:\n");

scanf("%d",&no);

printf("Enter elements:\n");

for(i=0;i<no;i++)

{

scanf("%d",ptr);

/*move pointer to next array element*/

ptr++;

}

       /* Set pointer back to first array element*/

ptr=arr;

printf("Array elements are:\n");

{

for(i=0;i<no;i++)

{

//print pointed values

printf("arr[%d]=%d\n",i,*ptr);

/*move pointer to next array element*/

ptr++;

}

}

return 0;

}


Above program shows the following output:


C Program to Print Array Elements Using Pointers

No comments:

Post a Comment

If you have any doubts, please discuss here...👇