+ 3

good day everyone. pls how can I write a program in c++ to find the largest element in an array of 10 element?

Arrays

8th Mar 2018, 3:10 PM
Victor Nwafor
Victor Nwafor - avatar
9 Answers
+ 3
When you loop through your array, store the first number into a variable (max) that we can use for comparison. In each loop through, check if the current number is greater than the value stored in the 'max' variable. If it is greater, then store that new number in the variable. By making this comparison with each loop through, by the end you'll have the biggest number stored in the variable you created, then you can do as you wish with it. Also, you could create another variable to keep track of the index, then you'll also know exactly which position it is in the array. Keep track of it in the same IF statement that's checking for the max value. That way it only stores the index if it's one of the elements that was considered bigger. If your iteration variable is 'i' then you'd just store the value of 'i' into the index variable you created.
8th Mar 2018, 3:20 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
https://code.sololearn.com/cpbfrF80gp5K/#cpp #include <iostream> using namespace std; int main() { int maxVal = 0; int maxIndex = 0; int valArr[6] = {0, 32, 12, 99, 14, 72}; for(int i = 0; i < 6; ++i){ if(valArr[i] > maxVal){ maxVal = valArr[i]; maxIndex = i; } } cout << "Biggest number in array is " << maxVal << ".\n"; cout << "Biggest number is located at index " << maxIndex << "\n"; return 0; } :::: OUTPUT :::: Biggest number in array is 99. Biggest number is located at index 3
8th Mar 2018, 3:38 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
sort then return last value
8th Mar 2018, 4:12 PM
Moustafa Shahin
Moustafa Shahin - avatar
+ 1
8th Mar 2018, 3:24 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 1
use bubble sort and then print the last value.... that's pretty much it
9th Mar 2018, 7:26 PM
Dwaipayan Dutta
Dwaipayan Dutta - avatar
+ 1
@Dwaipayan Dutta that will be too lengthy
11th Mar 2018, 7:09 AM
S O U ✌ I K
S O U ✌ I K - avatar
0
it's easy first set max to 0 and check by running loop . if any element is greater than max then replace max by that number.
8th Mar 2018, 5:11 PM
S O U ✌ I K
S O U ✌ I K - avatar
0
ik @souvik kar mahapatra but at that moment that only came to my mind 😅
11th Mar 2018, 8:13 AM
Dwaipayan Dutta
Dwaipayan Dutta - avatar
0
thanks to u guys I really learnt a lot
11th Mar 2018, 5:08 PM
Victor Nwafor
Victor Nwafor - avatar