ARRAYS USING FUNCTIONS-2
Example.2:
Write a C program to pass an array containing age of person to a function. This function should find
average age and display the average age in main function.
#include <stdio.h>
float average(float a[]);
int main()
float avg, c[]={23.4, 55, 22.6, 3, 40.5, 18};
avg=average(c); /* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
return 0;
float average(float a[])
int i;
float avg, sum=0.0;
for(i=0;i<6;++i)
sum+=a[i];
avg =(sum/6);
return avg;
}
Output
Average age= 27.08
***************************************************
Solved Example: Array Program
1. Write a program to find the largest of n numbers and its location in an array.
#include <stdio.h>
#include<conio.h>
void main()
int array[100], maximum, size, c, location = 1;
clrscr();
printf("Enter the number of elements in array\n");
scanf("%d", &size);
printf("Enter %d integers\n", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
maximum = array[0];
for (c = 1; c < size; c++)
if (array[c] > maximum)
maximum = array[c];
location = c+1;
}
printf("Maximum element is present at location %d and it's value is %d.\n", location, maximum);
getch();
Output:
Enter the number of elements in array
Enter 5 integers
Maximum element is present at location 4 and it's value is 9
2.Write a program to enter n number of digits. Form a number using these digits.
# include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
int number=0,digit[10], numofdigits,i;
clrscr();
printf(“\n Enter the number of digits:”);
scanf(“%d”, &numofdigits);
for(i=0;i<numofdigits;i++)
{
printf(“\n Enter the %d th digit:”, i);
scanf(“%d”,&digit[i]);
i=0;
while(i<numofdigits)
number= number + digit[i]* pow(10,i)
i++;
printf(“\n The number is : %d”,number);
getch();
Output:
Enter the number of digits: 3
Enter the 0th digit: 5
Enter the 1th digit: 4
Enter the 2th digit: 3
The number is: 543