Strona 1 z 1

Zadanie - rekurencja

: 16 gru 2021, 14:58
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.

Re: Zadanie - rekurencja

: 16 lut 2022, 20:55
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;
}