Algorithms
Transform Array
A transform loop writes a derived value for each input element.
input to output
Each output element is computed from the matching input element.
factor
Changing one scalar factor changes every transformed value.
Transform Array
transform_array.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int factor = 2;
int input[3] = {1, 2, 3};
int output[3] = {0, 0, 0};
int total = 0;
for (int i = 0; i < 3; i++) {
output[i] = input[i] * factor;
total += output[i];
}
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int factor = 3;
int input[3] = {1, 2, 3};
int output[3] = {0, 0, 0};
int total = 0;
for (int i = 0; i < 3; i++) {
output[i] = input[i] * factor;
total += output[i];
}
printf("total=%d\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
int factor = 4;
int input[3] = {1, 2, 3};
int output[3] = {0, 0, 0};
int total = 0;
for (int i = 0; i < 3; i++) {
output[i] = input[i] * factor;
total += output[i];
}
printf("total=%d\n", total);
return 0;
}
factor ← 2, input ← ⟨addr A⟩, output ← ⟨addr B⟩, total ← 0
3int main(void) {4 int factor→ 2 = 2; //@factor=3, 45 int input→ ⟨addr A⟩[3] = {1, 2, 3};6 int output→ ⟨addr B⟩[3] = {0, 0, 0};7 int total→ 0 = 0;output[i] ← 2, total ← 2
pass 1 of 39for (int i0 = 0; i < 3; i++) {10 output[i]→ 2 = input[i]1 * factor2;11 total→ 2 += output[i]2;12}All 3 passes — pass 1 is the card above pass iinput[i]output[i]total1 0 1 0 → 2 0 → 2 2 1 2 0 → 4 2 → 6 3 2 3 0 → 6 6 → 12 printf("total=%d ", total);
14 printf("total=%d\n", total12);15 return 0;16}outputtotal=12
factor ← 3, input ← ⟨addr A⟩, output ← ⟨addr B⟩, total ← 0
3int main(void) {4 int factor→ 3 = 3;5 int input→ ⟨addr A⟩[3] = {1, 2, 3};6 int output→ ⟨addr B⟩[3] = {0, 0, 0};7 int total→ 0 = 0;output[i] ← 3, total ← 3
pass 1 of 39for (int i0 = 0; i < 3; i++) {10 output[i]→ 3 = input[i]1 * factor3;11 total→ 3 += output[i]3;12}All 3 passes — pass 1 is the card above pass iinput[i]output[i]total1 0 1 0 → 3 0 → 3 2 1 2 0 → 6 3 → 9 3 2 3 0 → 9 9 → 18 printf("total=%d ", total);
14 printf("total=%d\n", total18);15 return 0;16}outputtotal=18
factor ← 4, input ← ⟨addr A⟩, output ← ⟨addr B⟩, total ← 0
3int main(void) {4 int factor→ 4 = 4;5 int input→ ⟨addr A⟩[3] = {1, 2, 3};6 int output→ ⟨addr B⟩[3] = {0, 0, 0};7 int total→ 0 = 0;output[i] ← 4, total ← 4
pass 1 of 39for (int i0 = 0; i < 3; i++) {10 output[i]→ 4 = input[i]1 * factor4;11 total→ 4 += output[i]4;12}All 3 passes — pass 1 is the card above pass iinput[i]output[i]total1 0 1 0 → 4 0 → 4 2 1 2 0 → 8 4 → 12 3 2 3 0 → 12 12 → 24 printf("total=%d ", total);
14 printf("total=%d\n", total24);15 return 0;16}outputtotal=24