Last active
September 13, 2018 23:13
-
-
Save ioxua/f6a4cd92c4f1fda6377712f1fa5fc225 to your computer and use it in GitHub Desktop.
Exercícios ED
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <locale.h> | |
#include <limits.h> | |
// Utilidades | |
#define PI 3.14159 | |
void lerVetorFloat(float vetor[], int qtd) { | |
printf("Digite %d valores separados por espaços:", qtd); | |
int i; | |
for (i = 0; i < qtd; i++) { | |
scanf("%f", &vetor[i]); | |
} | |
} | |
// Execução | |
void executar(char* titulo, void (*func)()) { | |
printf("%s\n", titulo); | |
(*func)(); | |
printf("\n\n"); | |
} | |
// Precisamos enviar o tamanho do vetor pois o tamanho do ponteiro | |
// para um vetor é diferente dentro e fora de uma função o.O | |
void executarLista(char* titulo, void (*exercicios[]), int qtdExerc) { | |
printf("%s\n", titulo); | |
int i; | |
for (i = 0; i < qtdExerc; i++) { | |
// Eu não sei o tamanho adequado para esse vetor, mas eu o inicializei | |
// com tamanho 12 antes, e ele fazia algumas coisas... | |
// especiais... acontecerem o.O | |
char titulo[20]; | |
sprintf(titulo, "Exercício %d", (i + 1)); | |
executar(titulo, exercicios[i]); | |
} | |
} | |
// Exercícios | |
/** | |
* Leia dois valores e informe a média (use float) | |
*/ | |
void ex1() { | |
float a, b; | |
printf("Informe dois valores separados por espaço:"); | |
scanf("%f %f", &a, &b); | |
float m = (a + b) / 2; | |
printf("A média entre %g e %g é igual a %g.", a, b, m); | |
} | |
/** | |
* Leia uma temperatura em graus centígrados e converta para graus Fahrenheit | |
* usando a fórmula: F = (9 * C + 160) / 5 | |
*/ | |
void ex2() { | |
float c; | |
printf("Informe uma quantidade de graus centígrados:"); | |
scanf("%f", &c); | |
float f = (9 * c + 160) / 5; | |
printf("%g°C convertidos para Fahrenheit são %g°F", c, f); | |
} | |
/** | |
* Calcule o volume de uma lata de óleo usando a fórmula: V = PI * R² * H | |
*/ | |
void ex3() { | |
float r, h; | |
printf("Informe a altura e o raio de uma lata, separados por espaços:"); | |
scanf("%f %f", &h, &r); | |
float v = PI * r * r * h; | |
printf("O volume dessa dada lata é de %g unidades", v); | |
} | |
/** | |
* Dados quatro valores, apresentar a soma e multiplicação deles baseado na | |
* propriedade distributiva: AB, AC, AD, BC, BD, CD | |
*/ | |
void ex4() { | |
float valores[4]; | |
lerVetorFloat(valores, 4); | |
int i; | |
for (i = 0; i < 4; i++) { | |
int j; | |
for (j = i + 1; j < 4; j++) { | |
float r = valores[i] + valores[j]; | |
printf("%g + %g = %g\n", valores[i], valores[j], r); | |
r = valores[i] * valores[j]; | |
printf("%g * %g = %g\n\n", valores[i], valores[j], r); | |
} | |
} | |
} | |
/** | |
* Leia 5 valores e informe o maior | |
*/ | |
void ex5() { | |
float m = INT_MIN; | |
printf("Digite 5 números separados por espaços:"); | |
int i; | |
for (i = 0; i < 5; i++) { | |
float l; | |
scanf("%f", &l); | |
if (l > m) | |
m = l; | |
} | |
printf("O maior número digitado foi %g", m); | |
} | |
/** | |
* Mostrar todos os números ímpares entre 0 e 20 | |
*/ | |
void ex6() { | |
printf("Os números ímpares entre 0 e 20 são: "); | |
int n; | |
for (n = 1; n < 20; n += 2) | |
printf("%d ", n); | |
} | |
/** | |
* Mostrar a soma dos 100 primeiros números inteiros não nulos | |
*/ | |
void ex7() { | |
int i, s = 0; | |
for (i = 1; i <= 100; i++) | |
s += i; | |
printf("A soma dos 100 primeiros números inteiros não nulos é %d", s); | |
} | |
/** | |
* Mostrar fibonacci até o 15º termo | |
*/ | |
void ex8() { | |
printf("A série de Fibonacci até o 10º termo é: "); | |
int i, p, u; | |
for (i = 0, p = 1, u = 0; i < 15; i++) { | |
int atual = u + p; | |
p = u; | |
u = atual; | |
printf("%d ", atual); | |
} | |
} | |
/** | |
* Leia 15 valores e mostre a diferença entre a média e o maior | |
*/ | |
void ex9() { | |
float valores[15]; | |
lerVetorFloat(valores, 15); | |
float media = 0, maior = INT_MIN; | |
int i; | |
for (i = 0; i < 15; i++) { | |
media += valores[i]; | |
if (valores[i] > maior) | |
maior = valores[i]; | |
} | |
media = media / 15; | |
float dif = maior - media; | |
printf("A diferença entre o maior número digitado (%g) e a média dos números digitados (%g) foi %g", maior, media, dif); | |
} | |
int main(void) { | |
setlocale(LC_ALL, "portuguese_brazil"); | |
void (*lista1[]) = { | |
ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8, ex9 | |
}; | |
executarLista("Lista 1", lista1, 9); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <locale.h> | |
// Execução | |
void executar(char* titulo, void (*func)()) { | |
printf("%s\n", titulo); | |
(*func)(); | |
printf("\n\n"); | |
} | |
// Precisamos enviar o tamanho do vetor pois o tamanho do ponteiro | |
// para um vetor é diferente dentro e fora de uma função o.O | |
void executarLista(char* titulo, void (*exercicios[]), int qtdExerc) { | |
printf("%s\n", titulo); | |
int i; | |
for (i = 0; i < qtdExerc; i++) { | |
// Eu não sei o tamanho adequado para esse vetor, mas eu o inicializei | |
// com tamanho 12 antes, e ele fazia algumas coisas... | |
// especiais... acontecerem o.O | |
char titulo[20]; | |
sprintf(titulo, "Exercício %d", (i + 1)); | |
executar(titulo, exercicios[i]); | |
} | |
} | |
// Exercícios | |
/** | |
* Dados dois números naturais, calcular o MDC | |
*/ | |
void ex1() { | |
int a, b; | |
printf("Informe dois valores separados por espaço:"); | |
scanf("%d %d", &a, &b); | |
int maior = a, menor = b; | |
if (b > a) maior = b; | |
if (a < b) menor = a; | |
int resto = maior % menor; | |
while (resto != 0) { | |
maior = menor; | |
menor = resto; | |
resto = maior % menor; | |
} | |
printf("O MDC entre %d e %d é %d", a, b, menor); | |
} | |
/** | |
* Dado um número real X e um número natural K, calcular X ^ K através de | |
* produtos sucessivos | |
*/ | |
void ex2() { | |
float x; | |
int k; | |
printf("Digite um número real positivo (X) e um número natural (K) separados por espaço:"); | |
scanf("%f %d", &x, &k); | |
printf("%g^%d é igual a ", x, k); | |
if (x < 2) | |
k = 0; | |
while (k-- > 0) | |
x *= x; | |
printf("%.0f", x); | |
} | |
/** | |
* Calcular a quantidade de combustível gasto em uma viagem dada a eficiência | |
* X em km/l, o tempo gasto na viagem e a velocidade média. | |
*/ | |
void ex3() { | |
float t, vm, e; | |
printf("Forneça o tempo gasto na viagem (em horas), a velocidade média durante esta (em km/h) e a eficiência do carro (em km/l) separados por espaços:"); | |
scanf("%f %f %f", &t, &vm, &e); | |
float d = t * vm; | |
float c = d / e; | |
printf("Combustível gasto: %gl\nDistância percorrida: %gkm\n", c, d); | |
printf("Tempo gasto: %gh\nVelocidade média: %gkm/h", t, vm); | |
} | |
int main(void) { | |
setlocale(LC_ALL, "portuguese_brazil"); | |
void (*lista2[]) = { | |
ex1, ex2, ex3 | |
}; | |
executarLista("Lista 2", lista2, 3); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <locale.h> | |
#define PI 3.14159 | |
// Execução | |
void executar(char* titulo, void (*func)()) { | |
printf("%s\n", titulo); | |
(*func)(); | |
printf("\n\n"); | |
} | |
// Precisamos enviar o tamanho do vetor pois o tamanho do ponteiro | |
// para um vetor é diferente dentro e fora de uma função o.O | |
void executarLista(char* titulo, void (*exercicios[]), int qtdExerc) { | |
printf("%s\n", titulo); | |
int i; | |
for (i = 0; i < qtdExerc; i++) { | |
// Eu não sei o tamanho adequado para esse vetor, mas eu o inicializei | |
// com tamanho 12 antes, e ele fazia algumas coisas... | |
// especiais... acontecerem o.O | |
char titulo[20]; | |
sprintf(titulo, "Exercício %d", (i + 1)); | |
executar(titulo, exercicios[i]); | |
} | |
} | |
// Utilidades | |
float media(float a, float b, float c, float d) { | |
return (a + b + c + d) / 4; | |
} | |
float vezes(float a, float b) { | |
return a * b; | |
} | |
float grausParaRadianos(float gra) { | |
return gra * PI / 180; | |
} | |
int imprimirMaior(float a, float b) { | |
float min = a; | |
if (b > a) | |
min = b; | |
printf("O maior número entre %g e %g é %g", a, b, min); | |
} | |
void nomeDoMes(int num) { | |
char* resposta; | |
char* primeiroTrimestre[] = { | |
"Janeiro", "Fevereiro", "Março" | |
}; | |
if (num > -1 && num < 4) { | |
resposta = primeiroTrimestre[num - 1]; | |
} else { | |
resposta = "Inválido!"; | |
} | |
printf("O mês %d é %s", num, resposta); | |
} | |
long int fatorial(int num, int sum) { | |
if (num < 2) | |
return sum; | |
return fatorial(num - 1, sum * num); | |
} | |
short isPrimo(int num, int div, int qtd) { | |
if (div == 1) { // Chegou no 1? Terminamos de contar os divisores | |
if (qtd >= 1) { // Tem mais de dois divisores? Não é primo :( | |
return 0; | |
} | |
return 1; // Yaaay é primo :D | |
} | |
if (num % div == 0) { | |
// Se é divisível, incrementar os divisores e prosseguir | |
return isPrimo(num, div - 1, qtd + 1); | |
} | |
// Não é divisível? Só prossiga | |
return isPrimo(num, div - 1, qtd); | |
} | |
// Exercícios | |
/** | |
* Leia um número inteiro e mostre seu dobro (através de função) | |
*/ | |
void ex1() { | |
int num; | |
printf("Digite um número inteiro: "); | |
scanf("%d", &num); | |
printf("O dobro de %d é %g", num, vezes(num, 2)); | |
} | |
/** | |
* Receba 4 notas e mostre sua média aritmética (através de função) | |
*/ | |
void ex2() { | |
float a, b, c, d; | |
printf("Digite 4 notas separadas por espaços: "); | |
scanf("%f %f %f %f", &a, &b, &c, &d); | |
printf("A média dos valores é: %g", media(a, b, c, d)); | |
} | |
/** | |
* Receba 2 valores e apresente o produto (através de função) | |
*/ | |
void ex3() { | |
float a, b; | |
printf("Digite dois valores separados por espaços: "); | |
scanf("%f %f", &a, &b); | |
printf("O produto de %g e %g é %g", a, b, vezes(a, b)); | |
} | |
/** | |
* Receba um valor em graus e converta em radianos (usando função) | |
* usando a fórmula RAD = DEG * PI / 180 | |
*/ | |
void ex4() { | |
float deg, rad; | |
printf("Digite um valor em graus: "); | |
scanf("%f", °); | |
printf("%g° em radianos é %grad", deg, grausParaRadianos(deg)); | |
} | |
/** | |
* Receba dois valores e exiba o maior (usando uma função void) | |
*/ | |
void ex5() { | |
float a, b; | |
printf("Digite dois valores separados por espaço: "); | |
scanf("%f %f", &a, &b); | |
imprimirMaior(a, b); | |
} | |
/** | |
* Receba um número correspondente a um mês do 1º trimestre e exiba o nome. | |
* Caso não exista, exiba 'Inválido' (usando função void) | |
*/ | |
void ex6() { | |
int num; | |
printf("Digite um número correspondente a um mês (1 = Janeiro, 12 = Dezembro): "); | |
scanf("%d", &num); | |
nomeDoMes(num); | |
} | |
/** | |
* Crie uma função que retorne o fatorial de um número | |
*/ | |
void ex7() { | |
int num; | |
printf("Informe um número: "); | |
scanf("%d", &num); | |
printf("O fatorial de %d é %ld", num, fatorial(num, 1)); | |
} | |
/** | |
* Crie uma função que verifique se um número é primo ou não | |
*/ | |
void ex8() { | |
int num; | |
printf("Informe um número: "); | |
scanf("%d", &num); | |
short primo = isPrimo(num, num - 1, 0); | |
if (primo == 1) { | |
printf("O número %d é primo!", num); | |
} else { | |
printf("O número %d não é primo!", num); | |
} | |
} | |
int main(void) { | |
setlocale(LC_ALL, "portuguese_brazil"); | |
void (*lista3[]) = { | |
ex1, ex2, ex3, ex4, ex5, ex6, ex7, ex8 | |
}; | |
executarLista("Lista 3", lista3, 8); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include "PILHA.h" | |
#define MAX 50 | |
typedef struct Pilha Pilha; | |
void exibirPilha(Pilha *p, char* formato) { | |
while (1 != pilhavazia(p)) { | |
printf(formato, Pop(p)); | |
} | |
} | |
void converterDecimalBaseN(int num, int base) { | |
int temp; | |
Pilha p; | |
IniPilha(&p); | |
temp = num; | |
while(temp > 0) { | |
Push(&p, temp % base); | |
temp = temp / base; | |
} | |
exibirPilha(&p, "%d"); | |
} | |
/** Reverta uma sequencia de digitos até q digitem 999 */ | |
void ex2() { | |
int temp; | |
Pilha p; | |
IniPilha(&p); | |
printf("Digite um um número:"); | |
scanf("%d", &temp); | |
Push(&p, temp); | |
for(int i = 1; i < MAX; i++) { | |
printf("Digite mais um número:"); | |
scanf("%d", &temp); | |
if (temp == 999) break; | |
Push(&p, temp); | |
} | |
exibirPilha(&p, "%d "); | |
} | |
/** Leia uma string e a inverta */ | |
void ex5() { | |
Pilha p; | |
IniPilha(&p); | |
char palavra[1024]; | |
printf("Digite uma string: "); | |
scanf("%[^\n]", palavra); | |
for(char *letra = palavra; *letra != '\0'; letra++) { | |
Push(&p, *letra); | |
} | |
while (1 != pilhavazia(&p)) { | |
printf("%c", Pop(&p)); | |
} | |
} | |
/** Converta de decimal pra hexa */ | |
void ex4() { | |
int num; | |
printf("Digite um número: "); | |
scanf("%d", &num); | |
converterDecimalBaseN(num, 16); | |
} | |
/** Converta de decimal pra octal */ | |
void ex3() { | |
int num; | |
printf("Digite um número: "); | |
scanf("%d", &num); | |
converterDecimalBaseN(num, 8); | |
} | |
int main(void) { | |
ex2(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Ex1. (papel) | |
Supondo que a pilha P esteja inicialmente vazia, | |
mostre como o estado se modifica à medida em que as operações seguintes são executadas: | |
empilha(1, P) | |
empilha(2, P) | |
empilha(3, P) | |
empilha(topo(P), P) | |
empilha(desempilha(P), P) | |
desempilha(P) | |
empilha(4, P) | |
desempilha(P) | |
Ex2. (papel) Considerando a ilustração a seguir, mostre a sequência de operações (empilha e desempilha) | |
que deve ser efetuada com as pilhas P, Q e R para que o estado inicial possa ser transferido | |
para o estado final: | |
|D|| || | | || ||B| | |
|C|| || | | || ||D| | |
|B|| || | => | || ||A| (tá fora de ordem mesmo '-') | |
|A|| || | | || ||C| | |
(P)(Q)(R) (P)(Q)(R) | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Aquele exercício que eu fiz com a Fernanda, que é pra criar uma interface para uma pilha. | |
// A partir do console, deve-se poder adicionar, remover, listar e olhar o topo da pilha |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Do prof Fretz | |
#include<stdlib.h> | |
#include<stdio.h> | |
#include<string.h> | |
#define MAX 50 | |
struct Pilha | |
{ | |
int item[MAX]; | |
int topo; | |
}; | |
void IniPilha(struct Pilha *ps); | |
int pilhavazia(struct Pilha *ps); | |
int pilhacheia(struct Pilha *ps); | |
int Push(struct Pilha *ps, int x); | |
int Pop(struct Pilha *ps); | |
int Top(struct Pilha *ps); | |
void IniPilha(struct Pilha *ps) { | |
ps->topo= -1; | |
} | |
int pilhavazia(struct Pilha *ps) { | |
if (ps->topo == -1) | |
return(1); | |
else | |
return(0); | |
} | |
int pilhacheia(struct Pilha *ps) { | |
if (ps->topo == MAX - 1) | |
return(1); | |
else | |
return(0); | |
} | |
int Push(struct Pilha *ps, int x) { | |
if (pilhacheia(ps)==1) { | |
printf("overflow!!\n"); | |
return(-1); | |
} | |
else | |
return(ps->item[++(ps->topo)]=x); | |
} | |
int Pop(struct Pilha *ps) | |
{ | |
if (pilhavazia(ps)==1) { | |
printf("underflow!!\n"); | |
return(-1); | |
} | |
else | |
return(ps->item[ps->topo--]); | |
} | |
int Top(struct Pilha *ps) { | |
if (pilhavazia(ps)==1) { | |
printf("Underflow!!!\n"); | |
return(-1); | |
} | |
else | |
return(ps->item[ps->topo]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment