Week 6: Arrays, Randomness, and Control Flow (solution)
Week 6: Arrays, Randomness, and Control Flow (solution)
Exercise 1: Count how many even numbers are in an array.
- Ask the user to enter 10 integers into a 1D array.
- Print how many of them are even.
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main(void) {
int arr[10], even = 0;
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
even += (arr[i] % 2 == 0);
}
printf("Number of even values: %d\n", even);
return 0;
}
Example Output:
1
Number of even values: 4
Exercise 2: Calculate the sum of a 2D array.
- Ask the user to input a 3x3 matrix
- Print the total sum of all elements.
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main(void) {
int arr[3][3], sum = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
scanf("%d", &arr[i][j]);
sum += arr[i][j];
}
printf("Sum: %d\n", sum);
return 0;
}
Example Output:
1
Sum: 45
Exercise 3: CFill an array with random numbers and find the maximum.
- Use
rand()
to generate 10 random numbers - Print the largest number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int arr[10], max;
srand(time(0));
for (int i = 0; i < 10; i++)
{
arr[i] = rand() % 100;
printf("arr[%d]: %d\n", i, arr[i]);
if (i == 0 || arr[i] > max)
max = arr[i];
}
printf("Max: %d\n", max);
return 0;
}
Example Output:
1
Max: 92
Exercise 4: Work with Variable-Length Arrays.
- Ask the user how many elements they want to enter
- Create a VLA and store those values
- Print them in entered order
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
int main(void)
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements:\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("The elements in entered order are:\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Example Output:
1
2
3
4
5
6
7
8
9
Enter the number of elements: 5
Enter the elements:
1
2
3
4
5
The elements in entered order are:
1 2 3 4 5
Bonus Challenge: Matrix Diagonal Sum
Ask the user to input a 3x3 matrix and print the sum of the diagonal elements.
1
This post is licensed under CC BY 4.0 by the author.