C Exercises: Return the largest span found in the leftmost and rightmost appearances of same value in a given array
C Array: Exercise-98 with Solution
Write a program in C to return the largest span found in the leftmost and rightmost appearances of the same value (values are inclusive) in a given array.
Expected Output:
The given array is:
17 42 19 7 27 24 17 54 73
The span between the same values in the array is: 7
The task is to write a C program that returns the largest span between the leftmost and rightmost appearances of the same value in a given array. The span is defined as the inclusive distance between the first and last occurrences of any value. The program should traverse the array, calculate the spans for all values, and then display the largest span found.
Sample Solution:
C Code:
#include<stdio.h>
// Function to calculate the maximum span between the same values in the array
int maxSpan(int arr1[], int n)
{
int l = n;
if (l > 0)
{
int maxSpanCtr = 1;
// Loop through the array to find the maximum span between same values
for (int i = 0; i < l; i++)
{
for (int j = l - 1; j > i; j--)
{
if (arr1[j] == arr1[i])
{
int count = (j - i) + 1;
if (count > maxSpanCtr)
maxSpanCtr = count;
break;
}
}
}
return maxSpanCtr;
}
else
return 0;
}
int main()
{
int arr1[] = {17, 42, 19, 7, 27, 24, 17, 54, 73};
int arr_size = sizeof(arr1) / sizeof(arr1[0]);
int i = 0;
// Print the original array
printf("The given array is: \n");
for (i = 0; i < arr_size; i++)
{
printf("%d ", arr1[i]);
}
printf("\n");
// Calculate and display the maximum span between same values in the array
printf("The span between the same values in the array is: %d", maxSpan(arr1, arr_size));
return 0;
}
Output:
The given array is: 17 42 19 7 27 24 17 54 73 The span between the same values in the array is: 7
Visual Presentation:
Flowchart:
C Programming Code Editor:
Previous: Write a program in C to find the index of first peak element in a given array.
Next: Write a program in C to check if an array can be splitted in such a position that, the sum of left side of the splitting is equal to the sum of the right side.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/c-programming-exercises/array/c-array-exercise-98.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics