Calculate Sum of all Elements of an Array using Pointers as
Arguments
#include
#include
void main()
{
static int array[5] = { 200, 400, 600, 800, 1000 };
int sum;
int addnum(int *ptr);
sum = addnum(array);
printf("Sum of all array elements = %5d\n", sum);
}
int addnum(int *ptr)
{
int index, total = 0;
for (index = 0; index < 5; index++)
{
total += *(ptr + index);
}
return(total);
getch();
}
Output
Sum of all array elements = 3000
Accept an Array & Swap Elements using Pointers
#include
#include
void swap34(float *ptr1, float *ptr2);
void main()
{
float x[10];
int i, n;
clrscr();
printf("How many Elements...\n");
scanf("%d", &n);
printf("Enter Elements one by one\n");
for (i = 0; i < n; i++)
{
scanf("%f", x + i);
}
swap34(x + 2, x + 3);
printf("\nResultant Array...\n");
for (i = 0; i < n; i++)
{
printf("x[%d] = %f\n", i, x[i]);
}
}
void swap34(float *ptr1, float *ptr2 )
{
float temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
getch();
}
Output
How many Elements...
4
Enter Elements one by one
23
67
45
15
Resultant Array...
x[0] = 23.000000
x[1] = 67.000000
x[2] = 15.000000
x[3] = 45.000000
No comments:
Post a Comment