22 November

Some examples of reference parameters

void swap(int& a, int& b)
{
int t = a;
a = b;
b = t;
}

void func(int a, int& b)
{
b = a+2;
a = a+1;
}

int main()
{
int x = 5, y = 3;
swap(x,y);
printf("%d,%d\n", x, y);
func(8,x); // okay
//func(x,8); // error.
return 0;
}

A quiz-like sample program

int grok(int& x, int y, int& z)
{
x = x + y;
y = x + z;
z = x + y;
return x+y+z;
}

int main()
{
int y = 2, z = 3, w = 4;
int b = grok(y,z,w);
printf("%d,%d,%d,%d\n", y,z,w,b);
return 0;
}

Using a reference parameter for Blackjack

void deal_one_card(int& rank, int& suit)
{
rank = rand()%13+1;
suit = rand()%4;
}

int main()
{
srand(time(NULL));
int rank=0, suit=0;
deal_one_card(rank, suit);
printf("%d of %d\n", rank, suit);
}

Arrays: numeric computation

const int SIZE = 100;
int main()
{
int a[SIZE]; // allocate SIZE slots for array

// initialize array to squares of indexes
for(int i = 0; i < SIZE; i++)
{
a[i] = i*i;
}

// sum of squares
for(int i = 1; i < SIZE; i++)
{
a[i] = a[i] + a[i-1];
}

// print array index and values
for(int i = 0; i < SIZE; i++)
{
printf("%d -> %d\n", i, a[i]);
}
return 0;
}

Arrays: tally how many rolls on 2 simulated dice

const int ROLLS = 1000;
const int DICE_SIDES = 6;
const int MAX_OF_2_DICE = DICE_SIDES*2;
int main()
{
srand(time(NULL));
int frequencies[MAX_OF_2_DICE+1];
// initialize array to all zeroes
for(int i = 0; i <= MAX_OF_2_DICE; i++)
{
frequencies[i] = 0;
}
// simulate rolling dice a lot
for(int i = 0; i < ROLLS; i++)
{
int roll1 = rand()%6+1;
int roll2 = rand()%6+1;
frequencies[roll1+roll2]++;
}
// print array
for(int i = 1; i <= MAX_OF_2_DICE; i++)
{
printf("%d -> %d\n", i, frequencies[i]);
}
return 0;
}

©2011 Christopher League · some rights reserved · CC by-sa