1. Write a recursive function that computes the sum of all numbers from 1 to n,
ID: 3841086 • Letter: 1
Question
1. Write a recursive function that computes the sum of all numbers from 1 to n, where n is given as parameter.
Here is the method header: public static int sum (int n){...}
2. Write a recursive function that finds and returns the minimum value in an array, where the array and its size are given as parameters.
Here is the method header: public static int minValue (int [] data, int size){...}
3. Write a recursive function that reverses the elements in an array, where the array, indices of the first and the last value in the array are given as parameters.
Here is the method header: public static void reverse (int [] data, int start, int end){...}
Explanation / Answer
The 3 functions are given below:
1.
//Sum of first n natural numbers
public static int sum (int n)
{
if(n==0)
return 0;
else
return n+sum(n-1);
}
2.
//Minimum value in an array
public static int minValue (int [] data, int size)
{
int t;
if(size==1)
return data[size-1];
if(data[size-1]<data[size-2])
{
t=data[size-1];
data[size-1]=data[size-2];
data[size-2]=t;
}
return minValue(data,size-1);
}
3.
//Reverse of an array
public static void reverse (int [] data, int start, int end)
{
int t,i;
while(start<end)
{
t=data[start];
data[start]=data[end];
data[end]=t;
reverse(data,++start,--end);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.