C Programming Exercises
C Programming Exercises
Programming
Exercises
1
Avisos de direitos autorais
"Todos os direitos reservados" é uma frase que se originou na lei de
direitos autorais como parte dos avisos de direitos autorais. Isso indica
que o detentor do direito autoral reserva, ou detém para seu próprio
uso, todos os direitos fornecidos pela lei de direitos autorais, como
distribuição, apresentação e criação de obras derivadas; ou seja, eles
não renunciaram a nenhum desses direitos. A lei de direitos autorais na
maioria dos países não exige mais esses avisos, mas a frase persiste. O
entendimento original da frase como relacionado especificamente ao
direito autoral pode ter sido suplantado pelo uso comum da frase para
se referir a qualquer direito legal, embora provavelmente seja entendido
como referindo-se pelo menos ao direito autoral.
https://pt.wikipedia.org/wiki/Todos_os_direitos_reservados
Copyright
Marcas
2
Ebook feito por APOSTILAS em MASSA, suas subsidiárias, afiliadas ou
licenciantes. É estritamente vedado o uso desautorizado de quaisquer
destas marcas, sob qualquer meio e forma e a qualquer título, estando
sujeito às responsabilidades e sanções legais.
----------------------
----------------------
3
Art. 7 - A lei considera que as obras protegidas, dentre outras, são:
textos, obras fotográficas, ilustrações, desenhos, programa de
computador, bases de dados e outras obras, que, por sua seleção,
organização ou disposição de seu conteúdo, constituam uma criação
intelectual.
----------------------
Sobre o Copyright
2024
#HistoriaEmC #DadosEmC #VariaveisEmC #InteirosEmC
#PontoFlutuante #FloatEmC #VetorEmC #MatrizEmC
4
#PonteirosEmC #StructsEmC #UnionEmC #ArquivosEmC
#BlockhainEmC #BitcoinEmC #CriptomoedasEmC
#CriptosEmC #ArvoresEmC #BuscaBinariaEmC
#BancoDeDadosEmC #GraficosEmC ClienteServidorEmC
#TecnologiaEmC #ProgramandoEmC #ProgramarEmC
#AprenderEmC #AprendaEmC #AprendaFacilEmC
#AprendaRapidoEmC
https://www.youtube.com/hashtag/AprendendoEmC
https://www.youtube.com/hashtag/AprendizagemEmC
https://www.youtube.com/hashtag/DadosEmC
https://www.youtube.com/hashtag/VariaveisEmC
https://www.youtube.com/hashtag/InteirosEmC
https://www.youtube.com/hashtag/PontoFlutuante
https://www.youtube.com/hashtag/FloatEmC
https://www.youtube.com/hashtag/VetorEmC
https://www.youtube.com/hashtag/MatrizEmC
https://www.youtube.com/hashtag/PonteirosEmC
https://www.youtube.com/hashtag/StructsEmC
https://www.youtube.com/hashtag/UnionEmC
https://www.youtube.com/hashtag/ArquivosEmC
5
https://www.youtube.com/hashtag/BlockhainEmC
https://www.youtube.com/hashtag/BitcoinEmC
https://www.youtube.com/hashtag/CriptomoedasEmC
https://www.youtube.com/hashtag/CriptosEmC
https://www.youtube.com/hashtag/ArvoresEmC
https://www.youtube.com/hashtag/BuscaBinariaEmC
https://www.youtube.com/hashtag/BancoDeDadosEmC
https://www.youtube.com/hashtag/GraficosEmC
https://www.youtube.com/hashtag/ClienteServidorEmC
https://www.youtube.com/hashtag/TecnologiaEmC
https://www.youtube.com/hashtag/ProgramandoEmC
https://www.youtube.com/hashtag/ProgramarEmC
https://www.youtube.com/hashtag/AprenderEmC
https://www.youtube.com/hashtag/AprendaEmC
https://www.youtube.com/hashtag/AprendaFacilEmC
https://www.youtube.com/hashtag/AprendaRapidoEmC
6
skills. Each exercise comes with a brief description
and sample code to get you started.
1. Hello World
Exercise: Write a simple program that prints
"Hello, World!" to the console.
código em C
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
2. Sum of Two Numbers
Exercise: Write a program that takes two integers
as input from the user and prints their sum.
7
código em C
#include <stdio.h>
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Sum: %d\n", a + b);
return 0;
}
3. Factorial Calculation
Exercise: Write a program to calculate the factorial
of a number using a loop.
código em C
#include <stdio.h>
int main() {
8
int num, factorial = 1;
printf("Enter a number: ");
scanf("%d", &num);
código em C
#include <stdio.h>
9
int main() {
int n, first = 0, second = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
10
second = next;
printf("%d ", next);
}
printf("\n");
return 0;
}
5. Prime Number Check
Exercise: Write a program to check if a number is
prime.
código em C
#include <stdio.h>
#include <stdbool.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (is_prime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
6. Reverse a String
Exercise: Write a program to reverse a given
12
string.
código em C
#include <stdio.h>
#include <string.h>
int main() {
char str[100], temp;
int length;
código em C
14
#include <stdio.h>
#define MAX 10
int main() {
15
int a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];
int row_a, col_a, row_b, col_b;
if (col_a != row_b) {
16
printf("Matrix multiplication not possible.\n");
return 1;
}
return 0;
}
8. Bubble Sort
Exercise: Implement the Bubble Sort algorithm to
sort an array of integers.
código em C
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
19
}
printf("\n");
return 0;
}
9. File Operations
Exercise: Write a program to read from and write
to a file.
código em C
#include <stdio.h>
int main() {
FILE *file;
char text[100];
// Writing to a file
file = fopen("example.txt", "w");
20
if (file == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
printf("Enter text to write to file: ");
fgets(text, sizeof(text), stdin);
fprintf(file, "%s", text);
fclose(file);
21
printf("%s", text);
}
fclose(file);
return 0;
}
10. Dynamic Memory Allocation
Exercise: Write a program to demonstrate
dynamic memory allocation using malloc and free.
código em C
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, n;
// Allocate memory
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Input elements
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Print elements
printf("Array elements are:\n");
23
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Feel free to experiment with these exercises and
modify them to suit your learning goals.
C programming 10 exercises
Certainly! Here are 10 C programming exercises
designed to cover a range of topics from basic
syntax to more complex concepts. Each exercise
includes a brief description and a starting point to
help you get started.
24
1. Print an Array
Exercise: Write a program that initializes an array
of integers and prints its elements.
código em C
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
25
return 0;
}
2. Count Vowels in a String
Exercise: Write a program that counts the number
of vowels in a given string.
código em C
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int count = 0;
código em C
#include <stdio.h>
int main() {
27
int arr[] = {15, 42, 7, 19, 89, 34};
int size = sizeof(arr) / sizeof(arr[0]);
int max = arr[0];
código em C
28
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char str[100];
int len, start, end, is_palindrome = 1;
29
start = 0;
end = len;
if (is_palindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
30
return 0;
}
5. Calculate the Average of an Array
Exercise: Write a program to calculate the average
of elements in an array.
código em C
#include <stdio.h>
int main() {
int arr[] = {12, 25, 37, 40, 58};
int size = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
código em C
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int temp;
32
printf("Original array:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Reversed array:\n");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
33
printf("\n");
return 0;
}
7. Generate Multiplication Table
Exercise: Write a program to generate a
multiplication table for a given number.
código em C
#include <stdio.h>
int main() {
int num;
return 0;
}
8. Bubble Sort
Exercise: Implement the Bubble Sort algorithm to
sort an array of integers.
código em C
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
36
}
printf("\n");
return 0;
}
9. Swap Two Numbers
Exercise: Write a program to swap the values of
two variables using a temporary variable.
código em C
#include <stdio.h>
int main() {
int a, b, temp;
37
// Swap the values
temp = a;
a = b;
b = temp;
código em C
#include <stdio.h>
int main() {
int n, sum = 0;
38
printf("Enter a positive integer: ");
scanf("%d", &n);
39
includes a brief description to help you get started.
1. Sum of Digits
Exercise: Write a program to calculate the sum of
the digits of an integer.
código em C
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter an integer: ");
scanf("%d", &num);
while (num != 0) {
sum += num % 10;
num /= 10;
}
40
printf("Sum of digits: %d\n", sum);
return 0;
}
2. Count Characters in a String
Exercise: Write a program to count the number of
characters in a string, excluding spaces.
código em C
#include <stdio.h>
int main() {
char str[100];
int count = 0;
41
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] != ' ' && str[i] != '\n') {
count++;
}
}
código em C
#include <stdio.h>
int main() {
42
int arr[] = {34, 78, 12, 56, 89, 23};
int size = sizeof(arr) / sizeof(arr[0]);
int min = arr[0], max = arr[0];
43
4. Binary to Decimal Conversion
Exercise: Write a program to convert a binary
number (entered as a string) to its decimal
equivalent.
código em C
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
char binary[32];
int decimal = 0;
44
for (int i = 0; i < length; i++) {
if (binary[length - i - 1] == '1') {
decimal += pow(2, i);
}
}
código em C
#include <stdio.h>
int main() {
int a[2][2], b[2][2], result[2][2];
45
printf("Enter elements of matrix A:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &a[i][j]);
}
}
// Matrix addition
for (int i = 0; i < 2; i++) {
46
for (int j = 0; j < 2; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
return 0;
}
6. Count Words in a Sentence
Exercise: Write a program to count the number of
words in a sentence.
47
código em C
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int count = 0;
int in_word = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
if (!in_word) {
count++;
48
in_word = 1;
}
} else {
in_word = 0;
}
}
código em C
#include <stdio.h>
int fibonacci(int n) {
49
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Sequence:\n");
for (int i = 0; i < n; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
return 0;
}
50
8. Find Prime Numbers up to N
Exercise: Write a program to find all prime
numbers up to a given number N.
código em C
#include <stdio.h>
#include <stdbool.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
return 0;
}
9. Calculate GCD (Greatest Common Divisor)
Exercise: Write a program to find the GCD of two
integers using the Euclidean algorithm.
código em C
#include <stdio.h>
52
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
código em C
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[50];
int age;
};
int main() {
int n;
printf("Enter the number of students: ");
54
scanf("%d", &n);
getchar(); // to consume the newline character
after the integer input
if (students == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
55
"\n")] = '\0';
printf("Student Information:\n");
for (int i = 0; i < n; i++) {
printf("Student %d - Name: %s, Age: %d\n", i
+ 1, students[i].name, students[i].age);
}
free(students);
return 0;
}
Feel free to modify these exercises according to
56
your needs or expand upon them to explore more
advanced topics. Happy coding!
57