## Largest number in integer array

Traversing an integer array linearly to find the largest number in the array.

## Learning Objectives

- Integer array initilisation.
- Array traversing.
- Array index concept.
- Array length finding in a dynamic way using the sizeof operator.

## Program Approach

Will assume first member of array at index 0 as maximum. Then all other members will be successively compared and the value of max be changed as soon as new member is higher than the previously set member in the max variable.

## Source Code

## Run Output

## Code Understanding

** int A[]={14,9,11,19,3};**

initialises 5 fixed integer values in the array named A.

**int max=A[0];**

First member is taken into a variable max. Other subsequent members will be compared to this max. Remember that first member is present at the index 0 of the array.

**int len=sizeof(A)/sizeof(A[0]);**

Here we find the length or total number of members in the array by using a dynamic method. The sizeof operator of c++ when applied to whole array gives actual length of array in total number of bytes and sizeof applied on first member will give number of bytes utilized by the first member. In this case numerator will give 20 and denominator will give 4 on most modern operating systems (On some old systems it may give 10 and 2)

**for(int i=1;i<len;i++) ****if(A[i]>max) max=A[i];**

This loop begins with index 1 as first member has already been saved. As each member is traversed it is compared with previous value in max and once the traversal finishes the final value should contain the largest value which is then printed in the next instruction.

## Notes

If you are working on a specific operating system and are sure of the integer size as 4 then this line

**int len=sizeof(A)/sizeof(A[0]);
**can be written as

**int len=sizeof(A)/4;**

while passing arrays to functions the size of array has to be manually passed, then numerator can be picked from the parameter passed to it.

**Suggested Filename(s): **largestinarr.cpp, largest

sunmitra| Created: 4-Dec-2017 | Updated: 8-Dec-2017|