Ficha 02 · C avançado + C++
Exercício 1 · malloc + free
Cria função int *criar_array(int n) que aloca dinamicamente um array de n inteiros e preenche-o com 0, 1, 2, ..., n-1. No main, cria array de 10, imprime, e liberta.
Resposta:
#include <stdio.h>
#include <stdlib.h>
int *criar_array(int n) {
int *arr = (int *) malloc(n * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "Erro: sem memória\n");
return NULL;
}
for (int i = 0; i < n; i++) {
arr[i] = i;
}
return arr;
}
int main() {
int n = 10;
int *arr = criar_array(n);
if (arr == NULL) return 1;
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
arr = NULL;
return 0;
}
Exercício 2 · Ler ficheiro
Cria um ficheiro numeros.txt com 5 inteiros (um por linha). Lê-o e imprime a soma.
Resposta:
#include <stdio.h>
int main() {
FILE *f = fopen("numeros.txt", "r");
if (f == NULL) {
perror("Erro");
return 1;
}
int soma = 0;
int n;
while (fscanf(f, "%d", &n) == 1) {
soma += n;
}
fclose(f);
printf("Soma: %d\n", soma);
return 0;
}
Para criar numeros.txt:
printf "10\n20\n30\n40\n50\n" > numeros.txt
Exercício 3 · Escrever ficheiro CSV
Cria array de structs Produto {nome, preco} com 3 produtos, e grava-os em produtos.csv no formato CSV.
Resposta:
#include <stdio.h>
typedef struct {
char nome[50];
double preco;
} Produto;
int main() {
Produto produtos[3] = {
{"Caneta", 1.50},
{"Caderno", 5.00},
{"Mochila", 35.00}
};
FILE *f = fopen("produtos.csv", "w");
if (f == NULL) {
perror("Erro");
return 1;
}
fprintf(f, "nome,preco\n");
for (int i = 0; i < 3; i++) {
fprintf(f, "%s,%.2f\n", produtos[i].nome, produtos[i].preco);
}
fclose(f);
printf("Gravado!\n");
return 0;
}
Verifica com cat produtos.csv.
Exercício 4 · Linked list (struct + pointers)
Implementa uma lista ligada simples:
- struct Node { int valor; struct Node *next; }.
- Função inserir_inicio(Node **head, int valor).
- Função imprimir(Node *head).
- Função libertar(Node *head).
- Insere 5 valores e imprime.
Resposta:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int valor;
struct Node *next;
} Node;
void inserir_inicio(Node **head, int valor) {
Node *novo = (Node *) malloc(sizeof(Node));
novo->valor = valor;
novo->next = *head;
*head = novo;
}
void imprimir(Node *head) {
Node *cur = head;
while (cur != NULL) {
printf("%d -> ", cur->valor);
cur = cur->next;
}
printf("NULL\n");
}
void libertar(Node *head) {
while (head != NULL) {
Node *tmp = head;
head = head->next;
free(tmp);
}
}
int main() {
Node *head = NULL;
for (int i = 1; i <= 5; i++) {
inserir_inicio(&head, i * 10);
}
imprimir(head);
// 50 -> 40 -> 30 -> 20 -> 10 -> NULL
libertar(head);
return 0;
}
Node ** para conseguir modificar o head da função main.
Exercício 5 · Calculadora CLI
Cria uma calculadora com menu: - 1. Somar - 2. Subtrair - 3. Multiplicar - 4. Dividir - 0. Sair
Loop até user escolher 0. Trata divisão por zero.
Resposta:
#include <stdio.h>
int main() {
int opcao;
double a, b;
while (1) {
printf("\n=== CALCULADORA ===\n");
printf("1. Somar\n");
printf("2. Subtrair\n");
printf("3. Multiplicar\n");
printf("4. Dividir\n");
printf("0. Sair\n");
printf("Escolha: ");
if (scanf("%d", &opcao) != 1) break;
if (opcao == 0) break;
if (opcao < 1 || opcao > 4) {
printf("Opção inválida.\n");
continue;
}
printf("Primeiro número: ");
scanf("%lf", &a);
printf("Segundo número: ");
scanf("%lf", &b);
switch (opcao) {
case 1: printf("= %.2f\n", a + b); break;
case 2: printf("= %.2f\n", a - b); break;
case 3: printf("= %.2f\n", a * b); break;
case 4:
if (b == 0) {
printf("Erro: divisão por zero!\n");
} else {
printf("= %.2f\n", a / b);
}
break;
}
}
printf("Adeus!\n");
return 0;
}
Exercício 6 · C++ Hello
Cria hello.cpp em C++. Pede nome ao utilizador usando cin e string, e responde com cout.
Resposta:
#include <iostream>
#include <string>
using namespace std;
int main() {
string nome;
int idade;
cout << "Nome: ";
cin >> nome;
cout << "Idade: ";
cin >> idade;
cout << "Olá, " << nome << "! Daqui a 10 anos terás "
<< (idade + 10) << " anos." << endl;
return 0;
}
g++ hello.cpp -o hello
./hello
Exercício 7 · Classe C++
Cria classe Carro com atributos privados marca, modelo, velocidade (começa em 0). Construtor recebe marca + modelo. Métodos:
- acelerar(int): aumenta velocidade.
- travar(int): diminui (mínimo 0).
- info(): imprime estado actual.
Demonstra no main.
Resposta:
#include <iostream>
#include <string>
using namespace std;
class Carro {
private:
string marca;
string modelo;
int velocidade;
public:
Carro(string m, string mo)
: marca(m), modelo(mo), velocidade(0) {}
void acelerar(int delta) {
velocidade += delta;
}
void travar(int delta) {
velocidade -= delta;
if (velocidade < 0) velocidade = 0;
}
void info() const {
cout << marca << " " << modelo
<< " — " << velocidade << " km/h" << endl;
}
};
int main() {
Carro c("Toyota", "Corolla");
c.info(); // 0 km/h
c.acelerar(50);
c.acelerar(30);
c.info(); // 80 km/h
c.travar(20);
c.info(); // 60 km/h
c.travar(100);
c.info(); // 0 km/h (não negativo)
return 0;
}
Exercício 8 · vector + algoritmos C++
Em C++, cria vector<int> com 10 números aleatórios. Usa STL para:
- Ordenar.
- Calcular soma.
- Encontrar máximo.
- Imprimir.
Resposta:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <random>
using namespace std;
int main() {
vector<int> nums;
// Gerar 10 aleatórios entre 1 e 100
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < 10; i++) {
nums.push_back(dist(gen));
}
cout << "Originais: ";
for (int n : nums) cout << n << " ";
cout << endl;
// Ordenar
sort(nums.begin(), nums.end());
cout << "Ordenados: ";
for (int n : nums) cout << n << " ";
cout << endl;
// Soma
int soma = accumulate(nums.begin(), nums.end(), 0);
cout << "Soma: " << soma << endl;
// Máximo
int max = *max_element(nums.begin(), nums.end());
cout << "Máximo: " << max << endl;
// Bonus: contar pares
int pares = count_if(nums.begin(), nums.end(),
[](int n) { return n % 2 == 0; });
cout << "Pares: " << pares << endl;
return 0;
}
Compilar com -std=c++17:
g++ -std=c++17 -Wall pratica.cpp -o pratica