Write a C program to execute and result following problem: Given a data set of u
ID: 3859601 • Letter: W
Question
Write a C program to execute and result following problem:
Given a data set of up to 25 integers, determine if there is a constant value which separates every element.
Display the value when it exists and the data set in sorted order.
Example Execution #1:
Enter up to 25 values or -1 to exit: 10 8 6 4 2 16 14 12 -1
Constant value 2 separates the elements: 2 4 6 8 10 12 14 16
Example Execution #2:
Enter up to 25 values or -1 to exit: 2 4 6 8 10 1 3 5 7 9 -1
Constant value 1 separates the elements: 1 2 3 4 5 6 7 8 9 10
Example Execution #3:
Enter up to 25 values or -1 to exit: 6 16 26 36 31 21 11 -1
Constant value 5 separates the elements: 6 11 16 21 26 31 36
Example Execution #4:
Enter up to 25 values or -1 to exit: 1 2 3 4 5 10 9 8 7 -1
No constant value that separates the elements.
Example Execution #5 (-1 not needed to terminate input when 25 elements are present in the data set):
Enter up to 25 values or -1 to exit: 10 20 30 40 50 60 11 21 31 41 51 1 2 3 4 5 12 13 14
15 16 8 7 6 9 10
No constant value that separates the elements.
Example Execution #6:
Enter up to 25 values or -1 to exit: 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6
5 4 3 2 1 -1
Constant value 1 separates the elements: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21 22 23 24
Example Execution #7:
Enter up to 25 values or -1 to exit: 1 6 12 18 24 -1
No constant value that separates the elements.
Example Execution #8:
Enter up to 25 values or -1 to exit: 6 12 18 24 30 36 42 45 -1
No constant value that separates the elements.
Explanation / Answer
#include<stdio.h>
void main(){
int data[25];
int count;
int i,j;
int diff;
int temp;
count = 0;
printf("Enter up to 25 values or -1 to exit:");
while (count < 25 ) {
scanf("%d", &data[count]);
if (data[count] == -1)
break;
count++;
}
for (i=0; i<count; i++){
for (j=i; j<count; j++){
if (data[i] > data[j]){
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
diff = abs(data[1] - data[0]);
for (i = 2; i<count-1; i++){
if (abs(data[i+1]-data[i]) != diff){
printf("No constant value that separates the elements ");
return;
}
}
printf("Constant value %d separates the elements:",diff);
for (i = 0; i<count; i++){
printf(" %d", data[i]);
}
printf(" ");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.