Skip to main content
Engineering LibreTexts

9.4: Finding a Specific Member of an Array

  • Page ID
    29087
  • Given an array, find first and last elements of it.

    In C++, we can use sizeof operator to find number of elements in an array. Notice we have to calculate the size based on the entire size of memory taken up by the array divided by the sizeof one element of the array.

    // C++ Program to print first and last element in an array 
    #include <iostream> 
    using namespace std; 
    int main() 
    { 
    	int myArr[] = { 4, 5, 7, 13, 25, 65, 98 }; 
    	int first, last, numberOf; 
    	
    	// Calculate how many elements are in the array
    	numberOf = sizeof(myArr) / sizeof(myArr[0]); 
    	
    	first = myArr[0]; 
    	// use [n-1] becuse arrays count from 0
    	last = myArr[n - 1]; 
    	cout << "First element: " << first << endl; 
    	cout << "Last element: " << last << endl; 
    	return 0; 
    }     
    

    This is pretty simple...and the output is:

    First element: 4
    Last element: 98
    

     We could have made the code simpler by coding the cout statements as:

    cout << "First element: " << myArr[0] << endl;
    cout << "Last element: " << myArr[n - 1] << endl;

    There is no need to use other variables...but it was an example of how to access elements of the array.

    A little more complex code here as an example of how to access array elements.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int newArr[] = { 74, 5, 37, 13, 2, 15, 9 };
       int low, arrSize = sizeof(newArr) / sizeof(newArr[0]);
    
       // Assign the first element to the variable low
       low = newArr[0];
       
       // Loop over every element in the array
       for(int index = 0; index < arrSize; index++)
       {
          // If the current array element (newArr[index]) is less than temp
          if(low > newArr[index])
          {
             // Then we assign that current array element to be the new lowest
             low = newArr[index];
          }
       }
       
       cout << "Smallest Element is: " << low << endl;
       return 0;
    }
    

    The smallest number is found when we look at every elements and simply track the smallest value.

    Smallest Element is: 2
    

     Adapted from:
    "Get first and last elements from Array and Vector in CPP" by ishwarya.27Geeks for Geeks