(1-D Array)
© Manzur Ashraf
Objective:
Learn how to use one-dimensional arrays with function.
Basic Concepts :
How to use
individual array elements as parameters in function ?
:
q This is similar
to passing simple arguments
q The formal
parameter should be a simple variable
q The actual
parameter should be the array name followed by the particular index in []
Solved Example# 1:
/* reads a 1-D
array and prints the sum of
even and odd numbers */
#include <stdio.h>
#define SIZE 4
/* determines if
an element is odd */
int
odd(int num)
{
int
isodd;
isodd
= (num%2==1);
return isodd;
}
int
main()
{
int
x[SIZE], i, oddsum=0, evensum=0;
printf("Enter %d integer values :", SIZE);
for (i=0; i<SIZE; i++)
{
scanf("%d",
&x[i]);
}
for (i=0; i<SIZE; i++)
{
if (odd(x[i]))
oddsum=oddsum+x[i];
else
evensum=evensum+x[i];
}
printf("The sum of odd elements is : %d\n", oddsum);
printf("The sum of even elements is : %d\n", evensum);
return 0;
}
How to pass
whole array as a parameter in Function ? :
q Unlike simple variables,
array is not passed into a function, but rather its address is passed.
q This is done by
specifying the array name followed by brackets [] (size is not necessary).
q This makes
processing more efficient
q The actual
parameter is the array name (no brackets)
Solved Example#2:
/* reads the grades of students and prints
the average grade.*/
#include <stdio.h>
#define SIZE 30
/* computes the average of elements in an
array */
float average(float list[], int
n)
{ int i;
float sum=0.0;
for (i=0; i<n; i++)
sum+=list[i];
return sum/n;
}
int
main()
{
int
i,n;
float
grades[SIZE];
printf("Enter number of students: ");
scanf(“%d”,&n);
printf("Enter grades for %d students\n", n);
for (i=0; i<n; i++)
scanf("%f", &grades[i]);
printf("The Average grade is %.2f\n", average(grades,
n));
return 0;
}
Programming Exercise:
Problem#1:
Based on Solved
Example#1 , Write an program to find the sum of first
three elements in the array.
Problem#2:
Based on solved
example#2 , Write a program to find largest element in
an array.