Pass by Reference Tracing Example
Pass by Reference Tracing Example
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
// 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
#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;
}
int P, O = 0;
}
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
char dummy[50];
else
#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);
}
}
// 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;
int tospend;
}
// Let's the user play Arup's Game of Dice.
// Returns 1 if the user wins, 0 otherwise.
int arupsdice() {
// 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) {
}
// 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);