Write a Scheme function sumEven that takes as an argument a list of integers L,
ID: 3810219 • Letter: W
Question
Write a Scheme function sumEven that takes as an argument a list of integers L, and returns th e summation of the even number s only in L. For example, (sumEven '(3 4 5 2 6 8 2)) => 22 (sumEven '(3 1 8)) => 8 (sumEven '(3 1 7 15)) => 0 (sumEven '()) => 0 (sumEven '(6 2 30)) => 38 2. Write a Scheme function divisibleByN that takes as an argument an integer n and a list of integers L, and returns a list of all eleme nts in L that are divisible b y n . For example, (divisibleByN '3 '(5 9 27 14)) => (9 27) (divisibleByN '4 '(15 6)) => () (divisibleByN '7 '()) => () (divisibleByN '5 '(40 40 40 3 10 50)) => (40 40 10 50) 3. Write a Scheme function swap that takes two atoms and a list as parameters and returns a li st identical to the parameter list except all occurrences of the first given at om in the list are replaced with the second given atom and vice versa. For example (swap '1 '2 '(1 2 3 1)) => (2 1 3 2) (swap 'a 'b '(c a m b t a)) => (c b m a t b) (swap 'a 'b '(c d e)) => (c d e) (swap 'e 'w '(c d e)) => (c d w) (swap 'w 'e '(c d e)) => (c d w) (swap 'a 'b '()) => ()
Explanation / Answer
Problem Statement 1 :
int sumEven(int arr[],int len)
{
int i,sum=0;
for(i=0;i<len;i++)
{
if(arr[i]%2==0) // Condition to check if number is even or not
sum= sum+arr[i]; // add to summ variable if number is even
}
return sum; // Return the sum
}
Problem Statement 2:
int *divisibleByN(int N,int p[],int len)
{
int *ptr,i;
ptr=&p[0]; // Pointer to keep the track of number divisble by N
for(i=0;i<len;i++)
{
if(p[i]%N==0)
{
*ptr = p[i]; // Change the array if it is divisble by N
ptr++;
}
}
*ptr = -9999; // -9999 to signify the end of array
return &(p[0]);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.