0% found this document useful (0 votes)
112 views6 pages

Pass by Reference Tracing Example

The document provides instructions and information for an exam on functions in C programming. It states that functions should use formal parameters, not ignore them. It also provides examples of function output and discusses character processing, including built-in functions and macros. Finally, it gives an example of passing structures by reference and calculating distance between points.

Uploaded by

Austin VanDyne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views6 pages

Pass by Reference Tracing Example

The document provides instructions and information for an exam on functions in C programming. It states that functions should use formal parameters, not ignore them. It also provides examples of function output and discusses character processing, including built-in functions and macros. Finally, it gives an example of passing structures by reference and calculating distance between points.

Uploaded by

Austin VanDyne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 6

For the exam, please remember the following: when I ask you

to write a function, DO NOT TRY TO READ IN THE


VALUES OF THE FORMAL PARAMETERS, UNLESS I
EXPLICITLY TELL YOU TO DO SO. The job of a function
is to USE the formal parameters, NOT IGNORE THEM!!!

Recapping, the entire output of this program is:


a=-3,b=13
a=5,b=2,c=16,d=-3
a=24,b=32
a=24,b=2,c=16,d=-3
a=0,b=16
a=24,b=16,c=0,d=-3
a=40,b=13
a=13,b=16,c=0,d=40

Character Processing
Remember internally, characters are stored as integers. These
integers are the characters' ascii values. Because the uppercase
letters, lowercase letters and digits are stored "in order", some
tasks that involve processing characters can be simplfied.
Consider the following idea:
If we were counting the frequency of lowercase letters in a file
that was known to be all lowercase letters, we could store the
frequency information in a frequency array:
int freq[26];
Now, if we read in a character and store it in the char variable
c, we could do the following to adjust the frequency:
freq[c-'a']++;
The functions getchar() and putchar() allow you to read and
print out characters individually, without ignoring whitespace.
Some of the macros from ctype.h will be useful:
Macros from ctype.h
int isalpha(int c);
int isdigit(int c);
int islower(int c);
int isupper(int c);
int tolower(int c);
int toupper(int c);
Pass by Reference Tracing Example

#include <stdio.h>
#include <math.h>
typedef struct {
double x;
double y;
} point_t;
double dist(const point_t* ptrP, const point_t* ptrQ);
int main() {
point_t p1, p2;
// Read in two points.
printf("Enter one x y coordinate.\n");
scanf("%lf%lf", &p1.x, &p1.y);
printf("Enter a second x y coordinate.\n");
scanf("%lf%lf", &p2.x, &p2.y);

In debugging and creating code, its imperative to understand the process the computer uses
with both pass by value and pass by reference parameters. The following example illustrates
the details of many situations that might arise. Keep in mind that the following code is NOT
// Calculate distance in main.
meant to be written to solve a problem. In fact, its intentionally written to be confusing.
printf("The distance from (%.2lf, %.2lf) to (%.2lf, %.2lf) is ", p1.x, p1.y, p2.x,
But, if one can trace through this example, she should be able to understand what is
transpiring in any situation with function calls, at least with respect to the mechanics of p2.y);
double distance = sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2));
what is going on.
printf("%.2lf\n", distance);
Here is the program:
// Use a function to do the same thing.
#include <stdio.h>
double altdistance = dist(&p1, &p2);
printf("With a function, we get: %.2lf.\n", altdistance);
int f1(int *a, int b);
return 0;
int f2(int a, int *b);
}
int main() {
int a = 5, b = 2, c = 7, d = 9;
c = f1(&d, a);
printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d);
a = f2(c - d, &a);
printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d);
b = f1(&c, 8);
printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d);
d = f2(b, &a);
printf("a=%d,b=%d,c=%d,d=%d\n",a,b,c,d);
return 0;
}
int f1(int *a, int b) {
*a = b - 8;
b = b*2 - (*a);
printf("a=%d,b=%d\n",*a,b);
return b - *a;
}
int f2(int a, int *b) {
a = *b + a;
*b = 37 - *b;
printf("a=%d,b=%d\n",a,*b);
return a;
line 32
}

// Returns the distance between the points pointed to by ptrP and ptrQ.

// line 8
// line 10
// line 11
// line 12
// line 13

double dist(const point_t* ptrP, const point_t* ptrQ) {


return sqrt(pow(ptrP->x - ptrQ->x, 2) + pow(ptrP->y - ptrQ->y, 2));
}
int i, j;
for (j=0; j<2; j++) {
P = 0;
O = 0;
for (i=j; i<COLS; i++) {
if (board[i][j] == '.')
O++;
else if (board[i][j] == 'P' && board[i+1][j] == 'P')
P++;
}
if (P > 0 && O > 0)
return 1;
}
return 0;

// line 14
// line 15
// line 16
// line 17
//
//
//
// line 24
//

line 21
line 22
line 23
line 25

// line 28
// line 29
// line 30
// line 31
//

}
//Check left side for moves
int check3(char board[][COLS]) {
int P, O = 0;
int i,j;
for (j=0; j<COLS; j++) {
P = 0;
O = 0;

// Peg Game

for (i=j; i<j+2; i++) {


if (board[i][j] == '.')
O++;
else if (board[i][j] == 'P' && board[i+1][j+1] == 'P')
P++;
}
if (P > 0 && O > 0)
return 1;

#include <stdio.h>
#define ROWS 5
#define COLS 5
#define GOOD 1
void printBoard(char board[ROWS][COLS]);
int checkBoard(char board[ROWS][COLS]);
int check1(char board[ROWS][COLS]);
int check2(char board[ROWS][COLS]);
int check3(char board[ROWS][COLS]);
int main() {
int i, j, playsleft;
char board[ROWS][COLS];
// Initialize the game board.
for (i=0; i<ROWS; i++)
for (j=0; j<i+1; j++)
board[i][j] = 'P';
// Place an . on the starting peg
board[2][1] = '.';
// Print out the board.
printBoard(board);
while (checkBoard(board)) {
// Ask for user input
int startR, startC, endR, endC, jumpedR, jumpedC;
printf("What are the row and column of your starting peg?\n");
scanf("%d%d", &startR, &startC);
startR--;
startC--;
printf("What are the row and column of the hole to jump to?\n");
scanf("%d%d", &endR, &endC);
endR--;
endC--;
//Find out what space was jumped
if (startR == endR)
jumpedR = startR;
else
jumpedR = (startR+endR)/2;
if (startC == endC)
jumpedC = startC;
else
jumpedC = (startC+endC)/2;

}
return 0;
}
//Check if there are any moves left on the board
int checkBoard(char board[][COLS]) {
if (check1(board) || check2(board) || check3(board))
return 1;
else
return 0;
}
//prints the game board before the move
void printBoard(char board[][COLS]) {
int i, j;
printf("Here is the playing grid:\n");
for (i=0; i<ROWS; i++) {
if (i == 0)
printf("
");
if (i == 1)
printf("
");
if (i == 2)
printf(" ");
if (i == 3)
printf(" ");
for (j=0; j<i+1; j++) {
printf("%c ", board[i][j]);
}
printf("\n");
}
}
//Returns the total numbers of pegs on the board.
int checkPegs(char board[][COLS]) {
int pegs = 0;
int i, j;
for (i=0; i<COLS; i++) {
for (j=0; j<i+1; j++) {
if (board[i][j] == 'P')
pegs++;
}
}
return pegs;
}

//Move the pegs around on the board


board[jumpedR][jumpedC] = '.';
board[startR][startC] = '.';
board[endR][endC] = 'P';
printBoard(board);
}
//Print final message once there are no moves left.
int numpegs;
numpegs = checkPegs(board);
printf("No more jumps are possible. You have left %d pegs.\nGood bye!", numpegs);
return 0;
}
//check bottom two rows for moves
int check1(char board[][COLS]) {
int P, O;
int i, j;
for (i=3; i<COLS; i++) {
P = 0;
O = 0;
for (j=0; j<i+1; j++) {
if (board[i][j] == '.')
O++;
if (board[i][j] == 'P' && board[i][j+1] == 'P')
P++;
}
if (P > 0 && O > 0)
return 1;
}
return 0;
}
//Check Right side for moves
int check2(char board[][COLS]) {

vice versa, with everything mapping linearly in between.


void invertColors(int pic[][WIDTH]) {
int i, j; // 1 pt
for (i=0; i<HEIGHT; i++) // 2 pts
for (j=0; j<WIDTH; j++) // 2 pts
pic[i][j] = 255 - pic[i][j]; // 5 pts // LHS = 1 pt
// RHS = 4 pts
}6) (10 pts) Write a function that takes in an image and reflects the picture along the vertical line
that divides the picture in two. Intuitively, the function will change the picture to be its own
mirror image. Specifically, for each pixel of the form pic[i][0] should be swapped with each
pixel of the form pic[i][WIDTH-1], each pixel of the form pic[i][1] should be swapped with the
pixel of the form pic[i][WIDTH-2], each pixel of the form pic[i][2] should be swapped with the
pixel of the form pic[i][WIDTH-3], etc. Note that the resulting picture has no new pixel values,
but each pixel has moved to a different location in the picture than where it was previously.
void mirrorImage(int pic[][WIDTH]) {
int i, j; // 1 pt
for (i=0; i<HEIGHT; i++) { // 2 pts
for (j=0; j<WIDTH/2; j++) { // 3 pts
int tmp = pic[i][j]; // 1 pt
pic[i][j] = pic[i][WIDTH-1-j]; // 2 pts
pic[i][WIDTH-1-j] = tmp; // 1 pt
}
}

int P, O = 0;

Spring 2014 COP 3223 Section 4 Final Exam Solutions


Note: You may declare extra variables for any of the following questions.
1) (10 pts) An ice cream cone costs $3 and a sundae costs $5. Complete the program below so
that it prompts the user for how many ice cream cones they want to buy and how many sundaes
they want to buy and prints out their final total. (Note: Tax is already included in the prices listed
above.)
#include <stdio.h>
int main() {
int cones, sundaes;
printf(How many ice cream cones do you want to buy?\n);
scanf(%d, &cones);
printf(How many sundaes do you want to buy?\n);
scanf(%d, &sundaes);
// printf = 1, () = 1, = 1, %d = 1, comma = 1
// formula = 5, 2 for each mult 1 for add
printf("Your total cost is $%d.\n", 3*cones + 5*sundaes);
return 0;
}
2) (10 pts) Paper costs $5 per ream. Its also sold in large boxes of 100 reams each for $300.
Complete the program below so that it prompts the user to enter the number of reams of paper
they need and prints out the minimum cost to buy at least than may reams of paper.
#include <stdio.h>
int main() {
int reams;
printf(How many reams of paper do you want to buy?\n);
scanf(%d, &reams);
// Grading: 2 pts correct expression for if
// 4 pts for > 60 case, 3 pts boxes only, 1 pt correct # boxes
// 4 pts for <= 60 case, 2 pts for each component
if (reams%100 > 60)
printf("You must spend $%d.\n", 300*(reams/100+1));
else
printf("You must spend $%d.\n", 300*(reams/100)+5*(reams%100));
return 0;
}3) (10 pts) Jacqueline runs 2 miles every weekday and 5 miles every weekend day. Assume that
day 0 is a Monday. Complete the program below so that takes a starting day number and an
ending day number from the user and prints out a report with a daily log of how far Jacqueline
ran that day and the total number of miles she ran up to that day, counting from the start day. For
example, if the user entered 4 for the starting day and 8 for the ending day, then the print out
should look like:
Day Miles Total
4 2 2
5 5 7
6 5 12
7 2 14
8 2 16
#include <stdio.h>
int main() {
int start, end, i, total = 0;
printf(Enter the starting and ending day.\n);
scanf(%d%d, &start, &end);
printf("Day\tMiles\tTotal\n"); // 0 pts
for (i=start; i<=end; i++) { // 2 pts
int day = 2; // These 3
if (i%7 > 4) // lines are
day = 5; // 4 pts
total += day; // 1 pt
printf("%d\t%d\t%d\n", i, day, total); // 3 pts 1
} // for each
return 0;
}
4) (8 pts) Describe what each of the following four string functions in string.h do.
strcmp: Makes a lexicographical comparison between two strings. (2 pts) In laymens terms,
this is similar to an alphabetical comparison. It returns a negative integer if the first
parameters comes before the second, 0 if theyre equal and a positive integer if the first
parameter comes after the second. (Only the first sentence is needed, and just
comparison is good enough.)
strlen: Returns the length of a string. (2 pts)
strcat: Concatenates the second string to the end of the first. (2 pts)
strcpy: Copies the contents of the second string into the first. (2 pts)5) (10 pts) The next two questions concern
manipulating grayscale picture images. These images
can be stored in two dimensional integer arrays with each value in the array ranging from 0
(black) to 255 (white). Functions that edit pictures take in the picture as a two dimensional
integer array and then make the appropriate changes to each pixel of the array. The function
below lightens each pixel by adding 10 to its value, with a maximum of 255:
#define HEIGHT 200
#define WIDTH 300
void lighten(int pic[][WIDTH]) {
int i, j;
for (i=0; i<HEIGHT; i++) {
for (j=0; j<WIDTH; j++) {
pic[i][j] += 10;
if (pic[i][j] > 255)
pic[i][j] = 255;
}
}
}
Write a function that takes in an image like the function above and flips the grayscale value of
each pixel. To flip pixel values, note that we want to replace a value of 0 with 255, a value of 1

}
7) (10 pts) Complete the function below so that it takes in an int array, the length of the array,
and a minimum value and returns the number of values in the array that are greater than or equal
to that minimum value. For example, if we gave the function the array [23, 12, 18, 16, 18, 22]
and a minimum value of 18, it should return 4, since 23, 18, 18 and 22 are at least as big as 18.
int numMeetThreshold(int array[], int length, int minimum) {
int cnt = 0, i; // 1 pt
for (i=0; i<length; i++) // 3 pts
if (array[i] >= minimum) // 3 pts
cnt++; // 2 pts
return cnt; // 1 pt
}8) (10 pts) Complete the function below so that it returns 1 if the second string is a substring of
the first string. A substring is a contiguous portion of a given string. For example baseball
contains the substrings base, ball, sebal and baseball. It does NOT contain the substrings
sb, baseballs or sell.
int contains(char str[], char sub[]) {
int i, j;
int lenStr = strlen(str);
int lenSub = strlen(sub);
for (i=0; i <= lenStr-lenSub; i++) { // 2 pts
int cnt = 0;
for (j=0; j < lenSub; j++) // 2 pts
if ( sub[j] == str[i+j] ) // 3 pts
cnt++;
if ( cnt == lenSub ) // 2 pts
return 1;
}
return 0 ; // 1 pt
}
9) (10 pts) The struct shown below stores a fraction. Write a method that takes in two struct
fractions and returns a struct fraction representing the sum of the two input fractions. Do not
reduce the resultant fraction (for ease of grading) and dont worry about overflow errors.
struct fraction {
int num;
int den;
};
struct fraction add(struct fraction op1, struct fraction op2) {
struct fraction ans; // 1 pt
ans.num = op1.num*op2.den + op2.num*op1.den; // 5 pts
ans.den = op1.den*op2.den; // 3 pts
return ans; // 1 pt
}10) (10 pts) Using the same fraction struct from the previous question, write a fraccmp function
that returns a positive integer if the first fraction is bigger than the second, 0 if the two are
equivalent in value, and a negative integer if the first is smaller than the second. For example, if
a = 3/5, b = 1/2 and c = 6/10, fraccmp(a,b) should return a positive integer, fraccmp(b,c) should
return a negative integer, and fraccmp(a,c) shold return 0. The struct definition is given for you
again below. YOU MAY ASSUME THAT BOTH op1 and op2 represent positive fractions.
struct fraction {
int num;
int den;
};
int fraccmp(struct fraction op1, struct fraction op2) {
return op1.num*op2.den op2.num*op1.den;
// Grading: Most will write more than this.
// 3 pts for numerator of first fraction
// 3 pts for numerator of second fraction
// 4 pts for returning accordingly
}
11) (2 pts) What is the first name of the author of I am Malala, the autobiographical account of a
young human rights advocate?
Malala (2 pts give to all)

with 254, a value of 2 with 253, etc. Basically, the darkest pixels become the lightest ones and

// Solution to COP 3223 Program #3: Casino


#include <stdio.h>

char dummy[50];

else

// variables storing the user's amount of cash and number of chips,

#include <stdlib.h>
#include <time.h>
// Costs for buying and selling a chip.
#define CHIP_BUY 11
#define CHIP_SELL 10
// Used to determine the status of a game.
#define WIN 1
#define LOSS 0
#define CONTINUE 2
int pairofdice();
int craps();
int craps_outcome(int roll);
int arupsdice();
int arups_outcome(int roll);
void statusreport(int numchips, int cash);
int buychips(int *cash);
int sellchips(int numchips);
void dobuy(int *cash, int *numchips);
void dosell(int *cash, int *numchips);
int menu();
int validchips(int *chipsbet, int numchips);
int main() {
// Set up variables and initial values.
int choice, cash=1000;
int numchips=0, chipsbet, numsell;
srand(time(0)); // Initialize random number generator.
// Continue until the user quits.
while ((choice = menu()) != 6) {
// Execute the appropriate choice.
if (choice == 1) {
dobuy(&cash, &numchips);
}
else if (choice == 2) {
dosell(&cash, &numchips);
}
else if (choice == 3) {
// Only play if a valid number of chips is bet.
if (validchips(&chipsbet, numchips)) {
// Adjust current number of chips based on the game outcome.
if (craps())
numchips += chipsbet;
else
numchips -= chipsbet;
}
}
else if (choice == 4) {
// Only play if a valid number of chips is bet.
if (validchips(&chipsbet, numchips)) {
// Adjust current number of chips based on the game outcome.
if (arupsdice())
numchips += chipsbet;
else
numchips -= chipsbet;
}
}
else if (choice == 5) {
statusreport(numchips, cash);
}

// Execute the first die roll.


printf("Press 'r' and hit enter for your first roll.\n");
scanf("%s", dummy);
first_roll = pairofdice();
printf("You rolled a %d.\n", first_roll);
// Determine the current game status.
status = craps_outcome(first_roll);
// Deal with the cases where the game is already over.
if (status == WIN) {
printf("You win!\n");
return WIN;
}
else if (status == LOSS) {
printf("Sorry, you have lost.\n");
return LOSS;
}

// Roll the next die.


printf("Press 'r' and hit enter for your next roll.\n");
scanf("%s", dummy);
roll = pairofdice();
printf("You rolled a %d.\n", roll);
// Check to see if the game has ended. Return the appropriate value.
if (roll == first_roll) {
printf("You win!\n");
return WIN;
}
else if (roll == 7) {
printf("Sorry, you have lost.\n");
return LOSS;
} }}
// Returns the status of a craps game based on the first roll.
int craps_outcome(int roll) {
// Check for a win or a loss and return the proper value.
if (roll == 7 || roll == 11)
return WIN;
else if (roll == 2 || roll == 3 || roll == 12)
return LOSS;
// The game continues.
else
return CONTINUE;

}
// Returns an integer in between 2 and 12, inclusive, representing the
// result of rolling two fair six-sided dice.
int pairofdice() {
int d1, d2;
d1 = 1 + rand()%6; // Result of die 1.
d2 = 1 + rand()%6; // Result of die 2.
return d1+d2;
}
// Let's the user play craps. Returns 1 if the user wins, 0 otherwise.
int craps() {
int first_roll, roll, status;

// Checks for the immediate win or loss.


if (roll == 11 || roll == 12)
return WIN;
else if (roll == 2)
return LOSS;
// The game will continue for a second roll.
else
return CONTINUE;
}

// Go ahead and execute the second die roll if necessary.


if (status == CONTINUE) {

// Ask the user how much they want to spend.


printf("How much cash do you want to spend for chips?\n");
scanf("%d", &tospend);
// Print out the error message if this is too much.
if (tospend > *cash)
printf("Sorry, you do not have that much money. No chips bought.\n");
// Execute the transaction.
else {
(*cash) -= tospend; // Spend the cash.
(*numchips) += buychips(&tospend); // Get the chips.
(*cash) += tospend; // Add the change from the transaction to cash.
}
}
// Executes selling chips. Both cash and numchips are pointers to the
// variables storing the user's amount of cash and number of chips,
// respectively.
void dosell(int *cash, int *numchips) {
int numsell;
// Determine the number of chips to be sold.
printf("How many chips do you want to sell?\n");
scanf("%d", &numsell);

// Adjusts the variable pointed to by cash to equal the change received


// from purchasing the maximum possible number of chips for the value
// of that variable, originally. Returns the total number of purchased
// chips.
int buychips(int *cash) {

// Print out the error message if this is too much.


if (numsell > *numchips)
printf("Sorry, you do not have that many chips. No chips sold.\n");
// Execute the transaction.
else {
(*cash) += sellchips(numsell);
(*numchips) -= numsell;
}

int numchips = (*cash)/CHIP_BUY;


(*cash) -= CHIP_BUY*numchips;
return numchips;
}
}
// Returns the cash gained by selling numchips chips.
int sellchips(int numchips) {
return CHIP_SELL*numchips;
}
// Prints out the menu for the user and returns the user's choice.
int menu() {
int ans;
printf("Welcome to the Casino. Here are your choices:\n");
printf("1) Buy chips\n");
printf("2) Sell chips\n");
printf("3) Play craps\n");
printf("4) Play Arup's Game of Dice\n");
printf("5) Status Report\n");
printf("6) Quit\n");
scanf("%d", &ans);
return ans;

int first_roll, second_roll, status;


char dummy[50];

// Determine the current game status.


status = arups_outcome(first_roll);

int tospend;

// Prints out the user's current status.


void statusreport(int numchips, int cash) {
printf("You currently have $%d left and %d chips.\n", cash, numchips);
}

}
// Let's the user play Arup's Game of Dice.
// Returns 1 if the user wins, 0 otherwise.
int arupsdice() {

// Execute the first die roll.


printf("Press 'r' and hit enter for your first roll.\n");
scanf("%s", dummy);
first_roll = pairofdice();
printf("You rolled a %d.\n", first_roll);

// respectively.
void dobuy(int *cash, int *numchips) {

}
// Returns the status of Arup's Game of Dice, based on the first roll.
int arups_outcome(int roll) {

// Continue rolling a die until the game ends.


while (1) {

}
// Sell the remaining chips and print out the final message.
cash += sellchips(numchips);
printf("After selling your chips, you have $%d.",cash);
printf(" Thanks for playing!\n");

status = LOSS;
}
// Return the final outcome of the game.
if (status == WIN) {
printf("You win!\n");
return WIN;
}
else {
printf("Sorry, you have lost.\n");
return LOSS;
}

}
// Determines if the user has entered a valid number of chips to bet.
// chipsbet is a pointer to the variable storing the number of chips the
// user is betting and numchips is the current number of chips the user
// has. 1 is returned if the bet is valid, 0 is returned otherwise.
int validchips(int *chipsbet, int numchips) {
// Read in the number of chips the user wants to bet.
printf("How many chips would you like to bet?\n");
scanf("%d", chipsbet);

// Execute the second die roll.


printf("Press 'r' and hit enter for your next roll.\n");
scanf("%s", dummy);
second_roll = pairofdice();
printf("You rolled a %d.\n", second_roll);
// Determine if the user won or not.
if (second_roll > first_roll)
status = WIN;

// Determine if the amount is valid or not.


if (*chipsbet == 0 || *chipsbet > numchips) {
printf("Sorry, that is not allowed. No game played.\n");
return 0;
}
return 1;
}
// Executes buying chips. Both cash and numchips are pointers to the

You might also like