In this example, we get sum and average of an array element using pointer. We use pointer to point to the first element of an array then we increment pointer each time we have to add element in an array. Pointer always point to the memory location of the array element. To use array element we use *ptr which represent the value. We have used both style to access array element in this example.
Source Code:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[100], *ptr, i, sum = 0, n;
float avg;
//initializing pointer
ptr = num;
printf("\tArray Manupulation using Pinter\n");
printf("--------------------------------------------------\n");
printf("Enter the number of integer : ");
scanf("%d", &n);
//assigining value to array using pointer
printf("Enter Number : ");
for(i = 0; i < n; i++)
{
scanf("%d", ptr);
//adding entered array element
sum += *ptr; // *ptr point to the value
ptr++;
}
avg = (float) sum / n;
printf("\nDisplay Array Element using Normal Method\n");
for(i = 0; i < n; i++)
{
printf("%4d", num[i]);
}
printf("\nDisplay Array Element using Pointer\n");
//moving to first location of array
ptr = num; // you can also do, ptr = ptr - n;
for(i = 0; i < n; i++)
{
printf("%4d", *ptr);
ptr++;
}
printf("\nSum of Array Element : %d", sum);
printf("\nAverage of Array Element : %f", avg);
getch();
}
#include <stdio.h>
#include <conio.h>
int main()
{
int num[100], *ptr, i, sum = 0, n;
float avg;
//initializing pointer
ptr = num;
printf("\tArray Manupulation using Pinter\n");
printf("--------------------------------------------------\n");
printf("Enter the number of integer : ");
scanf("%d", &n);
//assigining value to array using pointer
printf("Enter Number : ");
for(i = 0; i < n; i++)
{
scanf("%d", ptr);
//adding entered array element
sum += *ptr; // *ptr point to the value
ptr++;
}
avg = (float) sum / n;
printf("\nDisplay Array Element using Normal Method\n");
for(i = 0; i < n; i++)
{
printf("%4d", num[i]);
}
printf("\nDisplay Array Element using Pointer\n");
//moving to first location of array
ptr = num; // you can also do, ptr = ptr - n;
for(i = 0; i < n; i++)
{
printf("%4d", *ptr);
ptr++;
}
printf("\nSum of Array Element : %d", sum);
printf("\nAverage of Array Element : %f", avg);
getch();
}
Output:
No comments:
Post a Comment