Array traversal implementation in C
As we know earlier, array is a collection of similar data elements. Let us perform some array traversal implementations in C language.
It contains some of the programs listed as follows.
- · Sum of array elements
- · Search an element in an array
- · Count the number of elements in the array
- · Find the maximum and minimum value in the array
Sum of array elements:
This C
program calculates the sum of the array elements.
C Program:
#include <stdio.h>
int main() {
int a[10];
int i=0,n,sum=0;
printf("Enter
the number of elements:");
scanf("%d",&n);
printf("Enter
the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(int i=0;
i<5; i++)
{
sum += a[i];
}
printf("The
sum of the array elements are:");
printf("%d\n", sum);
return 0;
}
Output:
Enter the number of elements:5
Enter the elements:
2
3
14
67
19
The sum of the array elements are:105
Search an element in an array
This
program deals with searching an element in the array. it reads an array as
input. It gets the element to be searched in the array. if the element is
found, it returns the position. Otherwise, it returns the not found message.
#include <stdio.h>
int main() {
int a[10];
int
i=0,n,key,found = 0;
printf("Enter
the number of elements:");
scanf("%d",&n);
printf("Enter
the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter
the element to find:");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(a[i] == key)
{
found = 1;
printf("The
element is found at:%d",i+1);
break;
}
}
if(found==0)
printf("The
data is not found");
return 0;
}
Output:
Enter the number of elements:5
Enter the elements:23 34 45 56 67
Enter the element to find:45
The element is found at:3
Yes. The element is found in position. Hope, you understood
the programs in array traversal. This is the first part. Second part is coming
soon!!!
Comments
Post a Comment