Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

c++ find largest number in array

#include <iostream>

int largestNumber(int nVariables, int numbers[]) //pass number of variables and number array
{
    int largest = numbers[0]; //initiate largest as the number at index 0
    
    for (int i = 0; i <= nVariables; i++) { //for loop to iterate through the numbers array that is nVariables long
        largest = (largest<numbers[i]?numbers[i]:largest);
      	//^ternary operator same as:
      	/*
        	if(largest < numbers[i]){
            	largest = numbers[i]; //sets largest as numbers[current iteration of i]
            }
            else{
            	largest = largest; // stays same
            }
        */
    }
    
    return largest;
}

int main()
{
    int nOfVariables;
    std::cout << "Input number of variables: ";
    std::cin >> nOfVariables;
    
    int variables[nOfVariables - 1];
    
    for (int i = 0; i < nOfVariables; i++) {
        std::cout << "Enter Variable #" << i + 1 << ": ";
        std::cin >> variables[i];
    }
    std::cout << std::endl;
    
    std::cout << std::endl << largestNumber(nOfVariables, variables) << std::endl;
}
 
PREVIOUS NEXT
Tagged: #find #largest #number #array
ADD COMMENT
Topic
Name
2+1 =