Can only be done in stdio.h. We also must use user-defined functions and can onl
ID: 3687789 • Letter: C
Question
Can only be done in stdio.h. We also must use user-defined functions and can only use material through chapter 8 of the book Computer Science: A structured approach to C by Forouzan and Gilberg
Problem: Given an integer as a starting value, identify the next thirty prime numbers that are greater than or equal to the input value. The results will be stored in a thirty-element array and must be displayed on two separate lines, those at even-indexes first and odd-indexes second.
Example Execution #1:
Enter starting value: 23
Even-index elements: 23 31 41 47 59 67 73 83 97 103 109 127 137 149 157
Odd-index elements: 29 37 43 53 61 71 79 89 101 107 113 131 139 151 163
Example Execution #2:
Enter starting value: 377
Even-index elements: 379 389 401 419 431 439 449 461 467 487 499 509 523 547 563
Odd-index elements: 383 397 409 421 433 443 457 463 479 491 503 521 541 557 569
Example Execution #3:
Enter starting value: 0
Even-index elements: 1 3 7 13 19 29 37 43 53 61 71 79 89 101 107
Odd-index elements: 2 5 11 17 23 31 41 47 59 67 73 83 97 103 109
Example Execution #4:
Enter starting value: -4
Error! Non-negative values only!!!
Enter starting value: -5
Error! Non-negative values only!!!
Enter starting value: 91
Even-index elements: 97 103 109 127 137 149 157 167 179 191 197 211 227 233 241
Odd-index elements: 101 107 113 131 139 151 163 173 181 193 199 223 229 239 251
Explanation / Answer
#include<stdio.h>
int main()
{
int n,array[30],i,k=0,flag=0;
//input starting value from user
printf("enter starting value ");
scanf("%d",&n);
//check if input value is negative or not
while(n<0)
{
printf("error! enter non-negative values only!! ");
scanf("%d",&n);
}
//run while loop till array gets 30 values
while(k<=30)
{
//check if n is a prime number
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag++;
break;
}
}
if(flag==0 && n!=0)
{
//insert each prime into array
array[k] = n;
k++;
}
n++;
//re-initialize flag to 0
flag=0;
}
//print values at even indices
printf("Even-index elements ");
for(i=0;i<30;i=i+2)
printf("%d ",array[i]);
printf(" ");
//print values at odd indices
printf("Odd-index elements ");
for(i=1;i<30;i=i+2)
printf("%d ",array[i]);
printf(" ");
return 0;
}