-
-
Save jaonoctus/d9f19eb6d53c534bd59941b2a72652e8 to your computer and use it in GitHub Desktop.
Funções C
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> | |
/** | |
* [RESUMO] Escopo das variaveis: Global | |
* | |
* As variaveis declaradas "fora" das funcoes, ou seja, em escopo global, | |
* estao acessiveis em qualquer parte do codigo. | |
*/ | |
int n = 1, | |
a = 1, | |
b = 2; | |
/** | |
* [RESUMO] Escopo das variaveis: Local | |
* | |
* As variaveis declaradas "dentro" das funcoes, ou seja, em escopo local, | |
* estao acessiveis e sao persistentes apenas "dentro" da funcao. | |
* | |
* Note que ja declaramos o valor de "n" como 1 em escopo global. | |
* | |
* Vale lembrar que tambem declaramos "b" como 2 no escopo global, | |
* mas o valor que "b" assume nessa funcao seria o que foi passado para ela | |
* (local, ao inves do global). | |
* ex: somaDoisNumerosMaisUm(1, 5) retornaria 7 ao inves de 4. | |
*/ | |
int somaDoisNumerosMaisUm (int a, int b) | |
{ | |
return a + b + n; | |
} | |
/** | |
* [RESUMO] Funções que retornam void (procedimentos) | |
* | |
* Em tradução literal, "void" significa "vazio", "sem nada". Ou seja, | |
* A função do tipo "void" não retorna valores, apenas realiza operações. | |
*/ | |
void trocarValores (int *a, int *b) | |
{ | |
*a = *a + *b; | |
*b = *a - *b; | |
*a = *a - *b; | |
} | |
int main() | |
{ | |
/** | |
* [RESUMO] Passagem de parametros por valor | |
* | |
* É quando passamos valor(es) como argumento(s) de uma funcao. | |
* | |
* Esses valores sao "copiados" para "dentro" daquele escopo local. | |
* Ou seja, ao final deste procedimento, o valor 5 foi passado, | |
* porem o valor de "b" continua como 2 dentro do escopo "main". | |
*/ | |
printf("%d", somaDoisNumerosMaisUm(a, 5)); // exibe "7" | |
printf("%d", b); // exibe "2" | |
/** | |
* [RESUMO] Passagem de parametros por referencia | |
* | |
* É quando passamos referencia(s) de memoria como argumento(s) para uma funcao. | |
* | |
* Essas referências são passadas para "dentro" daquele escopo local, | |
* e as operacoes realizadas refletem no valor que a variavel assume. | |
* Ou seja, ao final deste procedimento, o valor de "a" (1) foi passado, | |
* no entanto, o valor de "b" é substituido pelo valor de "a" e passa a valer 5 | |
* e vice-versa. | |
*/ | |
printf("a = %d; b = %d", a, b); // exibe a = 1; b = 5 | |
trocarValores(&a, &b); | |
printf("a = %d; b = %d", a, b); // exibe a = 2; b = 1 | |
} |
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
/* | |
* Faça uma função para calcular a velocidade média (Vm) dados o espaço e o | |
* tempo como parâmetros. | |
* Vm=Δs/Δt | |
*/ | |
#include <stdio.h> | |
float vm (float s, float t) | |
{ | |
return s / t; | |
} | |
int main () | |
{ | |
float s, t; | |
puts("VELOCIDADE MEDIA"); | |
printf("Espaco (km): "); | |
scanf("%f", &s); | |
printf("Tempo (h): "); | |
scanf("%f", &t); | |
printf("Velocidade media: %.2f km/h", vm(s, t)); | |
} |
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
/* | |
* Faça uma função que recebe dois números inteiros como parâmetro e retorne o | |
* maior entre eles. | |
*/ | |
#include <stdio.h> | |
int maior (int n1, int n2) | |
{ | |
return (n1 > n2) ? n1 : n2; | |
} | |
int main () | |
{ | |
int n1, n2; | |
puts("Informe dois numeros inteiros:"); | |
scanf("%d", &n1); | |
scanf("%d", &n2); | |
printf("O maior numero: %d", maior(n1, n2)); | |
} |
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
/* | |
* Em um triângulo, cada lado é menor do que a soma dos outros dois. | |
* Faça uma função que recebe três números como parâmetro e retorna: | |
* - 0: caso não possa constituir um triângulo. | |
* - 1: caso o triângulo formado seja escaleno (lados diferentes). | |
* - 2: caso o triângulo seja isósceles (dois lados iguais). | |
* - 3: caso o triângulo seja equilátero (três lados iguais). | |
*/ | |
#include <stdio.h> | |
#define L 3 | |
int eMenor (float l1, float l2, float l3) | |
{ | |
return l1 < (l2 + l3); | |
} | |
int eTriangulo(float l1, float l2, float l3) | |
{ | |
int lado1 = eMenor(l1, l2, l3), | |
lado2 = eMenor(l2, l1, l3), | |
lado3 = eMenor(l3, l1, l2); | |
return (lado1 && lado2 && lado3); | |
} | |
int tipoTriangulo(float l1, float l2, float l3) | |
{ | |
if (!eTriangulo(l1, l2, l3)) { return 0; } | |
int escaleno = (l1 != l2 && l2 != l3 && l1 != l3), | |
equilatero = (l1 == l2 && l2 == l3); | |
if (escaleno) { return 1; } | |
if (equilatero) { return 3; } | |
return 2; | |
} | |
int main () | |
{ | |
float l1, l2, l3; | |
puts("Informe os 3 lados de um triangulo:"); | |
scanf("%f%f%f", &l1, &l2, &l3); | |
switch (tipoTriangulo(l1, l2, l3)) { | |
case 0: | |
puts("nao e um triangulo"); | |
break; | |
case 1: | |
puts("escaleno"); | |
break; | |
case 2: | |
puts("isosceles"); | |
break; | |
case 3: | |
puts("equilatero"); | |
break; | |
} | |
} |
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
/* | |
* Faça uma função que retorne o fatorial de um número inteiro passado como | |
* parâmetro. | |
*/ | |
#include <stdio.h> | |
int fatorial (int n) | |
{ | |
return (n > 1) ? (n * fatorial(n - 1)) : 1; | |
} | |
int main () | |
{ | |
int n; | |
printf("Informe um numero inteiro: "); | |
scanf("%d", &n); | |
printf("%d! = %d", n, fatorial(n)); | |
} |
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
/* | |
* Faça uma função para calcular o valor de H a partir de um número inteiro n | |
* passado como parâmetro. | |
* | |
* H = 1/1! + 1/2! + ... + 1/n! | |
*/ | |
#include <stdio.h> | |
int fatorial (int n) | |
{ | |
return (n > 1) ? (n * fatorial(n - 1)) : 1; | |
} | |
float valorH (int n) | |
{ | |
if (n <= 1) { return 1; } | |
float h = 0; | |
for (int i = 0; i < n; i++) { | |
h += 1.0 / fatorial(n - i); | |
} | |
return h; | |
} | |
int main () | |
{ | |
int n; | |
printf("Informe um numero inteiro: "); | |
scanf("%d", &n); | |
printf("H = %.2f", valorH(n)); | |
} |
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
/* | |
* Faça uma função que receba um vetor de 10 números reais como parâmetro e | |
* retorne o menor número armazenado no vetor. | |
*/ | |
#include <stdio.h> | |
#define N 10 | |
float menor (float numeros[N]) | |
{ | |
float menor = numeros[0]; | |
for (int i = 0; i < N; i++) { | |
if (menor > numeros[i]) { menor = numeros[i]; } | |
} | |
return menor; | |
} | |
int main () | |
{ | |
float numeros[N] = {5, 100, -0.5, -0.49, 0, 3, 10.1, -0.51, 10.2, 1}; | |
printf("menor numero: %.2f", menor(numeros)); | |
} |
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
/* | |
* Faça uma função que receba uma string como parâmetro e a converta em | |
* minúscula. Obs.: utilize a função tolower() da biblioteca ctype.h. | |
*/ | |
#include <stdio.h> | |
#include <ctype.h> | |
#define T 100 | |
char* minusculo(char string[T]) | |
{ | |
for (int i = 0; i < T; i++) { string[i] = tolower(string[i]); } | |
return string; | |
} | |
int main () | |
{ | |
char texto[T] = "Aqui é Body Builder BIRL! Vo derrubar tudo essas árvore do parque ibirapuera."; | |
printf("original:\n%s\n\n", texto); | |
printf("minusculo:\n%s\n", minusculo(texto)); | |
} |
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
/* | |
* Faça uma função que receba, como parâmetros, um vetor com as fichas de 100 | |
* alunos e um número inteiro correspondente a matrícula de um aluno e retorne a | |
* posição no vetor onde a ficha que possui a matrícula informada se encontra. | |
* Caso não encontre a matrícula correspondente, a função deve retornar -1. | |
*/ | |
#include <stdio.h> | |
#include <string.h> | |
#define A 100 | |
struct Ficha { | |
int matricula; | |
char nome[30], | |
curso[30], | |
telefone[10]; | |
} alunos[A]; | |
void cadastrarAlunos () | |
{ | |
for (int i = 0; i < A; i++) { | |
alunos[i].matricula = i+1; | |
strcpy(alunos[i].nome, "Aluno A"); | |
strcpy(alunos[i].curso, "Curso B"); | |
strcpy(alunos[i].telefone, "2222222222"); | |
} | |
} | |
int buscarAluno(struct Ficha alunos[], int matricula) | |
{ | |
for (int i = 0; i < A; i++) { | |
if (alunos[i].matricula == matricula) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
int main () | |
{ | |
cadastrarAlunos(); | |
int matricula, | |
posicao; | |
printf("Buscar matricula: "); | |
scanf("%d", &matricula); | |
posicao = buscarAluno(alunos, matricula); | |
switch (posicao) { | |
case -1: | |
printf("Aluno não encontrado"); | |
break; | |
default: | |
printf("Nome: %s\n", alunos[posicao].nome); | |
printf("Curso: %s\n", alunos[posicao].curso); | |
printf("Telefone: %s\n", alunos[posicao].telefone); | |
} | |
} |
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
/* | |
* Faça uma função que receba uma matriz de terceira ordem (3 x 3) como | |
* parâmetro e calcule seu determinante. | |
* | |
* |a b c| | |
* det |d e f| = (aei+bfg+cdh) − (ceg+afh+dbi) | |
* |g h i| | |
* | |
*/ | |
#include <stdio.h> | |
#define L 3 | |
#define C 3 | |
int matriz[L][C] = { | |
// a:00 b:01 c:02 | |
{5, 0, 1}, | |
// d:10 e:11 f:12 | |
{-2, 3, 4}, | |
// g:20 h:21 i:22 | |
{0, 2, -1} | |
}; | |
int det (int matriz[L][C]) | |
{ | |
int a = matriz[0][0], | |
b = matriz[0][1], | |
c = matriz[0][2], | |
d = matriz[1][0], | |
e = matriz[1][1], | |
f = matriz[1][2], | |
g = matriz[2][0], | |
h = matriz[2][1], | |
i = matriz[2][2]; | |
int aei = a * e * i, | |
bfg = b * f * g, | |
cdh = c * d * h, | |
ceg = c * e * g, | |
afh = a * f * h, | |
dbi = d * b * i; | |
return (aei + bfg + cdh) - (ceg + afh + dbi); | |
} | |
int main () | |
{ | |
puts("MATRIZ:"); | |
for (int i = 0; i < L; i++) { | |
for (int j = 0; j < C; j++) { | |
printf("%2d\t", matriz[i][j]); | |
} | |
printf("\n"); | |
} | |
printf("\nDeterminante: %d", det(matriz)); | |
} |
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
/* | |
* Faça uma função que receba um número inteiro como parâmetro por referência e | |
* converta-o para seu valor absoluto. | |
* Observação: | |
* - O valor absoluto de 10 é 10. | |
* - O valor absoluto de -10 é 10. | |
*/ | |
#include <stdio.h> | |
void absoluto(int *n) | |
{ | |
*n = (*n < 0) ? *n * -1 : *n; | |
} | |
int main () | |
{ | |
int num; | |
printf("Digite um numero inteiro: "); | |
scanf("%d", &num); | |
absoluto(&num); | |
printf("Valor absoluto: %d", num); | |
} |
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
/* | |
* Faça uma função que receba os coeficientes (a, b e c) de uma função do | |
* segundo grau ( f(x) = ax² + bx + c ) e, por referência, variáveis para as | |
* raízes reais ( r1 e r2 ) e que retorne o valor de ∆. Considere: | |
* | |
* ∆=b²−4ac | |
* | |
* - Com ∆ < 0, não há raizes reais. | |
* - Com ∆ = 0, há uma raiz real: | |
* r1 = -b / 2a. | |
* - Com ∆ > 0, há duas raízes reiais: | |
* r1 = -b + √∆ / 2a; | |
* r2 = -b - √∆ / 2a. | |
*/ | |
#include <stdio.h> | |
#include <math.h> | |
float a, b, c, // coeficientes | |
r1, r2; // raizes | |
void coeficientes () | |
{ | |
puts("f(x) = ax² + bx + c"); | |
printf("a: "); scanf("%f", &a); | |
printf("b: "); scanf("%f", &b); | |
printf("c: "); scanf("%f", &c); | |
} | |
float delta(float a, float b, float c, float *r1, float *r2) | |
{ | |
float d = pow(b, 2) - 4 * a * c; | |
if (d == 0) { | |
*r1 = -b / (2 * a); | |
} | |
if (d > 0) { | |
*r1 = -b + sqrt(d) / (2 * a); | |
*r2 = -b - sqrt(d) / (2 * a); | |
} | |
return d; | |
} | |
void funcaoSegundoGrau() | |
{ | |
coeficientes(); | |
float d = delta(a, b, c, &r1, &r2); | |
printf("\n∆ = %.2f\n", d); | |
if (d < 0) { puts("Não existem raizes reais."); } // a = 1; b = 2; c = 3 | |
if (d >= 0) { printf("r1 = %.2f\n", r1); } // a = -2; b = 20; c = -50 | |
if (d > 0) { printf("r2 = %.2f\n", r2); } // a = 2; b = 0; c = -18 | |
} | |
int main () | |
{ | |
funcaoSegundoGrau(); | |
} |
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
/* | |
* Faça uma função recursiva para calcular a multiplicação entre dois números | |
* inteiros positivos passados como parâmetro. | |
*/ | |
#include <stdio.h> | |
/** | |
* @var int a multiplicando | |
* @var int b multiplicador | |
*/ | |
int multiplicacaoPositiva (int a, int b) | |
{ | |
return (b == 0 || a == 0) | |
? 0 | |
: (b == 1) | |
? a | |
: a + multiplicacaoPositiva(a, b - 1); | |
} | |
int multiplicacao (int a, int b) | |
{ | |
int aNegativo = (a < 0), | |
bNegativo = (b < 0), | |
resultado; | |
if (aNegativo) { a *= -1; } | |
if (bNegativo) { b *= -1; } | |
resultado = multiplicacaoPositivos(a, b); | |
return (!aNegativo != !bNegativo) ? resultado * -1 : resultado; | |
} | |
int main () | |
{ | |
int n1, n2; | |
puts("Digite dois numeros inteiros:"); | |
scanf("%d%d", &n1, &n2); | |
printf("%d x %d = %d", n1, n2, multiplicacao(n1, n2)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment