Starting point
Use the first element as the provisional minimum and maximum.
C programming · Lesson
Keep two candidates while traversing the array: a new value replaces them only when it is smaller or larger.
Minimum and maximum start from the first element, not from an invented value. Every later element is compared with both.
min=max=v[0] → visit v[i] → update min and/or max → continue
The flowchart keeps algorithm control visible; the Array Lab below makes cells, indices, comparisons, candidates and swaps visible.
Indices stay visible at all times. Sorting traces highlight comparisons, the current candidate, swaps and the region already sorted.
Use the first element as the provisional minimum and maximum.
new maximum 7
new minimum 2
new maximum 9
new minimum 1
Traversal ends with minimum 1 and maximum 9.
Run C executes only the example shown on the left, using stdin on the right. The coding challenge below has a separate editor and test button.
1#include <stdio.h>
2
3int main(void)
4{
5 int v[5] = {4, 7, 2, 9, 1};
6 int minimo = v[0];
7 int massimo = v[0];
8
9 for (int i = 1; i < 5; i = i + 1)
10 {
11 if (v[i] < minimo)
12 minimo = v[i];
13
14 if (v[i] > massimo)
15 massimo = v[i];
16 }
17
18 printf("%d\n", minimo);
19 printf("%d\n", massimo);
20 return 0;
21}
Read five integers and print minimum and maximum separated by one space.
This is a different program from lab 1. Complete the starter code: Check all test cases compiles this editor and tests every input, including boundary cases.
For {4, 7, 2, 9, 1}, what are the minimum and maximum?
Challenge 1 / 5 · Understanding
Progress: 0 / 5 · correct: 0
ConceptStep separates what is required from what is recommended or useful as reinforcement. Only required prerequisites block your progress.
Relationships: solid line = required · dashed line = recommended · dotted line = reinforcement.