Ashton Stark
Ashton Stark

Reputation: 47

Find the index of the largest element in an array and find elements N indexes to the right and left of that max element

I am writing some c coding involving some array manipulation. I am trying to achieve the following:

  1. With a given input array, create a new_array consisting of only the first 10 elements
  2. Find the index_of_largest element in the new_array
  3. Take the 2 elements to the left of index_of_largest and 3 to the right and put them all in a new_array2
For example if array[15] = {12,25,99,56,44,79,62,11,10,2,1,3,4,5,6}
then new_array[10] = {12,25,99,56,44,79,62,11,10,2}
then new_array2 [6]={12,25,99,56,44,79}

This is my current code:

#include<stdio.h>  
  
  
int main()  
{  
    int a[15]={12,25,99,56,44,79,62,11,10,2,1,3,4,5,6}, arr1[10], arr2[5], i, pos=10, k1 = 0, k2 = 0, max_index, max;  
  
    for(i = 0; i < 10; i++)  
    {  
        if(i < pos)  
            arr1[k1++] = a[i];  //seperate array
        else  
            arr2[k2++] = a[i];  
    }  
  
    printf("\nElements of First Array -> arr1[%d]\n", k1);  
    for(i = 0; i < k1; i++)  
        printf("%d\n", arr1[i]); 

    max  = arr1[0]; //find index of max element
    for (i = 0; i < 10; i++)
    {
        if (arr1[i] > max) {
            max = arr1[i];
            max_index = i;
        }
    }
    printf("Largest element = %d at index %d", max, max_index);

    return 0;
    }

output:

Elements of First Array -> arr1[10]
12
25
99
56
44
79
62
11
10
2
Largest element = 99 at index 2

I am able to separate the initial array (1) am able to find the index of the largest element (2). I am not sure how to solve (3) moving forward from my current point. The largest index will always been in a position in the array so that it will be possible to get the elements to around it. (For example the largest value will not be the first or last index) I also think I should add a condition so that if there are multiple max values, we take the first one that occurs. I will in the future wrap all this in a function call but sorry for the messy code at the moment.

Upvotes: 1

Views: 947

Answers (1)

yano
yano

Reputation: 5265

You're using %f format specifier, this is for floats and doubles. max is an int, you need to use %d or similar:

printf("Largest element = %d at index %d", max, max_index);

For more information on printf format specifiers, see the man page

Upvotes: 2

Related Questions