Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

How to find subarray with given sum in C

1 Answer

0 votes
#include <stdio.h>
 
void find_sub_array(int arr[], int len, int sum, int *start, int *end) { 
    int current_sum = 0; 
 
    for (int i = 0; i < len; i++) { 
        current_sum = arr[i];  
		for (int j = i + 1; j <= len; j++) {  
            if (current_sum == sum) {  
                *start = i;
				*end = j - 1;
                return;  
            }  
            if (current_sum > sum || j == len)  
                break;  
			current_sum += arr[j];  
        }  
    }  
} 

int main()
{
	int arr[] = {6, 1, 4, -1, 5, -1, 2}; 
    int len = sizeof(arr)/sizeof(arr[0]); 
    int sum = 9, start = 0, end = 0;
   
    find_sub_array(arr, len, sum, &start , &end); 
     
    printf("from index %d to %d\n", start, end); 
 
    return 0;
}

 
/*
run:
 
from index 1 to 4
 
*/

 



answered Jul 19, 2019 by avibootz

Related questions

1 answer 108 views
1 answer 113 views
1 answer 129 views
1 answer 131 views
131 views asked Jul 20, 2019 by avibootz
1 answer 133 views
1 answer 102 views
102 views asked Jul 20, 2019 by avibootz
...