Zadanie - rekurencja
: 16 gru 2021, 14:58
Oblicz rekurencyjnie sumę liczb należących do n-elementowego ciągu wygenerowanego losowo, spełniających warunek, że są większe niż element poprzedni w kolejności. Wszystko w języku C.
Forum serwisu www.zadania.info
https://forum.zadania.info:443/
Kod: Zaznacz cały
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
const uint16_t n = 100;
const uint32_t maxInteger = 10000;
uint64_t sumGreaterThanLatest(const uint32_t* table,
uint64_t* sum,
const uint16_t element) {
if (element > 0 && element < n) {
if (table[element-1] < table[element]) {
*sum += table[element];
}
}
if (element+1 < n) {
return sumGreaterThanLatest(table, sum, element+1);
} else {
return *sum;
}
}
int main() {
uint32_t table[n];
srand(time(NULL));
for (uint16_t i = 0; i < n; i++) {
table[i] = rand()/(RAND_MAX/maxInteger);
}
uint64_t sum = 0;
sumGreaterThanLatest(table, &sum, 0);
printf("Suma liczb większych od poprzednika w n=%u elementowym zbiorze, wynosi: %u\n", n, sum);
return 0;
}