Fill the else statement which is a line of code and the else if print Fill in th
ID: 3555034 • Letter: F
Question
Fill the else statement which is a line of code and the else if print
Fill in the two missing pieces of the program below. The program keeps track of 6 integer values, each between 0 and 31, inclusive. They are indexed from 0 to 5. Normally you'd just use a 6 element integer array, but as you can see, you're constrained to just the variable "vals", a 32-bit int. All 6 integers may be stored in it, given the constraint on their value range. Think in terms of bit fields. In the input examples, the command "S index val" sets value at index (0-5) to be equal to val. E.g. S 2 23 sets value number 2 to be 23. The command "P" prints all 6 values in index order.
Enter code for ManageFields.c
Input OutputS 2 23 S 4 12 P S 2 21 S 5 31 S 1 14 P S 1 0 S 5 18 S 3 9 S 2 20 P
Value 0 is 0 Value 1 is 0 Value 2 is 23 Value 3 is 0 Value 4 is 12 Value 5 is 0 Value 0 is 0 Value 1 is 14 Value 2 is 21 Value 3 is 0 Value 4 is 12 Value 5 is 31 Value 0 is 0 Value 1 is 0 Value 2 is 20 Value 3 is 9 Value 4 is 12 Value 5 is 18
Explanation / Answer
#include <stdio.h>
const int SIZE = 5;
const int NUMVALS = 6;
const int MAX = 31;
int main() {
int vals = 0;
short which, newVal;
char cmd;
while (EOF != scanf(" %c", &cmd)) {
if (cmd == 'S') { // Set value
scanf("%hd %hd", &which, &newVal);
if (which < 0 || which >= NUMVALS)
printf("Bad value index %d ", which);
else if (newVal < 0 || newVal > MAX )
printf("Bad value %d ", newVal);
else
vals = ((int)newVal<<which*5)|((0xFFFFFFFF^(31<<which*5)) & vals) ;
}
else if (cmd == 'P') { // Print value
int x = vals;
for(int i = 0 ; i < 6 ; i++ )
printf("Value %d is %d ", i , 31&x),x = x>>5;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.