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

8. (5 points) Write a function alternates (1st) that returns True if the list of

ID: 663348 • Letter: 8

Question

8. (5 points) Write a function alternates (1st) that returns True if the list of integers 1st alternates between even and odd numbers (either [even, odd, even, odd, or [odd, even, odd, even, ...]), and False otherwise. For example: ? alternates ( [3 , 2, 5] ) and alternates ( [4 , 7, 2] ) should both return True. ? alternates ([5 , 8, 6, 7] ) should return False because 8 and 6 are both even, and they are next to each other in the list. ? alternates ([3 , 7, 8, 1] ) should return False because 3 and 7 are both odd, and they are next to each other in the list. You may assume that the list has at least 2 elements. Use a loop. Hint: You may find it helpful to compare (1st [i ] % 2) to (1st [i+1] % 2).

Explanation / Answer

// File name Alternates.c

#include<stdio.h>

int n; // size of list

// desired function alternates(lst)
bool alternates(int *lst)
{
   int count=1; // counter
  
   if(lst[0]%2==0) // checks for first number
   {
       for(int i=1;i<n;i++)
       {
           if(i%2==0&&lst[i]%2==0)
           {
               count++;
           }
           else if(i%2!=0&&lst[i]%2!=0)
           {
               count++;
           }
           else
           break;
       }
   }
   else
   {
       for(int i=1;i<n;i++)
       {
           if(i%2==0&&lst[i]%2!=0)
           {
               count++;
           }
           else if(i%2!=0&&lst[i]%2==0)
           {
               count++;
           }
           else
           break;
       }
      
   }
  
   if(count==n)
   return 1;
   else
   return 0;
}


int main()
{

   printf("enter the number of element in the list: ");
   scanf("%d",&n);
   int lst[n];
   printf(" enter the elements: ");
   for(int i=0;i<n;i++)
   {
       scanf("%d",&lst[i]);
   }
  
   if(alternates(lst))
   {
       printf("True");
   }
   else
   printf("False");
}

Outputs:

1.

enter the number of element in the list: 3

enter the elements: 3 2 5

true

//////////////////////////////////////

output 2.

enter the number of element in the list: 5

enter the elements: 1 2 3 4 5

true

//////////////////////////////////////

output 2.

enter the number of element in the list: 10

enter the elements: 1 2 3 4 5 6 7 8 8 9

false

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote