I have an assignment to write a recursive program that gets an array (lets call it arr1), the size of the array (n), and a value(s). The program will check if there are two numbers in the array so that their summary is s. example if the array is {1,3,2,0,5} and s=7, then the function will print "yes" because 5+2=7. if the array is {1,3,2,0,5} and s=9, then the function will print "no". no summary of a pair is equal to 9.
My algorithm works like this: i calculate the summary of the last spot in the array (arr1[n-1]), with every other spot. if i find a couple that their sum is s, great, print yes and leave. if i dont find, then i do the same, but instead of arr1[n-1] i check arr1[n-2]. i delete the last spot.
Here's my code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void input_array_dyn(int* a, int n);
void rec(int* a,int n, int s);
void main()
{
int n=0,s=0;
int* a;
printf("Enter value S\n");
scanf("%d",&s);
printf("Enter the size of the array\n");
scanf("%d",&n);
a=(int*)calloc(n,sizeof(int));
printf("Enter %d values for the array\n",n);
input_array_dyn(a,n);
rec(a,n,s);
free(a);
getch();
}
void input_array_dyn(int* a,int n)
{
int i=0;
for(i=0;i<n;i++)
scanf("%d",a[i]);
}
void rec(int* a,int n, int s)
{
int i;
if(n==1)
{
printf("There are no 2 number whos summary yields S\n");
return;
}
for(i=0;i<n-1;i++)
{
if(a[n-1]+a[i]==s)
{
printf("There are two numbers that give s\n");
return;
}
}
rec(a,n-1,s);
}
I get an error saying: "Unhandled exception at 0x5846e30e (msvcr100d.dll) in Test.exe: 0xC0000005: Access violation writing location 0x00000000."
also: Does anyone have a better idea for an algorithm to do this? :)