This question already has answers here:
calculate the sum of all element in a double array
(12 answers)
Closed 9 years ago.
Hello I'm learning recursion in C and I am trying to find the sum of the elements.
This is my main:
int main()
{
int arr[] = {1,2,3,4,5};
int sum;
sum = arr_sum(arr,4);
printf("\nsum is:%d",sum);
return 0;
}
And my recursive function:
//n is the last index of the array
int arr_sum( int arr[], int n )
{ // must be recursive
int sum = 0;
//base case:
if (n < 0) {
return sum;
} else{
sum = sum + arr[n];
}
//make problem smaller
arr_sum(arr,n-1);
}
The output is:
sum is :0
Try this for your recursive function:
int arr_sum( int arr[], int n ) {
if (n < 0) {
//base case:
return 0;
} else{
return arr[n] + arr_sum(arr, n-1);
}
}
you need to add your n-th case to your n-1 case until you get to the base case.
You could add a third argument, which is the running total calculated so far (start it as 0).
When you recursively call the function, pass the running total.
int arr_sum( int arr[], int n, int sum )
{ // must be recursive
if (n < 0) {
return sum;
}
sum += arr[n];
return arr_sum(arr, --n, sum);
}
Alternatively, you change it to not require passing the sum variable like so.
int arr_sum( int arr[], int n )
{ // must be recursive
if (n < 0) {
return sum;
}
return arr[n] + arr_sum(arr, n - 1);
}
In this way, it is similar to finding a number in the Fibonacci sequence.
Try this modified version of your program and work out on pen/paper the way it flows through. Hope it helps.
#include <stdio.h>
//n is the last index of the array
int
arr_sum(int arr[], int n )
{
//base case:
if (n == 0) {
return arr[0];
}
return (arr[n] + arr_sum(arr,n-1));
}
int
main(void)
{
int arr[] = {1,2,3,4,5};
int sum;
sum = arr_sum(arr,4);
printf("\nsum is:%d\n",sum);
return 0;
}
You are not returning any thing from else part.You also have return from that.
like.
return arr_sum(arr,n-1)+arr[n];
so this call the function again and again until n will be zero.
you got my point?
The problem with your code is that everytime when your recursive function calls, it initializes the sum as 0.
Declare sum outside the recursive method that will solve the problem.
Related
I'm trying to create a recursive function to reverse digits of a number in C. This is what I've written. It works fine when used one time but when used multiple times it keeps piling the numbers together. I think the problem can be sorted if the sum is initialized to zero each time the function is called but I'm unable to do it. I've tried declaring sum=0 as a global variable but the result was the same.
Input-
12
23
34
45
Output
21
2132
213243
21324354
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int digit_reverse(int N)
{
int rem;
static int sum=0;
if(N>0)
{
rem=N%10;
sum=sum*10+rem;
digit_reverse(N/10);
}
else
return 0;
return sum;
}
int main()
{
int a[25],i;
for(i=0;i<4;i++)
{
scanf("%d", &a[i]);
}
printf("Output\n");
for(i=0;i<4;i++)
{
printf("%d\n",digit_reverse(a[i]));
}
}
Maybe you can write your function without using static variables:
void _digit_reverse(int N, int *sum)
{
int rem;
if (N > 0)
{
rem = N % 10;
*sum = *sum * 10 + rem;
_digit_reverse(N / 10, sum);
}
}
int digit_reverse(int N)
{
int sum = 0;
_digit_reverse(N, &sum);
return sum;
}
Or take the sum outside:
int sum = 0;
int digit_reverse(int N)
{
int rem;
if (N > 0)
{
rem = N % 10;
sum = sum * 10 + rem;
digit_reverse(N / 10);
}
else
return 0;
return sum;
}
int main()
{
int a[25], i;
for (i = 0; i < 4; i++)
{
scanf("%d", &a[i]);
}
printf("Output\n");
for (i = 0; i < 4; i++)
{
sum = 0;
printf("%d\n", digit_reverse(a[i]));
}
}
I believe that the static variable gets initialized only once. This is the problem with your approach.
dude everything looks fine to me if the code do not needs to be reusable I can think of several solutions but keep in mind static and or global variables are not best practices unless necessarily required to.
secondly change your
// from static int sum = 0;
// to
static long sum = 0;
// or
static long long sum = 0;
the reason for this error is value overflow
an integer cannot have more than 4 bytes of data in this specific case you definitly needs more.
I have a task to write a recursive function to print all the numbers of an array whose indexes are prime numbers.
Actually, I can understand recursion, but I can't get in for void functions.
This is my code and I can't understand how to write if statement correctly to print it.
#include <stdio.h>
void prime(int arr[], int n)
{
if (n == 0) return; //there are no elements
for (int i = 2; i <= n / i; ++i)
{
if (n % i == 0)
break;
else
printf("Number %d has a prime index %d.", arr[n], n);
}
prime(arr + 1, n - 1);
}
int main()
{
int arr[100];
for (int i = 0; i < 100; ++i)
{
arr[i] = i;
}
prime(arr[100], 100);
}
While passing arrays we always pass its name and not its name
with size.
If we pass arr[100], it actually passes the element at 100th index which is out of bounds (as array will start at 0 and end at index 99).
You can refer here for more details.
prime(arr, 100);
I wanted to write a simple program to calculate the factorial of a given number using C. Yet my code seems to have some logical error that I can't detect. Would be glad for help.
int fact(int n);
int main(void)
{
int num = get_int("Type number: ");
printf("%i\n", fact(num));
}
//define function
int fact(int n)
{
for (int i = 1; i < n; i++)
{
n *= i;
}
return n;
}
You can't use n to calculate.
You have to save total with another variable
int fact(int n)
{
int product = 1;
for (int i = 1; i <= n; i++)
{
product = product * i;
}
return product;
}
In mathematics, the factorial of a positive integer N, denoted by N!, is the product of all positive integers less than or equal to N:
N!=N*(N-1)*(N-2)*(N-3)*.......*1
+-------------------------+
notice that this is: (N-1)! <==> So, N! = N*(N-1)!
we can use these mathematical facts to implement the factorial function in 2 different forms, recursive and iterative approaches:
recursive approach
size_t rec_factorial(size_t n)
{
/*Base case or stopping condition*/
if(n==0)
{
/* 0! = 1 */
return 1;
}
/*n! = n * (n-1)!*/
return n * rec_factorial(n-1);
}
iterative approach
size_t factorial(size_t n)
{
size_t j = 1;
size_t result = 1;
while(j <= n){
result *= j; /* n!=n*(n-1)*(n-2)*(n-3)*....1 */
++j;
}
return result;
}
i'm trying to write a program that print the prime factors of a given number ,but i need to print them from the biggest factor to the smallest, for example:
for the input 180 the output will be: 5*3*3*2*2,
any suggestions? here is what i got for now :
#include<stdio.h>
void print_fact(int n)
{
if (n==1)
return;
int num=2;
while (n%num != 0)
num++;
printf("*%d",num);
print_fact (n/num);
}
int main ()
{
int n;
printf("please insert a number \n");
scanf("%d",&n);
print_fact(n);
}
for this code the output is :
*2*2*3*3*5
You can simply print the output after the recursive call returns. You need to slightly modify how you display the *, which I leave to you.
#include<stdio.h>
void print_fact(int n)
{
if (n==1)
return;
int num=2;
while (n%num != 0)
num++;
// printf("*%d",num); // remove from here
print_fact (n/num);
printf("%d ",num); // put here
}
int main ()
{
int n;
printf("please insert a number \n");
scanf("%d",&n);
print_fact(n);
}
The output this gives on input 180 is:
5 3 3 2 2
Aside, there are much more efficient ways of actually finding the numbers though.
It is much faster to find them in the ascending order, mathematically speaking. Much, much faster.
The solution, if you don't want to bother yourself with dynamic arrays, is recursion. Find the lowest prime factor, recurse on the divided out number (num /= fac), and then print the earlier found factor, which will thus appear last.
to change the order in which they are printed, you could put the printf statement after the print_fact statement. To get rid of thew leading *, you would probably want to store the results and display them after computation
well, i'm trying to optimize my algorithm
this is my code for now:
functions code
#include "prime_func.h"
int divisors(int x) /* Function To set the maximum size of the future array,
Since there is no way to find the number of primary factors
without decomposing it into factors,
we will take the number of total number divisors
(which can not be greater than the number of primary factors) */
{
int limit = x;
int numberOfDivisors = 0;
if (x == 1) return 1;
for (int i = 1; i < limit; ++i) {
if (x % i == 0) {
limit = x / i;
if (limit != i) {
numberOfDivisors++;
}
numberOfDivisors++;
}
}
return numberOfDivisors;
}
void find_fact(int n, int *arr, int size, int i) //func to find the factors and apply them in allocated array
{
int num = 2;
if (n < 2)
{
printf("error\n");
return;
}
while (n%num != 0)
num++;
arr[i++] = num;
find_fact(n / num, arr, size, i);
}
void print_fact(int *arr, int size) // func to print the array in reverse
{
int i = 0;
int first;
first = FirstNumToPrint(arr, size);
for (i = first; i>0; i--)
printf("%d*", arr[i]);
printf("%d", arr[0]);
}
int FirstNumToPrint(int *arr, int size) // func to find the first number to print (largest prime factor)
{
int i;
for (i = 0; i < size; i++)
if (arr[i] == 0)
return i - 1;
}
int first_prime(int num) // for now i'm not using this func
{
for (int i = 2; i<sqrt(num); i++)
{
if (num%i == 0)
{
if (isprime(i));
return(i);
}
}
}
bool isprime(int prime) // for now i'm not using this func
{
for (int i = 2; i<sqrt(prime); i++)
{
if (prime%i == 0)
return(false);
}
return(true);
}
main code
#include "prime_func.h"
int main()
{
int n,i=0; // first var for input, seconde for index
int *arr; // array for saving the factors
int size;//size of the array
printf("please insert a number \n");// asking the user for input
scanf("%d", &n);
size = divisors(n); //set the max size
arr = (int *)calloc(size,sizeof(int)); //allocate the array
if (arr == NULL) // if the allocation failed
{
printf("error\n");
return 0;
}
find_fact(n, arr,size,i);// call the func
print_fact(arr,size); //print the result
free(arr); // free memo
}
#WillNess #GoodDeeds #mcslane
A person has to cross a road and with each step he either gains some energy or loses some (this info is provided as an array) . Find out the min amount of energy he should start with so that at any level his energy is not less than 1.
But the below program always prints "Error" not the number.
#include<stdio.h>
#include<limits.h>
int main(){
int a[]={10,20,20};
int n = sizeof(a)/sizeof(a[0]);
int ans = calldistance(a,n);
if(ans==-1)
printf("error");
else
printf("%d",ans);
return 0;
}
int calldistance(int a[],int n){
int i,min=INT_MAX;
for(i=0;i<n;i++){
min+=a[i];
if(min<1) return -1;
else continue;
}
return min;
}
You always return -1 because you call it quits if the array is one where the value isn't trivial.
You need to keep track of partial sums of the array. In particular you need to know when the partial sum is at its lowest negative value (or zero). The absolute value of this + 1 is your answer.
If the sum is never bellow 1, then your answer is just 1.
int calldistance(const int a[], const int n) {
int min_partial_sum = 0;
int partial_sum = 0;
for(int i = 0; i < n; ++i) {
partial_sum += a[i];
if(min_partial_sum > partial_sum)
min_partial_sum = partial_sum;
}
if(min_partial_sum < 0)
return -min_partial_sum + 1;
return 1;
}
int calldistance(int a[],int n){
int i,min=INT_MAX;
for(i=0;i<n;i++){
min+=a[i];
if(min<1) return -1;
else continue;
}
return min;
}
In the above function you are initializing min=INT_MAX and if you add even 1, it will return a negative number. That's the why you are always getting error as answer.