(C) 2004 Airton Filho 

Correction of Assignment questions

 

CHAPTER 1

A1.1) What are the advantages of C over Assembly language?
R: It is easier to read and write programs in C. It is more portable than assembly language code, which is dependent on the computer architecture.

A1.2) List three of the advantages of C language.
R: supports procedural programming paradigm; powerful programming language used in a scenario where speed of an application is critical; programs are compact and concise

A1.3) List three applications of C language.
R: device drivers; embedded applications; utility programs.

A1.4) For what sort of programs is C more suitable than C++? Why?
R: C is well suited for developing small programs that run on smaller systems. C++ complex class libraries that can occupy large amounts of disk space.

CHAPTER 3

A3.1) What is the output of the following program:

#define PI 3.141593
int main( )
{
int number = 5;
float coke = 13.5;
int cost = 21000;

printf ("The %d guy drank %f glasses of coke.\n", number, coke);
printf ("The value of pi is %f.\n", PI);
printf("Service turnarounds are tough.\n");
printf("%c%ld\n",'$', 2 * cost);
return 0;
}

R:

The 5 guy drank 13.5 glasses of coke.
The value of pi is 3.141593.
Service turnarounds are tough.
$42000

A3.2) Write a program that prints the first 3 letters of your name. For example, if your name is Toby, write a program that outputs:

TTTTTTTTTTT      OOOOOOO     BBBBB
    TTT          O     O     B    B
    TTT          O     O     B    B
    TTT          O     O     BBBBB
    TTT          O     O     B    B
    TTT          O     O     B    B
    TTT          OOOOOOO     BBBBB

A3.3) How would you print out, using printf( ), the sentence below:

My mom says a \ is a backslash 99.9% of the time.

R: printf ("My mom says a \\ is a backslash 99.9%% of the time.\n");

CHAPTER 4

A4.1) What is the value of variable x in each of the cases?

a) x = 2 + 3
R: 5

b) x = 2 * 3 + 4
R: 10

c) x = 5 + (6 + 4) / 2
R: 10

d) x = 10 % 3 * 4 + 5 * 2
R: 14

e) x = 10 % 2
R: 0

f) x = 27 % 7
R: 6

g) x = 5 / 4
R: 1

h) x = 7.0 / 4.0
R: 1.75

i) x = 7.0 / 4
R: 1.75

A4.2) What is the output of the following program?

main( )
{
int a, b;
float x,z;

a = 10;
b = 3;
z = a/b;
x = (float)a/b;

printf("a/b = %.3f\n",z);
printf("(float) a/b = %.3f\n",x);
return 0;
}

R:

a/b = 3.000
(float) a/b 3.3333

A4.3) What is the difference between a prefix and a postfix operator?
R: With a prefix operator the increment or decrement occurs before the variable's value is used in the rest of the expression. With a postfix operator, the increment or decrement occurs after the variable's value is used.

A4.4) What is the value of x?

if a = 11, what value will x be assigned?
A) x = ++a % 3;
R: 0

B) x = a++ % 3;
R: 2

If b = 7, what value is assigned x below? What is the value of b after the assignment?

x = -b++;

R:
x = -7
b = 8

A4.5) If originally x = 5, y = 0, and z = 1, what is the value of x, y, and z after executing the following code:

if (z == 0 || x && !y)
{
if (!z)
y = 1;
else
x = 2;
}

R:

x = 2
y = 0
z = 1

A4.6) If originally x = 0, y = 1, and z = 2, what is the value of x, y, and z after executing the following code:

if (z < x || y >= z && z ==1)
{
if (z && y)
y = 1;
else
x = 1;
}

R:

x = 0
y = 1
z = 2

A4.7) If originally x = 2, y = -1, and z = 0, what is the value of x, y, and z after executing the following code:

if (z = x > y)
{
x += 3;
y -= 2;
x = 2;
}
else
x = y++;

R:

x = 2
y = -3
z = 1

CHAPTER 5

A5.1) What does scanf( ) do?
R: It is the input function which converts text input or characters from the screen into integers, floating point numbers, or characters. Its arguments are also the format string and a variable list.

A5.2) What is the main difference between printf( ) and scanf( )?
R: The main difference with printf( ) is that the variable must be preceded by the '&' character. This means that scanf( ) uses the address of the variable.

A5.3) Write a if/else statement for each of the following:

a) If taxCode is 'T', increase cost by adding rate times cost to it.

R:

if (taxCode == 'T')
cost *= (1 + rate);

b) If id has value 1, read values for x and y (both integers), calculate and print the sum of x and y. Otherwise print the message "Id is not 1".

R:

int sum = x + y;
if (id == 1)
{
scanf (%d %d, &x &y);
printf ("%d", sum);
}
else
printf ("Id is not 1.");

A5.4) Write a program that given three integers, finds the smallest one:

R:

void main()
{
int num1, num2, num3;
printf ("Please enter 3 integers and press Enter after each one: \n", num1, num2, num3);
scanf ("%d%d%d", &num1, &num2, &num3);
printf ("The smallest one is ");
if (num1 <= num2 && num1 <= num3)
printf ("%d.\n", num1);
else if (num2 <= num1 && num2 <= num3)
printf ("%d.\n", num2);
else
printf ("%d.\n", num3);
}

A5.5) Calculating a student's grade. Write a program that captures three test scores of a student and displays the student's average and grade (A = 100-90; B = 89-80; C = 79-70; D = 69-60; F = 59-0)

R:

int main()
{
int grade1, grade2, grade3;
float average;
char letterGrade;

printf("Please enter 3 test scores (integers): ");
scanf(" %d%d%d", &grade1, &grade2, &grade3);

average = (grade1 + grade2 + grade3)/3.0;

if (average >=90)
letterGrade = 'A';
else if (average >= 70 && average < 90)
{
if (grade3 > 90)
letterGrade = 'A';
else
letterGrade = 'B';
}
else if (average >= 50 && average < 70)
{
if ((grade2 + grade3)/2.0 > 70)
letterGrade = 'C';
else
letterGrade = 'D';
}
else
letterGrade = 'F';

printf("Your average is %f and your final grade is: %c\n", average,letterGrade);

return 0;
}

A5.6) Write a program (using a switch statement) that computes the parking charge that, given the type of vehicle, ('c' for car, 'b' for bus, and 't' for truck) and the hours spent in the parking lot, finds the parking charge based on the rates below.

Car: $1 per hour
Bus: $4 per hour
Truck: $6 per hour

R:

int hours, charge;
char vehicle;
switch (vehicle)
{
case 'c':
charge = hours * 1
break;
case 'b':
charge = hours * 4
break;
case 't':
charge = hours * 6
break;
default:
printf ("Error: illegal vehicle type.");
}

A5.7) Use a switch statement to implement a table of values of the cost corresponding to a given distance.

Distance Cost
0 through 99 1.00
100 - 299 2.00
300 - 599 3.00
600 - 999 4.00
otherwise 5.00

R:

switch (distance / 100)
{
case 0:
cost = 1.00;
break;
case 1: case 2:
cost = 2.00;
break;
case 3: case 4: case 5:
cost = 3.00;
break;
case 6: case 7: case 8: case 9:
cost = 4.00;
break;
default:
cost = 5.00;
}

A5.8) How would you produce this pattern?

*
**
***
****
*****

R:

int row, star;
for (row = 1; row <= 5; row++)
{
for (star = 1; star <= row ; star++)
printf("*");
printf("\n");
}

return;
A5.9) What does the break statement, when executed in a for, while, or do/while structure do:
R: Causes immediate exit from the loop.

A5.10) What does the continue statement, when executed in a for, while, or do/while structure do:
R: Skips any remaining statements in the body and proceeds with the next iteration of the loop.

A5.11) What of the output of the following segment of code:

x = 1;
while (x <= 15)
{
printf ("%d", x);
if (x % 5 ==0)
printf ("\n");
else
printf ("\t");
x++;
}

R:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

A5.12) What is the output of the following program:

for (k = 1; k < 16; k += 2)
{
if (k % 3 ==0)
continue;
else
printf ("%d\n", k);
}

R:

1
5
7
11
13

A5.13) Use a for loop to add the odd numbers from 1 to 99. Then print out the result:

R:

for (int i = 1; i < 100; i +=2)
{
sum += i;
}
printf ("%d \n", sum);

A5.14) Write a data validation loop that would precede a switch statement to guarantee that month was a valid input if a user was asked to input a number form 1 to 12 to indicate the month.

R:

while (!(month >= 1 && month < = 12)
{
printf ("Not a valid month. /n")
scanf ("%d", &month);
}

A5.15) What is the output of the following program segments:

a)

for (x = 1; x <=4; x++)
{
for (y = 1; y<= 5; y++)
printf ("%d", x);
printf ("\n");
}

R:

11111
22222
33333
44444

b)

for (x = 8; x >=1; x--)
{
for (y = x; y>= 1; y--)
printf ("*");
printf ("%d\n", x);
}

R:

********8
*******7
******6
*****5
****4
***3
**2
*1


A5.16) Write a program that computes the average of several integers. Prompt the user to enter the number of numbers that will be entered. Use a loop to read in the values and accumulate the sum.

A5.17) Write a program that has two numbers between 1 and 100 stored as correct guesses for a computer guessing game. The first time the user plays, he has to guess the first number. If he succeeds within five tries, he will be asked if he wants to guess another time for the second number. If he does not succeed, he will not be offered a second game.

CHAPTER 6 (including Searching and Sorting)

A6.1) Write a program to read five values into an array and print them out in reverse order (Use two independent for loops).

R:

int i = 0;
int values [5];

for (i=0; i<5;i++)
{
printf ("Please enter an integer: ");
scanf ("%d", &values[i]);
}

printf ("Result: ");

for (i=4; i >= 0;i--)
printf ("%d ", values[i]);
printf ("\n");

A6.2) Assume the following declarations are made:

const int little = 6, medium = 10;
int k, number[medium];

For each of the following, show what the array looks like after the execution of the code:

a)

for (k = 0; k < medium; k++)
number[k] = k / 2;

R:

0 1 2 3 4 5 6 7 8 9
0 0 1 1 2 2 3 3 4 4

b)

for (k = 0; k < little; k++)
number[k] = k * k;
for (k = little; k < medium; k++)
number[k] = number[k - 5];

R:

0 1 2 3 4 5 6 7 8 9
0 1 4 9 16 25 1 4 9 16

c)

number[0] = 1;
k = 1;
do
{
number[k] = 2 * number[k -1];
k++;
}
while (k < medium);

R:

0 1 2 3 4 5 6 7 8 9
1 2 4 8 16 32 64 128 256 512

A6.3) Given the statement:

int profit[6] = {150, 300, 500};

What is the value of n, when:

a) n = profit[3]
b) n = profit[0]
c) n = profit[6]

R:

A. 0
B. 150
C. ???

A6.4) What would be printed by the following program segment:

int list[10] = {0};
int k;
for (k = 0; k < 5; k++)
list[2 * k + 1] = k + 2;
for (k = 0; k < 10; k++)
printf ("%4d\n", list[k]);

R:

0
2
0
3
0
4
0
5
0
6

A6.5) An array contains the elements shown below. The first two elements have been sorted using a selection sort. What would be the value of the elements in the array after three more passes of the selection sort algorithm?

1) 7 8 26 44 13 23 98 57

R:

2) 7 8 13 44 26 23 98 57
3) 7 8 13 23 26 44 98 57
4) 7 8 13 23 26 44 57 98

A6.6) We have the following array:

47 3 66 32 56 92

After two passes of a sorting algorithm, the array has been rearranged as shown below:

3 47 66 32 56 92

Which sorting algorithm is being used? Explain your answer.

R: Insertion algorithm. If selection had been used, after 2 passes, the array would have looked like this:
3 32 66 47 56 92

A6.7) We have the following array:

80 15 21 72 3 33

After two passes of a sorting algorithm, the array has been rearranged as shown below:

15 21 3 33 72 80

Which sorting algorithm is being used? Explain your answer.
R: Bubble sort algorithm. The two largest numbers were passed to the last two positions.

A6.8) An array contains the elements shown below. Using the binary search algorithm, trace the steps followed to find 88. At each loop, including the last, show the contents of low, middle, and high.

8 13 17 26 44 56 88 97

R:

1. L = 0; M = 3; H = 7
2. L = 4; M = 5; H = 7
3. L = 6; M = 6; H = 7

A6.9) The program below searches through an unsorted array for any to numbers that match and stops the search if a match is found. Fill in the missing numbers, variable names, or statements in the space provided:

int numbers[23], cnt1, cnt2, cnt3, testNo;
int match = 0;

for (cnt1 = 0; cnt1 < ______; cnt++)
{
testNo = numbers[cnt1];
for (cnt2 = ______; cnt2 < ______; cnt2++)
{
if (testNo == numbers[______])
{
match = 1;
break;
}
if (match == 1)
{
printf ("A match has been found!\n");
______;
}

R:

for (cnt1 = 0; cnt1 < 22; cnt++)
for (cnt2 = cnt1+1; cnt2 < 23; cnt2++)
break

A6.10) Based on the following array, what will be the output in each declaration?

char teams[ ] = {'L','a','k','e','r','s','\0','N','e','t','s','\0'};

a) printf(" %s",teams);
b) printf("%s",teams+7);
c) printf("%s",(teams+3));
d) printf("%s",teams[0]);
e) printf("%c",(teams+0)[0]);
f) printf("%c",(teams+5));
g) printf("%c",(teams-200)[202]);

R:

a) Lakers
b) Nets
c) ers
d) ERROR (this is a character, not a string)
e) L
f) ERROR (this is a string, not a character)
g) k

CHAPTER 7

A7.1) What is the output of the following program segment:

void new_sum (int x, int y);

int main()
{
int x = 10, y = 20;
printf ("%d %d\n", x,y);
new_sum (x, y);
printf ("%d %d\n", x,y);
return 0;
}

void new_sum (int x, int y)
{
x += 10;
y *= 10;
return;
}

R:

10 20
10 20

A7.2) What is the output of the following program segment:

int sum (int, int, int *);

int main()
{
int a = 4, b = 17, c = 9, int d;
d = sum (c, a, &b);
printf ("2. %d %d %d %d\n", a,b,c,d);
return 0;
}

int sum (int x, int y, int *z)
{
int k = 5;
printf ("1. %d %d %d\n", x,y,*z);
x += y;
*z = 2 * k;
return (x + y + *z);
}
R:

1. 9 4 17
2. 4 10 9 27

A7.3) What is the difference between a void function and a function of type int, float...?
R: A void function does not return a value to the calling routine, while the other types of function return a value through the return statement corresponding to the type of the defined function.

A7.4) What is the difference between global and local variables:
R: Global variables are defined at the top of the program and are "visible" to all functions. Local variables are only visible within the routine of their definition, and they disappear when their block ends.

A7.5) What is the difference between a an automatic and a static variable:
R: Automatic is the default and means that the variable is gone when the function of definition ends. Static variables do not lose their value when their function ends. If the function is called again, the variable has retained its value.

A7.6) What is the difference between passing by value and passing by address:
R: When passing by value, values are not changed, a copy of the variable is sent to the function. Passing by address allows the variable passed to be changed.

A7.7) What is the problem with the following functions: (ANSWERS ARE HIGHLIGHTED)

a)

test( )
{
return 4.7;
}

R:

float test( )
{
return 4.7;
}

b)

int fun (float x, float y)
{
float result;
result = x * y;
return (result);
}

R:

int fun (float x, float y)
{
float result;
result = x * y;
return ((int) result);
}

c)

void n_char (int n)
{
char ch;
if (n> 32 && n< 127)
ch = (char) n;
else
ch = '0';
return ch;
}

R:

char n_char (int n)
{
char ch;
if (n> 32 && n< 127)
ch = (char) n;
else
ch = '0';
return ch;
}

A7.8) Write a program to roll a pair of dice, and report what they. Use rand( ) and srand( ).

R:

int generateRandom();

int main()
{
int die1,die2,worksum;
srand (time(NULL));
die1 = generateRandom();
die2 = generateRandom();
worksum = die1 + die2;
printf("Player rolled %d + %d = %d\n", die1,die2,worksum);
return 0;
}

int generateRandom()
{
int die;
die = 1 + rand() % 6;
return (die);
}

A7.9) Modify problem 5 of chapter 5 so that you use a function to calculate the student's average and grade, and pass it to another function that prints it to the screen.

A7.10) Write function prototypes for the functions describe below:

a) type( ) takes two int arguments and returns a type int.
R: int type (int, int)

b) donut( ) takes int argument, prints that number of zeros, and does not pass anything back o the calling function.
R: void donut (int)

c) test_move( ) takes two integer inputs, row and column, and an integer moveType; and returns a 1 if the moveType would result in a legal move on the board, and a zero if it would not.
R: int test_move (int, int, int)

A7.11) Write a function that computes the payroll calculation for hourly employees. Allow for time and a half for hours over 40. Determine what parameters must be passed into the function and return the payroll calculation back to the calling program.

R: double payroll (double hourWage, int hours);

int main()
{
double hourWage = 4.0, salary;
int hours = 50;
salary = payroll (hourWage, hours);
printf ("%f\n", salary);
return 0;
}

double payroll (double hourWage, int hours)
{
double salary;
if (hours <= 40)
salary = hours * hourWage;
else
salary = hourWage * (40 + (1.5 * (hours - 40)));
return (salary);
}

A7.12) Write a program that randomly selects a number between 1 and 20, and asks the user to guess what the number is. The user has 5 chances to guess it. After each guess, a message is sent.

R:

//prototypes
int guess (int, int);
void unsuccessful(int);
void successful();
void sorry(int);

int main()
{
int randomNumber;
int tries = 0;//counter
int success;

srand (time(NULL));//seed
randomNumber = 1 + rand() % 20;

//printf("\n------- %d --------\n", randomNumber);

printf("I am thinking of a number between 1 and 20.\n");
printf("Try guessing it: ");

do
{
tries++;
//printf("\n------- %d --------\n", tries);
success = guess (randomNumber, tries);

if (success == 0)
{
unsuccessful(0);//guess is too low
}
else if (success == 1)
{
unsuccessful(1);//guess is too high
}
else if (success == 2)
{
successful();//guess is correct
break;
}
else
{
sorry(randomNumber);//end
break;
}
}
while (tries < 5);

return 0;
}

int guess (int rNumber, int tries2)
{
int uGuess;
scanf(" %d", &uGuess);
//printf("\n------- %d --------\n", tries2);

if (tries2 < 5 && uGuess != rNumber)
{
if (uGuess < rNumber)
return 0;//too low
else
return 1;//too high
}
else if (tries2 <= 5 && uGuess == rNumber)
return 2;//correct
else
return 3;//end
}

void unsuccessful(int val)
{
if (val == 0)
printf("\nYour guess is too low. Try again: ");
else
printf("\nYour guess is too high. Try again: ");

return;
}

void successful()
{

printf("\nCongratulations!!!\n");
return;
}

void sorry(int num)
{
printf("\nSorry. The number was %d.\n", num);
printf("You should have gotten it by now.\n");
printf("Better luck next time.\n");
return;
}

CHAPTER 8

A8.1) What is a struct?
R: A struct is a collection of different data type items that can be taken as a single entity. It is a given a structure tag which serves as a data type or template that you define. It is like the record in a database, or a record in Pascal, or a type in VB.

A8.2) Based on the structure definition below, answer the following questions:

struct student
{
char fst_name[20], last_name[300];
int score
char grade;
}
struct student stu1, stu2;

Identify the following statements as valid, valid under certain conditions, or invalid:

a) struct student stulist[30]; R: VALID
b) printf ("%s", stu1); R: INVALID
c) printf (("%d %c", stu1.score,stu1.grade); R: VALID
d) stu2 = stu1; R: VALID
e) if (stu2.score == stu1.score)
printf ('Equal"); R: VALID
f) if (stu2 == stu1)
printf ('Equal structures"); R: INVALID
g) stu2.lat_name = "Martin"; R: INVALID

Write a statement that displays the initials of stu1 with periods.

R:

printf ("%c.", stu1.fst_name[0]);
printf ("%c.", stu1.last_name[0]);

A8.3) Define a type name LONG_LAT using typedef that would be appropriate for storing longitude and latitude values. Include components named degrees (integer), minutes (integer), and direction (one of the characters 'N', 'S', 'E', 'W').

R:

typedef struct
{
int lon_degrees, lat_degrees, lon_min, lat_min;
char lon_dir, lat_dir;
} LONG_LAT;


A8.4) Given the following structure defined globally, declare the structure variable customer that would be in main( ).

struct customerRec
{
char custName[25];
double balance;
float disRate;
};

R: struct customerRec customer;

A8.5) Given the structure declaration below:

struct edCollection
{
char title[25];
char artist[25];
int numSongs;
float price;
char dateBought[9];
} cd1;

Assign "The Joshua Tree" to the title field in the structure variable

R: strcpy (cd1.title, "The Joshua Tree");

Declare a structure template that holds student access information into the student registration system. It should hold the 8 character student username, the student 9 character Id number, and the student 5 digit pin number.

R:

struct student
{
char name[9];
char id[10];
char pin[6];
}

CHAPTER 9 (Pointers)

A9.1) What is the problem with the following function: (ANSWERS ARE HIGHLIGHTED)

void swap (int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
return;
}

R:

void swap (int *x, int *y)
{
int temp;
temp = x;
*x = *y;
*y = temp;
return;
}

A9.2) Write the prototype for the function describe below:

stuff_it( ) takes a float argument and the address of a float variable and stores the first value in the address given in the second argument, passing nothing back to the calling function.

R: void stuff_it (float, float*)

A9.3) Write a program that asks the user to enter some money value and outputs the breakdown of the values (i.e.: number of dollars, half-dollars, quarters, dimes, nickels, and pennies). For example, 1.56 would output:

Dollar: 1
Half-dollar: 1
Quarter: 0
Dime: 0
Nickel: 1
Penny: 1

R:

//prototype
void giveChange(int *, int *, int *, int *, int *, int *);

int main()
{
int dollar = 0;
int halfDollar = 0;
int quarter = 0;
int dime = 0;
int nickel = 0;
int penny = 0;

printf("Please enter the change: ");

giveChange(&dollar, &halfDollar, &quarter, &dime, &nickel, &penny);

printf("Dollar: %d\n", dollar);
printf("Half Dollar: %d\n", halfDollar);
printf("Quarter: %d\n", quarter);
printf("Dime: %d\n", dime);
printf("Nickel: %d\n", nickel);
printf("Penny: %d\n", penny);

return 0;
}

void giveChange (int *d, int *hd, int *q, int *di, int *n, int *p)
{
int fraction;
float change;

scanf ("%f", &change);

*d = (change * 100) / 100;
fraction = (change - *d) * 100;
*hd = fraction / 50;
*q = (fraction - (*hd * 50)) / 25;
*di = (fraction - (*hd * 50) - (*q * 25)) / 10;
*n = (fraction - (*hd * 50) - (*q * 25) - (*di * 10)) / 5;
*p = (fraction - (*hd * 50) - (*q * 25) - (*di * 10) - (*n * 5));
}

A9.4) What is the output of the following program segment:

void alter (int *, int *);

main( )
{
int x, y;
x = 15;
y = 8;
alter (&x, &y);
printf ("x = %d and y = %d \n", x, y);
return 0;
}

void alter (int *a, int *b)
{
int temp;
temp = *a;
*a += *b;
*b -= temp;
return;
}

R: x = 23 and y = -7

A9.5) What is the output of the following program:

struct house
{
float sqft;
int rooms, stories;
char address[60];
};

int main()
{
struct house meadows = {1560.0, 6, 1, "22 Spiffo Road"};
struct house glen = {2000.0, 10, 2, "73 Appian way"};
struct house *ptrhaus;

ptrhaus = &glen;

printf ("%d %d\n", meadows.rooms, ptrhaus -> stories);
printf ("%s\n", meadows.address);
printf ("%c %c\n", ptrhaus -> address[3], meadows.address[4]);

return 0;
}
R:

6 2
22 Spiffo Ro
A p

A9.6) Based on the following declarations:

struct fullname
{
char fname[20];
char lname[20];
};

struct bard
{
struct fullname name;
int born;
int died;
};

struct bard willie;
struct bard *pt;
pt = &willie;

a) Assign the born member of the variable willie the year 1564
R: willie.born = 1564

b) Assign the died member often willie variable to the year 1616 using the pointer pt.
R: pt -> died = 1616

A9.7) What is the difference between malloc( ), calloc( ), free( ):

R:
- malloc( ): returns a pointer to the first byte of memory asked for, can be any type of pointer you wish
- calloc( ): returns a pointer to a contiguous block of memory, used for arrays. Needs the number of elements and the element size. It also clears the memory.
- free( ): returns previously allocated memory back to the system, the argument in the parenthesis must be a pointer to memory

A9.8) Assume that single precision floating point numbers are stored in 4 bytes and that the starting address of the array is at location 2500 (bytes) in memory. Array numbers is a float array of 10 elements, initialized to the values {0.0,1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9}.

a) Declare a pointer nPtr that points to an object of type float.
R: float *nPtr;
b) Give two separate statements that assign the starting address of any array numbers to the pointer variable nPtr.
R: nPtr = numbers;
nPtr = &numbers[0];

c) Refer to element 4 of array numbers in two ways using array subscripts or pointer notation where nPtr points to the beginning of the array.
R: *numbers[3];
*(numbers + 3) OR *(nPtr + 3) OR nPtr[3]

d) Assuming that nPtr points to the beginning of array numbers , what address is referenced by nPtr + 8 (2500+)? What value is stored at that location?
R: 2532
8.8

A9.9) Based on the following declarations, identify each statement as valid or invalid:

float rootbeer[10], *pf, value = 2.2;
char car[] = "1998 Audi 80";
char *pcar = "1956 Chevrolet";

a) rootbeer[2] = value; => VALID
b) printf ("%s", pcar); => VALID
c) rootbeer = value; => INVALID
d) printf ("%f", *(rootbeer +1)); => VALID
e) pf = value; => INVALID
f) pf = rootbeer; => VALID
g) rootbeer = pf; => INVALID
h) *pcar = value; => INVALID
i) pcar = "57 Chevrolet"; => VALID
j) car = "1993 BMW 325i"; => INVALID

A9.10) What is the output of this program?

int main()
{
char relative[] = "Mother";
char *ptr;

ptr = relative + strlen(relative);

while (--ptr >= relative)
printf ("%s\n", ptr);

return 0;
}

R:

r
er
her
ther
other
Mother

A9.11) Write a program that reads a character, an integer, and a floating point number, and displays them and the memory location for each one.

R:

int main()
{
char c;
int i;
float f;

printf ("Please enter a character: ");
scanf ("%c", &c);

printf ("Please enter an integer: ");
scanf ("%d", &i);

printf ("Please enter a floating point number: ");
scanf ("%f", &f);

printf ("The value of c is %c.\n", c);
printf ("The value of i is %d.\n", i);
printf ("The value of f is %f.\n", f);

printf ("The address of c is %p.\n", &c);
printf ("The address of i is %p.\n", &i);
printf ("The address of f is %p.\n", &f);

return 0;
}

A9.12) Rewrite the following function that converts a string into an integer with a pointer implementation. This version assumes that the string consists of a string of only digits from '0' to '9'.

int atoi (char s[])
{
int k, n;
n = 0;
for (k = 0; s[k] != '\0'; k++)
n = 10 * n + s[k] - '0';
return n;
}

R:

int atoi (char *s)
{
int n = 0;
while (*s != '\0')
{
n = 10 * n + *s - '0';
s++;
}
}

A9.13) Write a for loop that would place ones in the even-numbered elements of the following dynamically allocated array.

int *num_arr, k;
num_arr = (int *) calloc (20, sizeof(int));

R:

for (k = 0; k < 20; k += 2)
num_arr[k] = 1;

A9.14) Given the following declarations, which are not allowed?

int x, *p;
double d, *q;

a) p = &x;
b) q = &x;
c) p = x;
d) q = &d;
e) p = &d;

R: b; c; e


A9.15) Given the following declarations, what is the value of each expression?

int a = 5, b = 7;
int *p = &a, *q = &b;

a) ++a;
b) (*p)++;
c) p++;
d) - (*q)
e) *p + *q
R:

a) 6
b) 6
c) in this case, points to 2 bytes from 'a'
d) -7
e) 12

A9.16) Given the following declarations, what is the value of the following expressions?

int num[ ] = {23,3,5,7,4,-1,6};
int *nptr, x= 2, y = 4;
nptr = &num[0];

a) nptr
b) *nptr
c) *nptr + 1
d) *(nptr+x)
e) *nptr + y
f) *&x

R:

a) it's an address
b) 23
c) 24
d) 5
e) 27
f) 2

A9.17) What is the output of the following program:

int main()
{
int marbles[6] = {20,10,5,39,4,16};
int cnt, total = 0;
int *ar;
ar = marbles; /* or use ar = &marbles[0]; */
for (cnt = 0; cnt <6 ; cnt++)
{
total += *ar;
ar++;
}

printf("The total number of marbles is %d.\n",total);
return 0;
}

R: The total number of marbles is 94.

A9.18) Rewrite the following function using an array implementation:

int computeSum (int *list, int size)
{
int cnt, sum= 0;
for ( ; list < list + size; list++)
sum += *list;
return sum;
}

R:

int computeSum (int list[], int size)
{
int cnt, sum= 0;
for (cnt = 0; cnt < size; cnt++)
sum += list[cnt];
return sum;
}

A9.19) What is the output of the following program:

void main( )
{
char c[ ] = "programming";
char *pc;
for (pc = &c[5]; pc >= &c[0]; pc--)
printf("%c", *pc);
printf("\n");

return;
}

R: argorp

A9.20) Write a function that returns the number of times the character is found in a string. The function must have two parameters. The first is a character array. The second is the character to be counted.

a) Write with an array implementation
b) Write with a pointer implementation

R:

a)

int main()
{
char c[] = "point-to-point protocol";
int times;
char ch = 'p';
times = cntChar (c, ch);
printf ("times: %d\n", times);
return 0;
}

int cntChar(char c[], char ch)
{
int k, cnt = 0;
for (k = 0; c[k] != '\0'; k++)
{
if (c[k] == ch)
cnt++;
}
return cnt;
}

b)

int main()
{
char c[] = "point-to-point protocol";
int times;
char ch = 'p';
times = cntChar (c, ch);
printf ("times: %d\n", times);
return 0;
}

int cntChar(char *c, char ch)
{
int cnt = 0;
while (*c != '\0')
{
if (*c == ch)
cnt++;
c++;
}
return cnt;
}

A9.21) What is the output of the following program?

int main()
{
char *sptr= "HAL";
int cnt = 0;

for (cnt = 0; cnt < 3; cnt++)
*(sptr + cnt) =+ 1;

printf("sptr: %c\n",sptr);

return 0;
}

R: IBM

CHAPTER 13

A13.1) What is the difference between scanf( ) and gets( )?
R: scanf( ) only reads a single word, it reads characters until it encounters white space; gets( ) reads an entire string until '\n' is entered

A13.2) Write a program that reads two command line arguments. The first one is a string and the second one a file name. The program then should search the file, printing all lines that contain the string. Use fgets( ) rather than get( ). Hint: use the function strstr( ).

R:

int main()
{
char a[100], fileName[100], b[100];
FILE *fp;

printf ("Enter some text: ");
gets (a);

printf ("Enter the name of the file: ");
gets (fileName);
fp = fopen (fileName, "r");

if (fp == NULL)
{
printf("Error opening file.\n");
return 1;
}
else
{
while (!feof(fp))
{
fgets (b, sizeof (b), fp);
if (strstr (b,a) != NULL)
printf ("%s", b);
}
}

fclose (fp);
return 0;
}

A13.3) Find the error(s) in the following program segment;

int main ( )
{
int * fp;
int, k;
fp = fopen ("pizza");
for (k = 0; k < 30; k++)
printf ("Jill likes pizza.\n", fp);
fclose ("pizza");
return 0;
}

R:

int main ( )
{
FILE * fp;
int, k;
fp = fopen ("pizza"); // MISSING ACCESS CODE
for (k = 0; k < 30; k++)
fprintf (fp, "Jill likes pizza.\n");
fclose (fp);
return 0;
}

A13.4) Suppose we have these statements in a program

FILE *fp1, *fp2;
char ch;

fp1 = fopen ("file1", "r");
fp2 = fopen ("file2", "w");

Assuming that both files opened successfully, supply the missing arguments in the following function calls:

a) fscanf (___, "%c", &ch);
R: fp1

b) fprintf (___, "%c\n", ch);
R: fp2

c) fclose (___); /* close the file for writing */
R: fp2

A13.5) What is the output of the following program? Include in your answer the contents of any files created.

int main()
{
FILE *fp;
int k;
char ch;

fp = fopen ("file.txt", "w");

if (fp == NULL)
{
printf("Error opening file.\n");
return 1;
}
else
{
for (k = 2; k < 20; k+=2)
fprintf (fp, "%3d", k);

fclose (fp);
fp = fopen ("file.txt", "r");

while ((ch = fgetc(fp)) != EOF)
{
if (ch == ' ')
fputc ('*', stdout);
else if (ch != '1')
fputc (ch, stdout);
else
{
putchar ('\n');
putchar (ch);
}
}
}

return 0;
}

R:

Output Screen

**2**4**6**8*
10*
12*
14*
16*
18*

Output File

2 4 6 8 10 12 14 16 18

A13.6) Based on the statement below:

fp = fopen ("names.dat", "w");

a) What is the statement to declare this file pointer?
R: FILE *fp;

b) Write a statement that writes the string "Rock my heart" to the file.
R: fprintf (fp, "Rock my heart");

c) Write a statement that closes the file.
R: fclose (fp);

A13.7) With the following declarations:

double x;
int n;
char ch, str[40];

Indicate the contents of the variables after each of the following input operations are performed. Assume that the file accessed by fp consists of the data given and that each statement below occurs at the beginning of the program immediately after a statement that opens the file.

123 3.145 xyz<newline>35 z<newline>

a) fscanf (fp, "%d%lf%s%c", &n, &x, str, &ch);

R:
n = 123
x = 3.145
str = xyz
ch = '\n'
b) fscanf (fp, "%d%lf", &n, &x);
fscanf (fp, "%s %c", str, &ch);

R:
n = 123
x = 3.145
str = xyz
ch = 3

c) fscanf (fp, "%lf%d%c%s", &x, &n, &ch, str);

R:
n = 3
x = 123
str = 145
ch = '.'

d) Write the statement that opens this file.

R:

FILE *fp;


fp = fopen (_______, r);

A13.8) What does this program do?

int main()
{
FILE *fp;
char str[80];
fp = fopen ("file.txt", "w");

if (fp == NULL)
{
printf("Error opening file.\n");
return 1;
}
do
{
printf ("Enter a string (ENTER to quit): ");
gets (str);
strcat(str, "\n");
fputs (str,fp);
} while (*str != '\n');

return 0;
}

R: Concatenates the string entered by the user with a <newline>. Writes str to the file until the user presses ENTER.

9) What does this program do? Modify it so that it does the same thing for a file rather than for what is printed to the screen.

#define STOP '|'

int main()
{
char c;
int n_chars, n_lines, n_words;
int wordflag = 0;
n_chars = n_lines = n_words = 0;

while ((c = getchar()) != STOP)
{
n_chars++;

if (c == '\n')
n_lines++;

if (c != ' ' && c != '\n' && c != '\t' && wordflag ==0)
{
wordflag = 1;
n_words++;
}

if ((c == ' ' || c == '\n' || c == '\t') && wordflag ==1)
wordflag = 0;
}

n_lines++;
printf ("characters = %d, words = %d, lines = %d\n", n_chars, n_words, n_lines);

return 0;
}

R: Counts characters, words, and lines.

int main()
{
FILE *fp;
char c;
int n_chars, n_lines, n_words;
int wordflag = 0;

fp = fopen ("file.txt", "r");
n_chars = n_lines = n_words = 0;

while (!feof(fp))
{
c = getc(fp);
n_chars++;

if (c == '\n')
n_lines++;

if (c != ' ' && c != '\n' && c != '\t' && wordflag ==0)
{
wordflag = 1;
n_words++;
}

if ((c == ' ' || c == '\n' || c == '\t') && wordflag ==1)
wordflag = 0;
}

n_lines++;
printf ("characters = %d, words = %d, lines = %d\n", n_chars, n_words, n_lines);

return 0;
}

10) Based on the file data.txt, create a program that reads the file and outputs its content to the screen, with the appropriate headers (ex: Name, ID, Quiz 1, Quiz 2, Quiz 3, Quiz 4, Exam). Allow the user to view the data in "chunks", asking him to press any key in order to see the next "chunk". At the end, print a statistics table, showing the average, lowest, and highest scores on each quiz/exam.

R:

#include <stdio.h>
#include <conio.h>

typedef struct
{
char fname[10];
char lname[15];
int id;
int quiz1, quiz2, quiz3, quiz4, exam;
} STUDENT;

int findLow(STUDENT*, int, int);
int findHigh(STUDENT*, int, int);

int main()
{
STUDENT students[50];
FILE *fpr;
int i = 0;
int cnt = 0;
int sum[5] = {0};
float avg[5] = {0};
int low[5] = {0};
int high[5] = {0};

fpr = fopen("data.txt","r");

if (fpr == NULL)
{
printf("Error opening file!!\n");
}
else
{
printf("----- CLASS INFO -----\n\n");
printf(" Name\t\t ID\t Quiz1 Quiz2 Quiz3 Quiz4 Exam\n\n");

while (!feof(fpr))
{
fscanf(fpr, "%s%s%d%d%d%d%d%d", &students[i].fname,
&students[i].lname, &students[i].id,
&students[i].quiz1, &students[i].quiz2,
&students[i].quiz3, &students[i].quiz4,
&students[i].exam);

printf("%s %s\t %4d %3d %3d %3d %3d %3d\n",
students[i].fname, students[i].lname,
students[i].id, students[i].quiz1,
students[i].quiz2, students[i].quiz3,
students[i].quiz4, students[i].exam);

i++;
cnt++;

if ((i%16) == 0)
{
printf("\nPress any key to see the rest of the data\n\n");
getch();
}
}

for (i = 0; i < cnt; i ++)
{
sum[0] += students[i].quiz1;
sum[1] += students[i].quiz2;
sum[2] += students[i].quiz3;
sum[3] += students[i].quiz4;
sum[4] += students[i].exam;
}

printf("\n\nSTATISTICS\n\n");

printf("\t\tQuiz1 Quiz2 Quiz3 Quiz4 Exam\n\n");

//AVERAGES
printf("Average:\t");

for (i = 0; i < 5; i ++)
{
avg[i] = ((float)sum[i] / cnt);
printf("%5.1f\t", avg[i]);
}

printf("\n");

//LOWEST GRADES
printf("Lowest :\t");

for (i = 0; i < 5; i ++)
{
low[i] = findLow(students, i, cnt);
high[i] = findHigh(students, i, cnt);
}

for (i = 0; i < 5; i ++)
{
printf("%3d\t", low[i]);
}

printf("\n");


//HIGHEST GRADES
printf("Highest:\t");
for (i = 0; i < 5; i ++)
{
printf("%3d\t", high[i]);
}

printf("\n");

printf("\n----- END OF REPORT -----\n");
}

fclose(fpr);

return 0;
}

int findLow(STUDENT *stu, int x, int c)
{
int small;
int i;

if (x==0)
{
small = stu[0].quiz1;
for (i = 1; i < c; i ++)
{
if(small >= stu[i].quiz1 && stu[i].quiz1 > 0)
small = stu[i].quiz1;
}
return small;
}
else if (x==1)
{
small = stu[0].quiz2;
for (i = 1; i < c; i ++)
{
if(small >= stu[i].quiz2 && stu[i].quiz2 > 0)
small = stu[i].quiz2;
}
return small;
}
else if (x==2)
{
small = stu[0].quiz3;
for (i = 1; i < c; i ++)
{
if(small >= stu[i].quiz3 && stu[i].quiz3 > 0)
small = stu[i].quiz3;
}
return small;
}
else if (x==3)
{
small = stu[0].quiz4;
for (i = 1; i < c; i ++)
{
if(small >= stu[i].quiz4 && stu[i].quiz4 > 0)
small = stu[i].quiz4;
}
return small;
}
else if (x==4)
{
small = stu[0].exam;
for (i = 1; i < c; i ++)
{
if(small >= stu[i].exam && stu[i].exam > 0)
small = stu[i].exam;
}
return small;
}

return 0;
}

int findHigh(STUDENT *stu, int x, int c)
{
int big;
int i;

if (x==0)
{
big = stu[0].quiz1;
for (i = 1; i < c; i ++)
{
if(big <= stu[i].quiz1)
big = stu[i].quiz1;
}
return big;
}
else if (x==1)
{
big = stu[0].quiz2;
for (i = 1; i < c; i ++)
{
if(big <= stu[i].quiz2)
big = stu[i].quiz2;
}
return big;
}
else if (x==2)
{
big = stu[0].quiz3;
for (i = 1; i < c; i ++)
{
if(big <= stu[i].quiz3)
big = stu[i].quiz3;
}
return big;
}
else if (x==3)
{
big = stu[0].quiz4;
for (i = 1; i < c; i ++)
{
if(big <= stu[i].quiz4)
big = stu[i].quiz4;
}
return big;
}
else if (x==4)
{
big = stu[0].exam;
for (i = 1; i < c; i ++)
{
if(big <= stu[i].exam)
big = stu[i].exam;
}
return big;
}

return 0;
}

11) What is the output of the following program segment?

char *p;
p = strchr ("this is a test",'s');
printf ("%s\n",p);

R: s is a test

12) What is the output of the following program segment?

char *p;
p = strstr ("this is a test","is");
printf ("%s\n",p);

R: is is a test

13) What is the output of the following program segment?

int len;
len = strspn ("this is a test","isht");
printf ("%d\n",len);

R: 4

14) What is the output of the following program segment?

char *p;
p = strtok ("The summer soldier, the sunshine patriot"," ");
printf ("%s\n",p);

do
{
p = strtok (NULL,",");
if (p)
printf ("%s\n",p);
}
while (p);

R: will print out all the words, one per line.

15) What is the output of the following program segment?

char s1[10] = "abcdefghi";
char s2[10] = "ace";
char s3[10] = "defg";
char s4[10];
strcpy (s4, s2);
strcat (s4, s3);
strncat (s4, s1, sizeof(s4) - 1 - strlen (s2));
printf ("%s\n", s4);

R: acedefgabcdef

16) What is the output of the following program segment?

int d1, d2, d3, d4;
char s1[10] = "abcdefghi";
char s2[10] = "ace";
char s3[10] = "defg";
d1 = strspn (s1, s2);
d2 = strspn (s1, s3);
d3 = strcspn (s1, s2);
d4 = strcspn (s1, s3);
printf ("%d %d %d %d\n", d1, d2, d3, d4);

R: 1 0 0 3

17) What is the output of the following program?

int main()
{
struct gas
{
float distance;
float gals;
float mpg;
}

trip[3] = {{1000.0, 40.0, 0}, {400.0, 15.0, 0}, {500.0, 20.0, 0}};

struct gas *ps = trip;
int cnt = 1;
char add[5];

while (ps <= &trip[2])
{
ps -> mpg = ps -> distance / ps -> gals;
switch (cnt)
{
case 1:
strcpy (add, "st");
break;
case 2:
strcpy (add, "nd");
break;
case 3:
strcpy (add, "rd");
}

printf ("The %d%s calculated field is: %f\n", cnt, add, ps -> mpg);
ps++;
cnt++;
}

return 0;
}

R:

The 1st calculated field is: 25.0
The 2nd calculated field is: 26.66
The 3rd calculated field is: 25.00

18) Given the following declaration, what is the value of *x, *(x+1), and *(x+4)?

char *x = "Life is beautiful"

R:

*x = L
*(x+1) = i
*(x+4) = <space>

19) Would the value of the integer dif on the program segment below be positive, negative or zero?

char s1[] = "xyzt";
char *s2 = "xyAt";
int dif;
dif = strcmp (s1, s2);

R: positive

20) What is the output of the following program segment?

char s1[50] = "abcd";
char *s2 = "efghijklmno";
char *s3, *s4, *s5, *s6;
s3 = s1;
s4 = s2;
strcat (s1, s2);
s5 = strchr (s1, 'd');
s6 = strrchr (s2, 'n');
printf ("%s\n%s\n%s\n%s\n", s3, s4, s5, s6);

R:

abcdefghijklmno
efghijklmno
defghijklmno
no

21) What is the output of the following program segment?

char *s1 = "uabefgnpanm";
char s2[] = "ab";
char *s3 = "pan";
char s4[] = "bef";
char *s5 = "panam";
char *s6, *s7, *s8, *s9;
s6 = strstr (s1, s2);
s7 = strstr (s1, s3);
s8 = strstr (s1, s4);
s9 = strstr (s1, s5);
printf ("%s\n%s\n%s\n%s\n", s6, s7, s8, s9);

R:

abefgnpanm
panm
befgnpanm
<null>

22) What is the output of the following program segment?

char *s1 = "abefgnpanm";
char s2[] = "ab";
char *s3 = "pan";
char s4[] = "bef";
char *s5 = "panam";
int d1, d2, d3, d4;
d1 = strspn (s1, s2);
d2 = strspn (s1, s3);
d3 = strspn (s1, s4);
d4 = strspn (s1, s5);
printf ("%d\n%d\n%d\n%d\n", d1, d2, d3, d4);

R:
2
1
0
1
23) What is the output of the following program segment?

char *a[5] = {"cool", "groovy", "sweet", "dreading", "awesome"};
printf ("%s\n", a[0]);
printf ("%s\n", *(a+2));
printf ("%c\n", *(a[2]+2));
printf ("%s\n", a[3]);
printf ("%c\n", *(*(a+3)+4));

R:

cool
sweet
e
dreading
d

24) Modify the following code to use a string for the password. Use the function getch( ) to keep the password from showing up on the screen, instead type asterisks to the screen. You will need to read the characters into a character array, character by character.

int main()
{
int storedPass = 11862;
int numTries = 0;
int maxTries = 3;
int userPass;

while (numTries < maxTries)
{
printf ("Enter the password: ");
scanf ("%d", &userPass);
numTries++;

if (userPass == storedPass)
{
printf ("Welcome to the FBI file system.\n");
break;
}
else
{
printf ("Wrong password!");

if (numTries == maxTries)
{
printf ("Locked out!\n");
exit(0);
}
else if (numTries == (maxTries - 1))
printf ("%d more try.\n", maxTries - numTries);
else
printf ("%d more tries.\n", maxTries - numTries);
}
}

return 0;

}

R:

int main()
{
char storedPass[] = "123456";
char userPass[15], c;
int numTries = 0;
int maxTries = 3;
int cnt = 0;

while (numTries < maxTries)
{
printf ("Enter the password: ");

while (cnt < sizeof(userPass))
{
c = getch();
if (c != '\r') //user presses Enter
{
userPass[cnt] = c;
printf ("*");
cnt++;
}
else
break;
}

userPass[cnt] = '\0';

cnt = 0;
numTries++;
printf ("\n");

if (strcmp(storedPass, userPass) == 0)
{
printf ("Welcome to the FBI file system.\n");
exit(0);
}
else
{
printf ("Wrong password! ");

if (numTries == maxTries)
{
printf ("Locked out!\n");
exit(0);
}
else if (numTries == (maxTries - 1))
printf ("%d more try.\n", maxTries - numTries);
else
printf ("%d more tries.\n", maxTries - numTries);
}
}
return 0;
}

 

[Your opinion is important to us. If have a comment, correction or question
pertaining to this chapter please send it to comments@peoi.org .]