Week 2 - Arrays, Strings, Random Numbers and Functions Flashcards
In C, how do you declare a 1d array of 5 characters, initialised with 5 values?
char array[5] = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
In C, how do you declare an initialised 2d 2x3 array of ints?
int array[2][3] = { {1, 2, 3}, {4, 5, 6} };
Where is it guaranteed that arrays are stored in C?
In contiguous memory.
How do arrays reserve an appropriate amount of memory in C? Use example int array[10].
int array[10] reserved 10 x sizeof(int) = 10 * 4 bytes = 40 bytes saved for array.
What is another name for an array of chars in C?
String
In C, what variable type uses single quotes (‘’) and what uses double quotes (“”)?
A char uses single, a string uses double
In C, what does the null terminator do?
The null terminator is ‘\0’. It tells printf when to stop printing out characters
In C, how does memory get allocated for a string?
Memory allocated is number of characters plus one for the null terminator
What happens if your string doesn’t have a null terminator?
printf keeps going through memory and printing out characters until it encounters a null terminator (which is one reason arrays are stored contiguously)
How would you print out 3 characters of the string variable char animal[21]=”elephant” in C?
printf(“0.3s\n”, name);
How would you write this C code with width and precision? printf(“%20.10s\n”, “My elephants”);
int wid = 20;
int prec = 10;
char str[] = “My elephants”;
printf(“%.s\n”, wid,prec, str);
What do these special characters mean?
\n
\t
\v
\b
\r
\f
'
"
%%
\n - line-feed (new line)
\t - horizontal tab
\v - vertical tab
\b - backspace
\r - carriage return
\f - form-feed (new page)
\ - backslash
' - single quote
" - double quote
%% - percent sign
What do these C string functions do?
strlen(a)
strcpy(a, b)
strcat(a, b)
strcmp(a, “hello”)
sprintf(buffer, “%s %d”, a, b)
strlen(a) - returns the number of characters in variable name, not including the null terminator
strcpy() - copies the string a into b, including the null terminator
strcat(a, b) - concatenates b onto the end of a, overwriting a from first null terminator
strcmp(a, “hello”) - returns 0 if the two strings are the same, otherwise some other int value
sprintf(buffer, “%s %d”, a, b) - like printf, but places the result in buffer instead of printing it out
Give 3 features of pseudo-random numbers.
Generated by an algorithm
Repeats over a (hopefully) very long period
Look random but aren’t
Describe these random number distributions:
Uniform
Normal (Gaussian)
Poisson
Bernoulli
Gamma
Uniform - a distribution where all values in a defined range are equally likely
Normal (Gaussian) - the bell curve, a result of the Central Limit Theorem
Poisson - the distribution of a count
Bernoulli - the distribution of two mutually exclusive events (call them 0 and 1)
Gamma - a distribution of positive values only