#6 | Pointers | Write a Program to store n Elements in an array and print them using Pointers

 

YouTube Video :- 



Question :- 

Write a Program to store n elements in an array and print the elements using pointers

Code :-


// 6. Write a program to store n elements in an array and print the
//elements using pointer.

#include<stdio.h>

void main()
{
    // declare array and pointer variable
    int a[5],i;
    int *p;

    // collect values from user and store them in an array

    for (i = 0 ; i < 5 ; i++)
    {
        printf("\n Enter Number :- ");
        scanf("%d",&a[i]);
    }

    // assign the address of array's first number

    p = &a[0];

    // print values of array

    printf("\n\nPrinting Values of array a\n");

    for (i = 0 ; i < 5 ; i++)
    {
        printf("\n a[%d] = %d",i,*p);
        p++;
    }
}


Description :-

  • In This Program our query is to store n Elements is an array using pointers and also print them.
  • In Previous Practical Videos we learn that how to store memory address of any variables and print them
  • Now we have to store memory address in an array and print them.
  • For that, First we required one integer array to store some values.
  • Also we have to declare one extra variable to run a loop, so that we don't have to write printf and scanf statements .
  • Then we will declare one pointer variable to store memory address.
  • Using for loop or any other loop we will assign some values to the intger array.
  • After assigning values to the array we will assign the memory address of first element of array,
    • for ex. pointer variable p = array a[0] (value at 0th or first index)
  • We don't have to assign addresses of all elements of array, only first element is required for that.
  • Now using for loop again, we will print the values of array but now we will print them using pointer variable.
  • In for loop, we will increment the address of pointer variable so that it will move to the next element of array.

! Thank You For Visiting !

Comments

Popular posts from this blog

#9 | Pointer | Write a program to count vowels and consonants in string using pointer

#5 | Pointers | Find Maximum Number Using Pointers | #comptech #prathamrathod