What is the purpose of a loop in C?
To repeat a block of code multiple times until a condition is met or no longer true.
What is the syntax of a for loop?
for (initialization; condition; increment) { /* code */ }
What library must be included to use rand() and srand()?
#include <stdlib.h>
What is the difference between an array index and an element?
The index is the position number; the element is the value stored at that position.
What happens if you access an array element beyond its size?
Undefined behavior: it may crash or give garbage values.
What does break; do in a loop?
It exits the loop immediately.
What is a pre-test loop? Give an example using while.
A loop that checks the condition before running.
How do you seed the random number generator with the current time and what library do you need to include?
srand(time(NULL));
requires #include <time.h>
Declare and initialize a 1D array of 5 integers in C.
int arr[5] = {1, 2, 3, 4, 5};
Write a loop to copy values from one array to another (size 5).
for (int i = 0; i < 5; i++) {
b[i] = a[i]; }
What does continue; do in a loop?
It skips the rest of the loop body and moves to the next iteration.
What is a post-test loop? Give an example using do...while.
A loop that runs first and checks condition after.
What does rand() % 10 return?
A random number between 0 and 9.
Use a loop to fill a 10-element array with random numbers.
for (int i = 0; i < 10; i++){
arr[i] = rand() % 100 + 1; }
Write a loop to reverse a 1D array in-place.
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n-1-i];
a[n-1-i] = temp; }
What does return; do inside a function?
It exits the function and optionally returns a value.
Write a while loop that counts down from 10 to 1.
int i = 10; while (i >= 1) { printf("%d\n", i); i--; }
Write code to generate a random number between 20 and 50.
int num = rand() % 31 + 20;
Declare a 2D array with 3 rows and 4 columns.
int arr[3][4] = {0};
Explain the difference between element position and index.
Index starts from 0; position is index + 1.
What does this loop output?
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
printf("* "); }
printf("\n"); }
What is an infinite loop? Write one using for.
A loop that never ends.
for (;;) { /* endless */ }
Write a loop that prints 5 random numbers from 1 to 100.
srand(time(NULL));
for (int i = 0; i < 5; i++) {
printf("%d\n", rand() % 100 + 1); }
Write a nested loop to print all elements of a 3x3 array.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]); }
printf("\n"); }
Copy values from a[3][3] to b[3][3] using nested loops.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = a[i][j]; } }