Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming in C 3. Define an array f= [11, -23, 34, -8, -10, 18, 29], using cal

ID: 3728391 • Letter: P

Question

Programming in C

3. Define an array f= [11, -23, 34, -8, -10, 18, 29], using call by-reference (that is, use of pointers), to pass the array to a function named: Summation .

In main: define array, pass array, print out the array and the result returned from Summation on screen.

In function : Summation ...

1) take array and size from main

2) sum each element according to the following rules

3) sum each element according to the following rules:

- if the value of f(i) is POSITIVE , add 3*f(i) to the sum

- if the value of f(i) is NEGATIVE, add -2*f(i) to the sum

4) return the final value of sum to main

Note: You MUST use call-by-reference to call functions

Explanation / Answer

Code:

#include <stdio.h>
# include <stdlib.h>

//summation function is called by reference
//arr represent first element in f
//returns the sum value to main
int summation(int *arr, int *len){
int sum=0 ;
int l = *len;

printf(" Value of array are :");
for(int i = 0; i<l; i++){
printf(" %d ",*arr);//display the array element

if(*arr>0)//if positive
sum = sum+3*(*arr);
if(*arr<0)//if negative
sum = sum-2*(*arr);
arr++;//access next array element

}
return sum;//returns the sum
}

int main()
{
int f[]={11,-23,34,-8,-10,18,29};//initialise the array variable
int n = sizeof(f)/sizeof(int);//find the length of the array
int sum = summation(f,&n);//calls the function summation by reference
printf(" The sum of the array elements : %d",sum);
  
}

Sample output:

Value of array are : 11 -23 34 -8 -10 18 29
The sum of the array elements : 358
RUN SUCCESSFUL (total time: 168ms)