Home > Software engineering >  How to get all the elements of an array that are divisible with 3 and then sum them thogether?
How to get all the elements of an array that are divisible with 3 and then sum them thogether?

Time:10-16

I dont know how to get the code to print out the elements that are divisable with 3 and the print out the sum of those elements , can someone help me do it , thanks for your time!

Code:

    #include <stdio.h>

int sum(int arr[]){
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 0;
    for (int y=0;y<n;y  ){
        sum  = arr[y];
        printf("%d",sum);
    }
}

int main() {
    int F[5] = {1,3,5,9,8};
    int s = 0;
     for (int i=0;i<5;i  ){
       if (F[i]%3 == 0) {
           int diviz[] = {F[i]};
           printf("%d\n",diviz[0]);
           sum(diviz);
       }
    }
    return 0;
}

Expected Output:

3
9
12

Actual Output:

3
349
910

Idk how to solve this issue

CodePudding user response:

This function declaration

int sum(int arr[]){

is adjusted by the compiler to the declaration

int sum(int *arr){

That is within the function the variable arr has the pointer type int *.

Thus the declaration with sizeof expression

int n = sizeof(arr) / sizeof(arr[0]);

is equivalent to

int n = sizeof( int * ) / sizeof( int );

and yields either 2 or 1 depending on the size of the pointer.

On the other hand, this call of the function

   int diviz[] = {F[i]};
   printf("%d\n",diviz[0]);
   sum(diviz);

in any case does not make a great sense because instead of passing the original array you are passing an array that contains only one element. And the for loop in main is redundant.

You need explicitly to pass the number of elements in the array.

So the function can look like

long long int sum( const int arr[], size_t n, int divisor )
{
    long long int sum = 0;

    for ( size_t i = 0; i < n; i   )
    {
        if ( arr[i] % divisor == 0 ) sum  = arr[i];
    }

    return sum;
}

And the function can be called like

int arr[] = {1,3,5,9,8};
const size_t N = sizeof( arr ) / sizeof( *arr );

int divisor = 3;

printf( "The sum of elements divisible by %d = %lld\n", divisor, sum( arr, N, divisor ) );

The function will be more safer if to add a check whether divisor is passed equal to 0 as for example

long long int sum( const int arr[], size_t n, int divisor )
{
    long long int sum = 0;

    if ( divisor != 0 )
    {
        for ( size_t i = 0; i < n; i   )
        {
            if ( arr[i] % divisor == 0 ) sum  = arr[i];
        }
    }

    return sum;
}

CodePudding user response:

int main() {
    int F[5] = {1,3,5,9,8};
    int s = 0;
     for (int i=0;i<5;i  ){
       if (F[i]%3 == 0) {
           s = s   F[i];
           printf("%d",F[i]); 
       }
    }
    printf("%d",s); //print sum total 
    return 0;
}
  • Related