Skip to content

Instantly share code, notes, and snippets.

@olegon
Last active January 17, 2017 12:24
Show Gist options
  • Save olegon/abd83399fa2bed576a2de27f7e06a03f to your computer and use it in GitHub Desktop.
Save olegon/abd83399fa2bed576a2de27f7e06a03f to your computer and use it in GitHub Desktop.
#include <stdio.h>
int sum_positives (int *v, int n);
int main (void) {
int v[5] = { -1, 7, -3, 11, 4 };
int result = sum_positives(v, 5);
printf("Sum: %d\n", result);
return 0;
}
/*
Dado um vetor de inteiros v e um inteiro n >= 0
devolve a soma dos inteiros positivos no intervalo v[0..n-1]
*/
int sum_positives (int *v, int n) {
if (n == 0) return 0;
else {
int total = sum_positives(v, n - 1);
/* Invariante: total possui a soma dos inteiros positivos do vetor v[0..n-2] */
if (v[n - 1] > 0) return total + v[n - 1];
else return total;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment