Gcobani Mkontwana

Gcobani Mkontwana

  • 570
  • 1.9k
  • 407.2k

How to write a return function back?

Sep 1 2022 11:15 PM

HI Team

 

I want to achieve this logic together with my following code,

Given a collection of ten (10) non negative integers and a target value called sum_target:. How do i write a function back to return.?

 

// Solution

// C# code to Find subarray
// with given sum
using System;

class GFG {
	// Returns true if the there is a
	// subarray of arr[] with sum
	// equal to 'sum' otherwise returns
	// false. Also, prints the result
	int subArraySum(int[] arr, int n, int sum)
	{
		int currentSum, i, j;

		// Pick a starting point
		for (i = 0; i < n; i++) {
			currentSum = arr[i];

			// try all subarrays
			// starting with 'i'
			for (j = i + 1; j <= n; j++) {
				if (currentSum == sum) {
					int p = j - 1;
					Console.Write("Sum found between "
								+ "indexes " + i + " and "
								+ p);
					return 1;
				}
				if (currentSum > sum || j == n)
					break;
				currentSum = currentSum + arr[j];
			}
		}

		Console.Write("No subarray found");
		return 0;
	}

	// Driver Code
	public static void Main()
	{
		GFG arraysum = new GFG();
		int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 };
		int n = arr.Length;
		int sum = 23;
		arraysum.subArraySum(arr, n, sum);
	}
}

// This code has been contributed
// by nitin mittal