From 54c08258c262a6519eaee2378ad3383b8b22b051 Mon Sep 17 00:00:00 2001 From: Abreu Date: Sat, 11 Feb 2023 20:57:59 -0300 Subject: [PATCH] Added some more exercises --- Exercícios/04/fatorial2.c | 22 ++++++++++++++++++++++ Exercícios/04/potenciacao.c | 2 +- Exercícios/09/fibonacci_2.c | 31 +++++++++++++++++++++++++++++++ Exercícios/09/fibonacci_3.c | 27 +++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 Exercícios/04/fatorial2.c create mode 100644 Exercícios/09/fibonacci_2.c create mode 100644 Exercícios/09/fibonacci_3.c diff --git a/Exercícios/04/fatorial2.c b/Exercícios/04/fatorial2.c new file mode 100644 index 0000000..a880ee5 --- /dev/null +++ b/Exercícios/04/fatorial2.c @@ -0,0 +1,22 @@ +#include + +int factorial(int n) { + if (n < 2) + return 1; + return n * factorial(n - 1); +} + +int main() { + int n; + + printf("Este programa calcula o valor do fatorial n!, para qualquer valor " + "de n positivo.\nDigite um valor para n e presione ENTER: "); + + if (!scanf("%d", &n) || n < 0) { + printf("Valor inválido.\n"); + return 1; + } + + printf("%d! = %d\n", n, factorial(n)); + return 0; +} diff --git a/Exercícios/04/potenciacao.c b/Exercícios/04/potenciacao.c index 4b54799..497ffaf 100644 --- a/Exercícios/04/potenciacao.c +++ b/Exercícios/04/potenciacao.c @@ -24,7 +24,7 @@ int main() { else { resultado = -1; } - + } while (seq < k) { diff --git a/Exercícios/09/fibonacci_2.c b/Exercícios/09/fibonacci_2.c new file mode 100644 index 0000000..b4f195a --- /dev/null +++ b/Exercícios/09/fibonacci_2.c @@ -0,0 +1,31 @@ +#include +#include + +int * fibonacci (int n) { + int i, *A = malloc(n * sizeof(int)); + + for (i = 0; i < n && i < 2; i++) + A[i] = 1; + if (n > 2) + while (i < n) + A[i++] = A[i - 1] + A[i - 2]; + return A; +} + +int main () { + int n, i, *A; + + printf("Este programa calcula os valores até o enésimo número na sequência Fibonacci.\nDigite um valor inteiro e positivo para n tal que n < 45: "); + if (!scanf(" %d", &n) || n < 0 || n > 45) { + printf("Valor inválido.\n"); + return 1; + } + A = fibonacci(n); + + printf("Sequência Fibonacci até o %dº elemento:", n); + for (i = 0; i < n; i++) + printf(" %d", A[i]); + printf("\n"); + free(A); + return 0; +} diff --git a/Exercícios/09/fibonacci_3.c b/Exercícios/09/fibonacci_3.c new file mode 100644 index 0000000..bde5e12 --- /dev/null +++ b/Exercícios/09/fibonacci_3.c @@ -0,0 +1,27 @@ +#include + +void printFibonacci (int n) { + int i = 0, A[3] = {1,1,1}; + + for (i = 0; i < n && i < 2; i++) + printf("%d ", A[i]); + while (n-- > 2){ + A[i - 2] = A[i - 1]; + A[i - 1] = A[i]; + A[i] += A[i - 2]; + printf("%d ", A[i]); + } + printf("\n"); +} + +int main () { + int n; + + printf("Este programa calcula os valores até o enésimo número na sequência Fibonacci.\nDigite um valor inteiro e positivo para n tal que n < 45: "); + if (!scanf(" %d", &n) || n < 0 || n > 45) { + printf("Valor inválido.\n"); + return 1; + } + printFibonacci(n); + return 0; +}