w3resource

C Exercises: Find the maximum for each and every contigious subarray of size k from a given array

C Array: Exercise-94 with Solution

Write a program in C to find the largest element of each and every contiguous subarray of size k from a given array.

Sample Solution:

C Code:

#include<stdio.h> 
  
void contSubArr (int arr1[], int x, int k) 
{ 
    for (int i = x; i <= x+(k-1); i++) 
    { 
        printf("%d ", arr1[i]); 
    } 
}
  
void findMaxFrom (int arr1[], int n, int k) 
{ 
    int j, maxofn,m=0; 
    for (int i = 0; i <= n-k; i++) 
    { 
        maxofn = arr1[i]; 
       
        for (j = 1; j < k; j++) 
        { 
            if (arr1[i+j] > maxofn) 
               maxofn = arr1[i+j]; 
        } 
		contSubArr(arr1, m, k);
        printf("----> %d \n", maxofn);
        m++;		
    } 
}  
  
int main() 
{ 
    int arr1[] = {1, 3, 6, 21, 4, 9, 12, 3, 16, 10}; 
    int n = sizeof(arr1)/sizeof(arr1[0]); 
    int i,k = 4; 
   //------------- print original array ------------------	
	printf("The given array is:  \n");
	for(i = 0; i < n; i++)
		{
			printf("%d  ", arr1[i]);
		}
	printf("\n");
//-----------------------------------------------------------
    printf("The length of each subarray is: %d\n",k);
	printf("The contigious subarray of length %d and their maximum value are: \n",k);
    findMaxFrom(arr1, n, k); 
    return 0; 
}

Sample Output:

The given array is:  
1  3  6  21  4  9  12  3  16  10  
The length of each subarray is: 4
The contigious subarray of length 4 and their maximum value are: 
1 3 6 21 ----> 21 
3 6 21 4 ----> 21 
6 21 4 9 ----> 21 
21 4 9 12 ----> 21 
4 9 12 3 ----> 12 
9 12 3 16 ----> 16 
12 3 16 10 ----> 16

Pictorial Presentation:

C Exercises: Find the maximum for each and every contigious subarray of size k from a given array

Flowchart:

Flowchart: Find the maximum for each and every contigious subarray of size k from a given array

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Write a program in C to rearrange positive and negative numbers alternatively in a given array.
Next: Write a program in C to segregate 0s and 1s in an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - What is the argument for printf that formats a long?

Put an l (lowercased letter L) directly before the specifier.

unsigned long n;
long m;

printf("%lu %ld", n, m);

Ref : https://bit.ly/3dIwfkP