﻿ C : First, last, and middle of an array with odd lengths

# C Exercises: Find the largest value from first, last, and middle elements of a given array of integers of odd length

## C-programming basic algorithm: Exercise-50 with Solution

Write a C program to find the largest value from the first, last, and middle elements of a given array of integers of odd length (at least 1).

C Code:

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

// Function prototype for 'test'
int test(int numbers[], int arr_size);

int main(void){
// Declaration of variables
int arr_size; // Variable to store the size of the array

// Declaration and initialization of three different arrays
int array1[] = {1};
int array2[] = {1,2,9};
int array3[] = {1,2,9,3,3};

// Calculating the size of the first array
arr_size = sizeof(array1)/sizeof(array1);

// Printing the result of 'test' function for the first array
printf("%d",test(array1, arr_size));

// Calculating the size of the second array
arr_size = sizeof(array2)/sizeof(array2);

// Printing the result of 'test' function for the second array
printf("\n%d",test(array2, arr_size));

// Calculating the size of the third array
arr_size = sizeof(array3)/sizeof(array3);

// Printing the result of 'test' function for the third array
printf("\n%d",test(array3, arr_size));
}

// Definition of the 'test' function
int test(int numbers[], int arr_size)
{
// Declaration of variables
int first, middle_ele, last_ele, max_ele;

// Initializing 'first', 'middle_ele', and 'last_ele' with values from the array
first = numbers;
middle_ele = numbers[arr_size / 2];
last_ele = numbers[arr_size - 1];

// Initializing 'max_ele' with the value of 'first'
max_ele = first;

// Checking if 'middle_ele' is greater than 'max_ele'
if (middle_ele > max_ele)
{
max_ele = middle_ele;
}

// Checking if 'last_ele' is greater than 'max_ele'
if (last_ele > max_ele)
{
max_ele = last_ele;
}

// Returning the maximum value
return max_ele;
}
``````

Sample Output:

```1
9
9
```

Pictorial Presentation: Flowchart: C Programming Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿