Structures, Unions, and Enumerations
Exercises
Question 16.1
In the following declarations, the x and y structures have members named x and y:
struct { int x, y; } x;
struct { int x, y; } y;
Are these declarations legal on an individual basis? Could both declarations appear as shown in a program? Justify your answer.
- Answer
- Output
- Program
Yes, the declarations are indeed legal. As seen in #8 of Chapter's Notes, we can declares structures as described in the question. One thing that seems like a minor inconvenience is that structure x and structure y are not considered as the same by the compiler, i.e. we can't assign the struct x to struct y and vice versa.
The structure x has the members x and y whose values are 1 and 2 respectively. The structure y has the members x and y whose values are 3 and 4 respectively.
#include <stdio.h>
int main (void) {
struct {
int x, y;
} x;
struct {
Question 16.2
- Declare structure variables named
c1,c2, andc3, each having membersrealandimaginaryof typedouble. - Modify the declaration in part (a) so that
c1's members initially have the values 0.0 and 1.0, whilec2's members are 1.0 and 0.0 initially. (c3is not initialized.) - Write statements that copy the members of
c2intoc1. Can this be done in one statement, or does it require two? - Write statements that add the corresponding members of
c1andc2, storing the result inc3.
- Answer
-
We can declare (and define) a struct variable in one of three ways:
- Defining struct without any structure tag:
struct {
double real;
double imaginary;
} c1, c2, c3; - Defining struct along with a structure tag:
struct complex_number {
double real;
double imaginary;
} c1, c2, c3; - Defining a type of structure using typedef:
typedef struct {
double real;
double imaginary;
} complex_number;
(a) is not really a good practice as if we later define another structure (without a tag) with similar members, this won't change the fact that the compiler will treat those two structures are different "types".
(b) and (c) are preferred practices as it allows the programmer to create multiple variables of the same structure types.
- Defining struct without any structure tag:
-
We can initialize the variables as follows:
-
struct {
double real;
double imaginary;
} c1 = { 0.0, 1.0 },
c2 = { .real = 1.0, .imaginary = 0.0 },
c3; -
struct complex_number {
double real;
double imaginary;
} c1 = { .imaginary = 1.0, .real = 0.0 },
c2 = { .real = 1.0, .imaginary = 0.0 },
c3; -
typedef struct {
double real;
double imaginary;
} complex_number;
complex_number c1 = { 0.0, 1.0 }, c2 = { .imaginary = 0.0, .real = 1.0 }, c3;
-
-
We can only use a single statment to copy the members from one structure to another structure for the structures declared and defined above. There is a scenario when we need to use two statements to copy the members of a structure. Consider the program:
struct {
double real;
double imaginary;
} c1;
struct {
double real;
double imaginary;
} c2;
c1 = { 1.0, 0.0 };
c2.real = c1.real;
c2.imaginary = c1.imaginary;In this case, we can't simply copy the members of structure c1 into the structure c2.
-
The statement required is:
c3.real = c1.real + c2.real;
c3.imaginary = c1.imaginary + c2.imaginary;
Question 16.3
- Show how to declare a tag named
complexfor a structure with two members,realandimaginary, of typedouble. - Use the
complextag to declare variables namedc1,c2, andc3. - Write a function named
make_complexthat stores its two arguments (both of typedouble) in acomplexstructure, then returns the structure. - Write a function named
add_complexthat adds the corresponding members of its arguments (bothcomplexstructures), then returns the result (anothercomplexstructure).
- Program
- Output
#include <stdio.h>
/*
* complex: a structure that contains two members--real and imaginary--which acts
* as a data type that is capable to store a "complex" number
*/
struct complex {
double real;
double imaginary;
[LOG] c1 has the values for members real and imaginary as 1 and 0 respectively. [LOG] c2 has the values for members real and imaginary as 0 and 1 respectively. [LOG] c3 has the values for members real and imaginary as 1 and 1 respectively.
Question 16.4
Repeat Exercise 3, but this time using a type named Complex.
- Program
- Output
#include <stdio.h>
/*
* Complex: a structure that contains two members--real and imaginary--which acts
* as a data type that is capable to store a "complex" number
*/
typedef struct {
double real;
double imaginary;
[LOG] c1 has the values for members real and imaginary as 1 and 0 respectively. [LOG] c2 has the values for members real and imaginary as 0 and 1 respectively. [LOG] c3 has the values for members real and imaginary as 1 and 1 respectively.
Question 16.5
Write the following functions, assuming that the date structure contains three members: month, day, and year (all of type int).
-
int day_of_year(struct date d);Returns the day of the year (an integer between 1 and 366) that corresponds to the date
d. -
int compare_dates(struct date d1, struct date d2);Returns -1 if
d1is an earlier date thand2. +1 ifd1is a later date thand2, and 0 ifd1andd2are the same.
- Program
- Output
#include <stdio.h>
/*
* date: A structure that has the members month (int), day (int), and year (int).
*/
struct date {
int month;
int day;
int year;
Enter the first date in the format (yyyy/mm/dd): 2025/09/14 Enter the second date in the format (yyyy/mm/dd): 2025/08/12 The day of the year for the two dates are: For the first date: 257 For the second date: 224 The first date is later than the second date.
Question 16.6
Write the following function, assuming that the time structure contains three members: hours, minutes, and seconds (all of type int).
struct time split_time(long total_seconds);
total_seconds is a time represented as the number of seconds since midnight. The function returns a structure containing the equivalent time in hours (0-23), minutes (0-59), and seconds (0-59).
- Program
- Output
#include <stdio.h>
/*
* time: A structure that contains the members hours (int), minutes (int),
* and hours (int).
*/
struct time {
int hours;
int minutes;
Enter the time elapsed in seconds: 120 The time in hh:mm:ss format is: 00:02:00
Question 16.7
Assume that the fraction structure contains two members: numerator and denominator (both of type int). Write functions that perform the following operations on fractions:
- Reduce the fraction
fto lowest terms. Hint: To reduce a fraction to lowest terms, first compute the greatest common divisor (GCD) of the numerator and denominator. Then divide both the numerator and denominator by the GCD. - Add the fractions
f1andf2. - Subtract the fraction
f2from the fractionf1. - Multiply the fractions
f1andf2. - Divide the fraction
f1by the fractionf2.
The fractions f, f1, and f2 will be arguments of type struct fraction: each function will return a value of type struct fraction. The fractions returned by the functions in parts (ii)-(v) should be reduced to lowest terms. Hint: You may use the function from part (i) to help write the functions in parts(ii)-(v).
- Program
- Output
#include <stdio.h>
struct fraction {
int numerator;
int denominator;
};
/*
* reduce_fraction: Takes the parameter "fraction_to_reduce" and uses the GCD
Enter the numerator and denominator for the first fraction (in the format n/d): 2/3 Enter the numerator and denominator for the second fraction (in the format n/d): 5/7
The following operations are performed. Reduced form of the first fraction is: 2/3 Reduced form of the second fraction is: 5/7 The sum of first fraction and second fraction is: 29/21 The subtraction of second fraction from first fraction is: 1/-21 The multiplication of first fraction and second fraction is: 10/21 The division of first fraction by second fraction is: 14/15
Question 16.8
Let color be the following structure:
struct color {
int red;
int green;
int blue;
};
- Write a declaration for a
constvariable namedMAGENTAof typestruct colorwhose members have the values 255, 0. and 255. respectively. - (C99) Repeat part (i), but use a designated initializer that doesn't specify the value of
green, allowing it to default to 0.
- Program
- Output
#include <stdio.h>
/*
* color: A structure that has the members red (int), green (int),
* and blue (int).
*/
struct color {
int red;
int green;
For the first part, the primary colors defined for MAGNETA is: Red = 255 Green = 0 Blue = 255
For the second part, the primary colors defined for MAGNETA_C99 is: Red = 255 Green = 0 Blue = 255
Question 16.9
Write the following functions. (The color structure is defined in Exercise 8.)
-
struct color make_color(int red, int green, int blue);Returns a
colorstructure containing the specified red, green, and blue values. If any argument is less than zero, the corresponding member of the structure will contain zero instead. If any argument is greater than 255. the corresponding member of the structure will contain 255. -
int getRed(struct color c);Returns the value of
c's red member. -
bool equal_color(struct color color1, struct color color2);Returns
trueif the corresponding members ofcolor1andcolor2are equal. -
struct color brighter(struct color c);Returns a
colorstructure that represents a brighter version of the colorc. The structure is identical toc, except that each member has been divided by 0.7 (with the result truncated to an integer). However, there are three special cases: (1) If all members ofcare zero, the function returns a color whose members all have the value 3. (2) If any member ofcis greater than 0 but less than 3, it is replaced by 3 before the division by 0.7. (3) If dividing by 0.7 causes a member to exceed 255, it is reduced to 255. -
struct color darker(struct color c);Returns a
colorstructure that represents a darker version of the colorc. The structure is identical toc, except that each member has been multiplied by 0.7 (with the result truncated to an integer).
- Program
- Output
#include <stdio.h>
#include <stdbool.h>
/*
* color: A structure with members red (int), green (int),
* and blue (int).
*/
struct color {
int red;
Enter the Red, Green, and Blue value for the first color: 120 93 250 Enter the Red, Green, and Blue value for the first color: 33 77 222 The value of red in color1 and color2 is: 120 and 33 respectively. The entered colors are different. The brighter color version for color 1 is: Red = 171 Green = 132 Blue = 255 The brighter color version for color 2 is: Red = 47 Green = 110 Blue = 255 The darker color version for color 1 is: Red = 84 Green = 65 Blue = 175 The darker color version for color 2 is: Red = 23 Green = 53 Blue = 155
Question 16.10
The following structures are designed to store information about objects on a graphics screen:
struct point { int x, y; };
struct rectangle { struct point upper_left, lower_right; };
A point structure stores the x and y coordinates of a point on the screen. A rectangle structure stores the coordinates of the upper left and lower right corners of a rectangle. Write functions that perform the following operations on a rectangle structure r passed as an argument:
- Compute the area of
r. - Compute the center of
r, returning it as apointvalue. If either the x or y coordinate of the center isn't an integer, store its truncated value in thepointstructure. - Move
rbyxunits in the x direction andyunits in the y direction, returning the modified version ofr. (xandyare additional arguments to the function.) - Determine whether a point
plies withinr, returningtrueorfalse. (pis an additional argument of typestruct point.)
- Program
- Output
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
/*
* point: is a structure that has the members x (int), and y (int)
* as the coordinates in a 2D plane*/
struct point {
Enter the length and breadth of the rectangle: 8 9 Enter the command for the following actions: Usage Command 1. Calculate the area of the rectangle. (a) 2. Compute the center (b) 3. Move the shape (m) 4. Check if a point lies inside the rectangle. (c) 5. Quit the program. (q) Enter command: a [LOG] The area of the rectangle is: 72
Enter the command for the following actions: Usage Command 1. Calculate the area of the rectangle. (a) 2. Compute the center (b) 3. Move the shape (m) 4. Check if a point lies inside the rectangle. (c) 5. Quit the program. (q) Enter command: b The center of the rectangle is: x = 4 and y = 4
Enter the command for the following actions: Usage Command 1. Calculate the area of the rectangle. (a) 2. Compute the center (b) 3. Move the shape (m) 4. Check if a point lies inside the rectangle. (c) 5. Quit the program. (q) Enter command: m Move rectangle by (format x, y): 10,10 [LOG] The rectangle's new length and breadth is: Length: 18 Breadth: 19
Enter the command for the following actions: Usage Command 1. Calculate the area of the rectangle. (a) 2. Compute the center (b) 3. Move the shape (m) 4. Check if a point lies inside the rectangle. (c) 5. Quit the program. (q) Enter command: c Enter the point to check if it lies inside the rectangle (format x, y): 6,6 [LOG] The point provided is inside the rectangle.
Enter the command for the following actions: Usage Command 1. Calculate the area of the rectangle. (a) 2. Compute the center (b) 3. Move the shape (m) 4. Check if a point lies inside the rectangle. (c) 5. Quit the program. (q) Enter command: q
Question 16.11
Suppose that s is the following structure:
struct {
double a;
union {
char b[4];
double c;
int d;
} e;
char f[4];
} s;
If char values occupy one byte, int values occupy four bytes, and double values occupy eight bytes, how much space will a C compiler allocate for s? (Assume that the compiler leaves no "holes" between members.)
- Answer
- Output
- Program
Assuming that the compiler leaves no holes, the struct contains the following members:
- A variable 'a' of type double.
- A union 'e' consisting of members: a. A character array of length 4. b. A variable of type double. c. A variable of type integer.
- An array of characters 'f' of length 4.
Based on this informations, we can say that the structure will have 8 bytes + max(4 bytes, 8 bytes, 4 bytes) + 4 * 1 bytes
So, the structure will occupy a space of 20 bytes.
[LOG] The size of the structure variable s of tag <anonymous> is: 24
#include <stdio.h>
int main (void) {
struct {
double a;
union {
char b[4];
double c;
Question 16.12
Suppose that u is the following union:
union {
double a;
struct {
char b[4];
double c;
int d;
} e;
char f[4];
} u;
If char values occupy one byte, int values occupy four bytes, and double values occupy eight bytes, how much space will a C compiler allocate for u? (Assume that the compiler leaves no "holes" between members.)
- Program
- Output
#include <stdio.h>
int main (void) {
union {
double a;
struct {
char b[4];
double c;
[LOG] The size of the union variable u is: 24
Question 16.13
Suppose that s is the following structure (point is a structure tag declared in Exercise 10):
struct shape {
int shape_kind; /* RECTANGLE or CIRCLE */
struct point center; /* coordinates of center */
union {
struct {
int height, width;
} rectangle;
struct {
int radius;
} circle;
} u;
} s;
If the value of shape_kind is RECTANGLE, the height and width members store the dimensions of a rectangle. If the value of shape_kind is CIRCLE, the radius member stores the radius of a circle. Indicate which of the following statements are legal, and show how to repair the ones that aren't:
s.shape_kind = RECTANGLE;s.center.x = 10;s.height = 25;s.u.rectangle.width = 8;s.u.circle = 5;s.u.radius = 5;
- Answer
- Output
- Program
-
The statement isn't legal as the type of
shape_kindis integer, not enum. To make the statement legal, we need to defineshape_kindas:enum { RECTANGLE, CIRCLE } shape_kind; -
The statements are indeed legal as it accesses the member
xof the structurecenterof tag point, of the structuresof tag shape. -
The statement isn't legal, as it is trying to access the member height of the structure
sof tag shape. But height is not a member of the structureshape, but rather a member of the structure variablerectanglewhich is embedded inside the union variableu. To make the statement legal, we need to state it as:s.u.rectangle.height = 25; -
The statement is indeed legal.
-
The statement is not legal as there is no specification on the member for the structure variable
circle. The correct statement will be:s.u.circle.radius = 5; -
The statement is not legal as
radiusis not a member of the union variableu, but rather a member of the structure variablecircleembedded inside the union variableu.
The center of the Rectangle is: x = 0 y = 0 The height and the width of the Rectangle is: height = 0 width = 8
The center of the Circle is: x = 0 y = 0 The Radius of the Circle is: radius = 5
#include <stdio.h>
struct point {
int x, y;
};
struct shape {
// int shape_kind; // Not legal, but need to have a separate macro called RECTANGLE and CIRCLE
enum { RECTANGLE, CIRCLE } shape_kind;
Question 16.14
Let shape be the structure tag declared in Exercise 13. Write functions that perform the following operations on a shape structure s passed as an argument:
- Compute the area of
s. - Move
sbyxunits in the x direction andyunits in the y direction, returning the modified version ofs. (xandyare additional arguments to the function.) - Scale
sby a factor ofc(adoublevalue), returning the modified version ofs. (cis an additional argument to the function.)
- Program
- Output
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define PI 3.141592
struct point {
int x, y;
};
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: i Enter the necessary parameters for the shape: Press 1 for rectangle. Press 2 for circle. 1 Enter the center (format (x y)): 3 4 Enter the length and breadth (format (l b)): 6 7 A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: a The area of the shape is: 42
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: m Enter the x and y coordinates to move the shape by (format (x y)): 4 4 The information about the rectangle is: Center (x, y): 7, 8 Height: 6 Width: 7
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: s Enter the scale factor: 5 The information about the rectangle is: Center (x, y): 7, 8 Height: 30 Width: 35
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: v The information about the rectangle is: Center (x, y): 7, 8 Height: 30 Width: 35
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: i Enter the necessary parameters for the shape: Press 1 for rectangle. Press 2 for circle. 2 Enter the center (format (x y)): 5 5 Enter the radius: 8 A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: a The area of the shape is: 201.062
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: m Enter the x and y coordinates to move the shape by (format (x y)): 5 5 The information about the circle is: Center (x, y): 10, 10 Radius: 8
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: s Enter the scale factor: 4 The information about the circle is: Center (x, y): 10, 10 Radius: 32
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: v The information about the circle is: Center (x, y): 10, 10 Radius: 32
A program that provides the listed functionality for either rectangle or circle: Usage Commands 1. Initialize the shape (i) 2. Calculate the area (a) 3. Move the shape (m) 4. Scale the shape (s) 5. View the current shape detail (v) 6. Quit the program (q) Enter your command: q
Question 16.15
- Declare a tag for an enumeration whose values represent the seven days of the week.
- Use
typedefto define a name for the enumeration of part (a).
- Program
- Output
#include <stdio.h>
int main (void) {
enum days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };
{
typedef enum { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } days_t;
printf("Inside the block where a type definition of enumerator is declared as:\n" \
Inside the block where a type definition of enumerator is declared as: Monday: 0 Tuesday: 1 Wednesday: 2 Thursday: 3 Friday: 4 Saturday: 5 Sunday: 6
Inside the main function where a enum of tag days is declared as: Monday: 0 Tuesday: 1 Wednesday: 2 Thursday: 3 Friday: 4 Saturday: 5 Sunday: 6
Question 16.16
Which of the following statements about enumeration constants are true?
- An enumeration constant may represent any integer specified by the programmer.
- Enumeration constants have exactly the same properties as constants created using
#define. - Enumeration constants have the values 0,1,2,... by default.
- All constants in an enumeration must have different values.
- Enumeration constants may be used as integers in expressions.
- Answer
- Output
- Program
-
True. We must declare enumeration constant and initialize it if necessary:
enum { SPADES = 10, DIAMONDS = 20, HEARTS = 30, CLUBS = 40 } s1, s2; -
False. Enumeration constants must follow the C's block scope, i.e. enumeration defined inside a block won't be visible outside the block.
-
True. Enumerations constants have 0, 1, 2, ... as the default value, but can be changed like:
enum { VAR_1, VAR_2 = 10, VAR_3, VAR_4 = 20 } var; /* VAR_1 = 0, VAR_2 = 10, VAR_3 = 11, VAR_4 = 20 */ -
False. Enumeration constants can contain the same integer constant:
enum { NUM_1 = 15, NUM_2 = 30, NUM_3 = 15, NUM_4 } num; /* NUM_1 = 15, NUM_2 = 30, NUM_3 = 15, NUM_4 = 16 */ -
True. We can use the enumeration constants defined in an expression:
enum { SPADES = 10, DIAMONDS = 20, HEARTS = 30, CLUBS = 40 } s1, s2;
int i;
s1 = SPADES;
s2 = CLUBS;
i = s1 + s2;
if (i == 50 && (s1 == CLUBS || s1 == SPADES) && (s2 == SPADES || s2 == CLUBS)) {
printf("The selected card only consists of the color black\n");
} else if (i == 50 && (s1 == DIAMONDS || s1 == HEARTS) && (s2 == DIAMONDS || s2 == HEARTS)) {
printf("The selected card only consists of the color red\n");
} else {
printf("The selected cards consists of both color: black and red\n");
}
The contents of enum defined in this block is: SPADES: 10 DIAMONDS: 20 HEARTS: 30 CLUBS: 40 The contents of enum defined in this block is: VAR_1: 0 VAR_2: 10 VAR_3: 11 VAR_4: 20 The contents of enum defined in this block is: NUM_1: 15 NUM_2: 30 NUM_3: 15 NUM_4: 16 The selected cards consists of both color: black and red
#include <stdio.h>
int main (void) {
{
enum { SPADES = 10, DIAMONDS = 20, HEARTS = 30, CLUBS = 40 } s1, s2;
printf("The contents of enum defined in this block is: \n" \
"SPADES: %d\n" \
"DIAMONDS: %d\n" \
Question 16.17
Suppose that b and i are declared as follows:
enum {FALSE, TRUE} b;
int i;
Which of the following statements are legal? Which ones are "safe" (always yield a meaningful result)?
b = FALSE;b = i;b++;i = b;i = 2 * b + 1;
- Answer
- Output
- Program
- Legal. The statement assigns the enumeration constant to the variable
b- of typeenum <anonymous>. - Legal but not safe.
ican be any integer, and ificontains an integer which none of the enumeration constant holds, we might have some problems. Like, We might be iterating the variablebover to check for a certain enumeration constant, but end up not getting any result. - Legal but not safe. Enumeration might go out of bound.
- Legal. The statement assigns the integers that represents the enumeration constant stored in
b. - Legal. The statement results in 2 * (integer constant represented by the enumeration constant on b) + 1
b contains: 1 [LOG 1] b still contains an enumeration. b contains: 2 [LOG 2] b does not contain an enumeration constant. [LOG 2] b does not contain an enumeration constant. b contains: 3 i contains: 5
#include <stdio.h>
int main (void) {
enum { FALSE, TRUE } b;
int i = 10;
b = FALSE;
// b = i;
Question 16.18
- Each square of a chessboard can hold one piece — a pawn, knight, bishop, rook, queen, or king — or it may be empty. Each piece is either black or white. Define two enumerated types:
Piece, which has seven possible values (one of which is "empty"), andColor, which has two. - Using the types from part (a), define a structure type named
Squarethat can store both the type of a piece and its color. - Using the
Squaretype from part (b), declare an 8 x 8 array namedboardthat can store the entire contents of a chessboard. - Add an initializer to the declaration in part (c) so that
board's initial value corresponds to the usual arrangement of pieces at the start of a chess game. A square that's not occupied by a piece should have an "empty" piece value and the color black.
- Program
- Output
#include <stdio.h>
int main (void) {
enum Piece { PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, EMPTY };
enum Color { BLACK, WHITE };
struct Square {
enum Piece piece;
For the board variable: White piece White piece White piece White piece White piece White piece White piece White piece White piece White piece White piece White piece White piece White piece White piece White piece
Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece Black piece For the new_board variable: Array index 0 has a White piece Array index 1 has a White piece Array index 2 has a White piece Array index 3 has a White piece Array index 4 has a White piece Array index 5 has a White piece Array index 6 has a White piece Array index 7 has a White piece Array index 8 has a White piece Array index 9 has a White piece Array index 10 has a White piece Array index 11 has a White piece Array index 12 has a White piece Array index 13 has a White piece Array index 14 has a White piece Array index 15 has a White piece Array index 48 has a Black piece Array index 49 has a Black piece Array index 50 has a Black piece Array index 51 has a Black piece Array index 52 has a Black piece Array index 53 has a Black piece Array index 54 has a Black piece Array index 55 has a Black piece Array index 56 has a Black piece Array index 57 has a Black piece Array index 58 has a Black piece Array index 59 has a Black piece Array index 60 has a Black piece Array index 61 has a Black piece Array index 62 has a Black piece Array index 63 has a Black piece
Question 16.19
Declare a structure with the following members whose tag is pinball_machine:
name - a string of up to 40 characters
year - an integer (representing the year of manufacture)
type - an enumeration with the values EM (electromechanical) and SS (solid state)
players - an integer (representing the maximum number of players)
- Program
- Output
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// #include <string.h>
#define PM_NAME_LEN 40
#define MAX_PM_SPEC 100
/*
A program that keeps track of the pinball machine specification Enter one of the command listed below: Usage Command 1. Add a specification (a) 2. View the specification (v) 3. Quit the program (q) Enter the command: a Enter the name: Pranav Ram Joshi Enter the year: 2025 Enter the number of players: 10 Enter the type (Electromechanical - 0, Solid State - 1): 1 [SUCCESS] The Specification Added To The Array.
A program that keeps track of the pinball machine specification Enter one of the command listed below: Usage Command 1. Add a specification (a) 2. View the specification (v) 3. Quit the program (q) Enter the command: v There are 1 specifications currently ------------------------------------------------------------------------------------- Name Year Type Players Pranav Ram Joshi 2025 SS 10 ------------------------------------------------------------------------------------- A program that keeps track of the pinball machine specification Enter one of the command listed below: Usage Command 1. Add a specification (a) 2. View the specification (v) 3. Quit the program (q) Enter the command: q
Question 16.20
Suppose that the direction variable is declared in the following way:
enum {NORTH, SOUTH, EAST, WEST} direction;
Let x and y be int variables. Write a switch statement that tests the value of direction, incrementing x if direction is EAST, decrementing x if direction is WEST, incrementing y if direction is SOUTH, and decrementing y if direction is NORTH.
- Program
- Output
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main (void) {
enum { NORTH, SOUTH, EAST, WEST } direction;
int x = 0, y = 0;
The current value of x and y is: x = 0 y = 0
Enter the direction as specified: Direction Command North (n) South (s) East (e) West (w) Enter q to exit the program. Enter your command: n The current value of x and y is: x = 0 y = -1
Enter the direction as specified: Direction Command North (n) South (s) East (e) West (w) Enter q to exit the program. Enter your command: s The current value of x and y is: x = 0 y = 0
Enter the direction as specified: Direction Command North (n) South (s) East (e) West (w) Enter q to exit the program. Enter your command: e The current value of x and y is: x = 1 y = 0
Enter the direction as specified: Direction Command North (n) South (s) East (e) West (w) Enter q to exit the program. Enter your command: w The current value of x and y is: x = 0 y = 0
Enter the direction as specified: Direction Command North (n) South (s) East (e) West (w) Enter q to exit the program. Enter your command: q
Question 16.21
What are the integer values of the enumeration constants in each of the following declarations?
enum {NUL, SOH, STX, ETX};enum {VT = 11, FF, CR};enum {SO = 14, SI, DLE, CAN = 24, EM};enum {ENQ = 45, ACK, BEL, LF = 37, ETB, ESC};
- Answer
- Output
- Program
The corresponding integer constant for the enumeration constants are:
-
NUL: 0
SOH: 1
STX: 2
ETX: 3 -
VT: 11
FF: 12
CR: 13 -
SO: 14
ST: 15
DLE: 16
CAN: 24
EM: 25 -
ENO: 45
ACK: 46
BEL: 47
LF: 37
ETB: 38
ESC: 39
The enumerations constants and their corresponding integer constant are: NUL: 0 SOH: 1 STX: 2 ETX: 3
The enumerations constants and their corresponding integer constant are: VT: 11 FF: 12 CR: 13
The enumerations constants and their corresponding integer constant are: SO: 14 ST: 15 DLE: 16 CAN: 24 EM: 25
The enumerations constants and their corresponding integer constant are: ENQ: 45 ACK: 46 BEL: 47 LF: 37 ETB: 38 ESC: 39
#include <stdio.h>
int main (void) {
{
enum { NUL, SOH, STX, ETX };
printf("The enumerations constants and their corresponding integer constant are:\n" \
"NUL: %d\n" \
"SOH: %d\n" \
Question 16.22
Let chess_pieces be the following enumeration:
enum chess_pieces {KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN};
- Write a declaration (including an initializer) for a constant array of integers named
piece_valuethat stores the numbers 200, 9, 5, 3, 3, and 1, representing the value of each chess piece, from king to pawn. (The king's value is actually infinite, since "capturing” the king (checkmate) ends the game, but some chess-playing software assigns the king a large value such as 200.) - (C99) Repeat part (a), but use a designated initializer to initialize the array. Use the enumeration constants in
chess_piecesas subscripts in the designators. (Hint: See the last question in Q&A for an example.)
- Program
- Output
#include <stdio.h>
#include <stdlib.h>
int main (void) {
enum chess_pieces { KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN };
const int chess_pieces[] = { 200, 9, 5, 3, 3, 1 };
The contents of constant integer variable chess_pieces is: Index 0: 200 Index 1: 9 Index 2: 5 Index 3: 3 Index 4: 3 Index 5: 1
The contents of constant integer variable chess_pieces_c99 is: KING: 200 QUEEN: 9 ROOK: 5 BISHOP: 3 KNIGHT: 3 PAWN: 1
Programming Projects
Project 16.1
Write a program that asks the user to enter an international dialing code and then looks it up in the country_codes array (see Section 16.3). If it finds the code, the program should display the name of the corresponding country: if not, the program should print an error message.
- Program
#include <stdio.h>
#include <stdlib.h>
#define COUNTRY_NAME 30
struct dialing_code {
char *country;
int code;
};
Project 16.2
Modify the inventory.c program of Section 16.3 so that the p (print) operation displays the parts sorted by part number.
- Program
Makefile
main.c
quicksort.c
quicksort.h
readline.c
readline.h
Project 16.3
Modify the inventory.c program of Section 16.3 by making inventory and num_parts local to the main function.
- Program
Makefile
main.c
readline.c
readline.h
Project 16.4
Modify the inventory.c program of Section 16.3 by adding a price member to the part structure. The insert function should ask the user for the price of a new item. The search and print functions should display the price Add a new command that allows the user to change the price of a part.
- Program
Makefile
main.c
readline.c
readline.h
Project 16.5
Modify Programming Project 8 from Chapter 5 so that the times are stored in a single array. The elements of the array will be structures, each containing a departure lime and the corresponding arrival time. (Each time will be an integer, representing the number of minutes since midnight.) The program will use a loop to search the array for the departure time closest to the time entered by the user.
- Program
#include <stdio.h>
#include <stdbool.h>
// struct flight {
// int departure_time;
// int arrival_time;
// } flight_time[] = {[0].departure_time = 8 * 60, [0].arrival_time = 10 * 60 + 16,
// [1].departure_time = 9 * 60 + 43, [1].arrival_time = 11 * 60 + 52,
// [2].departure_time = 11 * 60 + 19, [2].arrival_time = 13 * 60 + 31,
Project 16.6
Modify Programming Project 9 from Chapter 5 so that each date entered by the user is stored in a date structure (see Exercise 5). Incorporate the compare_dates function of Exercise 5 into your program.
- Program
#include <stdio.h>
/*
* date: A structure that has the members month (int), day (int), and year (int).
*/
struct date {
int month;
int day;
int year;