Click here to Skip to main content
15,029,771 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Anybody help asap !!!
I am unable to calculate the largest index at which the maximum value appears in an array x[n] of n integers.

What I have tried:

int lastMax(int n, int x[n]) {
 if (n<=0) {
     return -1; }
    int max = x[0];
    int maxIndex = 0;
    for (int i = 1;i <n; i++) {
        if (x[i] > max) {
            maxIndex = i;
            max = x[i];
    return maxIndex;

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    scanf("%d", &n);
    int *x = NULL;
    if (n > 0) {
        x = (int *) malloc(n * sizeof(int));
        if (x != NULL) {
            for (int i = 0; i < n; ++i) {
                scanf("%d", &x[i]);
    printf("%d\n", lastMax(n, x));
    if (x != NULL) {
    return 0;
Updated 11-Jan-21 10:30am
k5054 11-Jan-21 15:57pm
In what way does this not work?
Why "Do not modify below this line" ??
I think it would be helpful if you did something like:
int maxIndex = lastMax(n, x);
printf("Max value: x[%d] = %d\n", maxIndex, x[maxIndex]);

But you should probably test that maxIndex is not -1 first.
Shri_hari 11-Jan-21 22:29pm
It calculates the index of largest number but if the largest number is present at more than one position say 2 3 4 4 then I should get output as 3 and not 2.
But it is not doing that part properly ..!

Change the definition of your function to:
int lastMax(int n, int* x) {  // x is a pointer to an array
To add to what Richard has said: the C Language Specification defines that the name of an array variable is a pointer to its first element.
So given this:
int arr[10];

These two statements are equivalent:
int *p1 = arr;

int *p2 = &(arr[0]);

This means that it is legal to treat any pointer to a type as an indexable array of that type - so passing an array to a function is done by declaring the parameter as a pointer, and then using an index within the function to access individual elements;
void PrintArray(int *arr, int n)
   for (int i = 0; i < n; i++)
      printf("%u\n", arr[i]);
Or as a pointer:
void PrintArray(int *arr, int n)
   while(n-- > 0)
      printf("%u\n", *arr++);
In either case, you can hand the array and it's size, and the function will work:
int myArray[10];
PrintArray(myArray, 10);
Shri_hari 11-Jan-21 22:37pm
What you are saying is right.
But how does that solve my problem of not being able to calculate "largest index of largest number in array".
I couldn't understand. Clarify this if possible.
OriginalGriff 12-Jan-21 2:43am
You know how to find the largest value, yes?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900