The user has to input 10 values and that you should display the largest value and its index. I already got the largest value using for loop..
largest = num[0];
for (n = 1; n < 10; n++) {
if (largest < num[n])
largest = num[n];
}
but I don't know how to get its index. I've tried googling it but they are in java (PS I'm only a beginner)
Instead of storing the largest value, just store the index:
size_t index_of_max = 0;
for(size_t n = 1; n < 10; n++) {
if(numbers[index_of_max] < numbers[n]) {
index_of_max = n;
}
}
Also, just a small stylistic note: always use braces for if
s, even if they're one statement. It's good practice that can avoid bugs (and not doing it has been the cause of a lot of security problems).
Always index starts from 0. try this i hope this may help you out.
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.