Zadanie - rekurencja

Otrzymałeś(aś) rozwiązanie do zamieszczonego zadania? - podziękuj autorowi rozwiązania! Kliknij
MrMatier
Witam na forum
Witam na forum
Posty: 1
Rejestracja: 16 gru 2021, 14:38

Zadanie - rekurencja

Post autor: MrMatier »

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.
ThePPK
Witam na forum
Witam na forum
Posty: 6
Rejestracja: 24 sie 2021, 10:27
Otrzymane podziękowania: 3 razy
Płeć:

Re: Zadanie - rekurencja

Post autor: ThePPK »

Rozwiązanie przedstawione poniżej posiada statyczny rozmiar tablicy (n), po modyfikacji kodu można go podawać jako argument. Tablica jest również generowana dynamicznie w funkcji main.

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;
}
ODPOWIEDZ