0% found this document useful (0 votes)
14 views57 pages

C Programming Exercises

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views57 pages

C Programming Exercises

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C

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

Copyright© 2001-2022, Esse Ebook feito por APOSTILAS em MASSA.


Todos os direitos reservados. Todos os textos, imagens, gráficos,
animações, vídeos, músicas, sons e outros materiais são protegidos por
direitos autorais e outros direitos de propriedade intelectual
pertencentes à esse Ebook feito por APOSTILAS em MASSA , suas
subsidiárias, afiliadas e licenciantes.

Esse Ebook feito por APOSTILAS em MASSA é, também, proprietário dos


direitos autorais de desenvolvimento, seleção, coordenação,
diagramação e disposição dos materiais neste site. É expressamente
vedada a cópia ou reprodução destes materiais para uso ou distribuição
comercial, a modificação destes materiais, sua inclusão em outros
websites e o seu envio e publicação em outros meios digitais e físicos, ou
de qualquer outra forma dispor de tais materiais sem a devida
autorização, estando sujeito às responsabilidades e sanções legais.

Marcas

Todas as marcas exibidas neste Ebook são de propriedade exclusiva do

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.

Direito autoral tradicional, definido pela expressão “todos os direitos


reservados”. Significa que todos os direitos relativos àquela obra, como
reprodução, alteração, distribuição comercialização, pe...

Direitos autorais do Ebook do APOSTILAS em MASSA (2024)

Todos os textos, fotos e imagens, mapas, logomarca e mascote


apresentados no Ebook do APOSTILAS em MASSA (2024) são protegidos
por lei.

Qualquer reprodução (total ou parcial) do conteúdo divulgado no site,


sem a prévia autorização, é proibida.

NENHUM meio de divulgação (jornais, revistas, televisão, websites, sites,


minisites, miniblog, blogs e etc.), empresas, pessoas físicas ou qualquer
outro veículo de comunicação (folders, panfletos, cartões de visitas,
trabalhos acadêmicos, apresentações etc.) está autorizado a utilizar as
informações e/ou imagens mesmo que coloque os créditos.

----------------------

CÓDIGO PENAL - Dos crimes contra a propriedade intelectual

Violação de direito autoral - Art. 184

Pena de detenção de 3 meses a 1 ano.

Se a violação consistir em reprodução, por qualquer meio, com intuito


de lucro, qualifica o crime.

Pena de reclusão de 1 ano a 4 anos.

----------------------

DIREITOS AUTORAIS - Lei 9.610 de 19 de fevereiro de 1998.

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.

Art. 28 - Cabe ao autor o direito exclusivo de utilizar, fruir e dispor da


obra literária, artística ou científica.

Veja a íntegra da lei em: http://www.planalto.gov.br/CCIVIL_


03/leis/9610.htm

----------------------

Sobre o Copyright

O © Copyright é um símbolo do direito autoral, uma forma de direito


intelectual.

Também denominado direitos de autor ou direitos autorais, o copyright


impede a cópia ou exploração de qualquer obra sem que haja permissão
para tal. Toda obra original incluindo música, imagens, vídeos,
documentos digitais, fotografias, arranjo gráfico etc., são trabalhos que
dão ao proprietário direito exclusivo.

O símbolo do copyright © quando presente em uma obra restringe a sua


impressão e/ou publicação sem autorização prévia, impedindo que haja
benefícios financeiros para outros que não sejam o autor ou o editor da
obra.

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

Sure! Here are some C programming exercises


designed to help you practice and reinforce your

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);

for (int i = 1; i <= num; i++) {


factorial *= i;
}

printf("Factorial of %d is %d\n", num, factorial);


return 0;
}
4. Fibonacci Series
Exercise: Write a program to print the first n terms
of the Fibonacci series.

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);

printf("Fibonacci Series: ");


for (int i = 0; i < n; i++) {
if (i == 0) {
printf("%d ", first);
continue;
}
if (i == 1) {
printf("%d ", second);
continue;
}
next = first + second;
first = second;

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>

bool is_prime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) return false;
11
}
return true;
}

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;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);
length = strlen(str) - 1; // -1 to remove the
newline character

// Remove the newline character if it exists


if (str[length] == '\n') {
str[length] = '\0';
13
length--;
}

// Reverse the string


for (int i = 0; i < length / 2; i++) {
temp = str[i];
str[i] = str[length - i];
str[length - i] = temp;
}

printf("Reversed string: %s\n", str);


return 0;
}
7. Matrix Multiplication
Exercise: Write a program to multiply two
matrices.

código em C
14
#include <stdio.h>

#define MAX 10

void multiply_matrices(int a[MAX][MAX], int


b[MAX][MAX], int c[MAX][MAX], int row_a, int
col_a, int row_b, int col_b) {
for (int i = 0; i < row_a; i++) {
for (int j = 0; j < col_b; j++) {
c[i][j] = 0;
for (int k = 0; k < col_a; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
}

int main() {

15
int a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];
int row_a, col_a, row_b, col_b;

printf("Enter rows and columns for matrix A: ");


scanf("%d %d", &row_a, &col_a);

printf("Enter elements of matrix A:\n");


for (int i = 0; i < row_a; i++) {
for (int j = 0; j < col_a; j++) {
scanf("%d", &a[i][j]);
}
}

printf("Enter rows and columns for matrix B: ");


scanf("%d %d", &row_b, &col_b);

if (col_a != row_b) {

16
printf("Matrix multiplication not possible.\n");
return 1;
}

printf("Enter elements of matrix B:\n");


for (int i = 0; i < row_b; i++) {
for (int j = 0; j < col_b; j++) {
scanf("%d", &b[i][j]);
}
}

multiply_matrices(a, b, c, row_a, col_a, row_b,


col_b);

printf("Resultant matrix C:\n");


for (int i = 0; i < row_a; i++) {
for (int j = 0; j < col_b; j++) {
printf("%d ", c[i][j]);
17
}
printf("\n");
}

return 0;
}
8. Bubble Sort
Exercise: Implement the Bubble Sort algorithm to
sort an array of integers.

código em C
#include <stdio.h>

void bubble_sort(int arr[], int n) {


int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
18
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

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]);

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);

// Reading from the file


file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
printf("Content of the file:\n");
while (fgets(text, sizeof(text), 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;

printf("Enter the number of elements: ");


22
scanf("%d", &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");

// Free allocated memory


free(arr);

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]);

printf("Array elements are:\n");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

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;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

for (int i = 0; str[i] != '\0'; i++) {


26
char ch = tolower(str[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o'
|| ch == 'u') {
count++;
}
}

printf("Number of vowels: %d\n", count);


return 0;
}
3. Find the Largest Element in an Array
Exercise: Write a program to find the largest
element in an array of integers.

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];

for (int i = 1; i < size; i++) {


if (arr[i] > max) {
max = arr[i];
}
}

printf("The largest element is %d\n", max);


return 0;
}
4. Check for Palindrome
Exercise: Write a program that checks if a given
string is a palindrome.

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;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

// Remove newline character if present


len = strlen(str) - 1;
if (str[len] == '\n') {
str[len] = '\0';
}

29
start = 0;
end = len;

while (start < end) {


if (tolower(str[start]) != tolower(str[end])) {
is_palindrome = 0;
break;
}
start++;
end--;
}

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;

for (int i = 0; i < size; i++) {


sum += arr[i];
}
31
float average = (float)sum / size;
printf("Average of array elements: %.2f\n",
average);
return 0;
}
6. Reverse an Array
Exercise: Write a program to reverse the elements
of an array.

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");

// Reverse the array


for (int i = 0; i < size / 2; i++) {
temp = arr[i];
arr[i] = arr[size - i - 1];
arr[size - i - 1] = temp;
}

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;

printf("Enter a number: ");


scanf("%d", &num);

printf("Multiplication table for %d:\n", num);


34
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}

return 0;
}
8. Bubble Sort
Exercise: Implement the Bubble Sort algorithm to
sort an array of integers.

código em C
#include <stdio.h>

void bubble_sort(int arr[], int n) {


int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
35
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

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;

printf("Enter two numbers: ");


scanf("%d %d", &a, &b);

37
// Swap the values
temp = a;
a = b;
b = temp;

printf("After swapping: a = %d, b = %d\n", a, b);


return 0;
}
10. Sum of Natural Numbers
Exercise: Write a program to calculate the sum of
the first n natural numbers.

código em C
#include <stdio.h>

int main() {
int n, sum = 0;

38
printf("Enter a positive integer: ");
scanf("%d", &n);

for (int i = 1; i <= n; i++) {


sum += i;
}

printf("Sum of the first %d natural numbers is %


d\n", n, sum);
return 0;
}
These exercises cover a range of fundamental C
programming concepts and should help you build
a solid foundation. Feel free to modify and expand
upon them as you continue to learn!
C programming 10 exercises
Certainly! Here are 10 C programming exercises
designed to test and enhance your understanding
of various C programming concepts. Each exercise

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;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

41
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] != ' ' && str[i] != '\n') {
count++;
}
}

printf("Number of characters (excluding spaces):


%d\n", count);
return 0;
}
3. Find the Minimum and Maximum in an Array
Exercise: Write a program to find the smallest and
largest elements in an array.

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];

for (int i = 1; i < size; i++) {


if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}

printf("Minimum value: %d\n", min);


printf("Maximum value: %d\n", max);
return 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;

printf("Enter a binary number: ");


scanf("%s", binary);

int length = strlen(binary);

44
for (int i = 0; i < length; i++) {
if (binary[length - i - 1] == '1') {
decimal += pow(2, i);
}
}

printf("Decimal equivalent: %d\n", decimal);


return 0;
}
5. Matrix Addition
Exercise: Write a program to add two matrices of
size 2x2.

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]);
}
}

printf("Enter elements of matrix B:\n");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &b[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];
}
}

printf("Resultant matrix after addition:\n");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

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;

printf("Enter a sentence: ");


fgets(str, sizeof(str), stdin);

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;
}
}

printf("Number of words: %d\n", count);


return 0;
}
7. Fibonacci Sequence Using Recursion
Exercise: Write a recursive function to print the
Fibonacci sequence up to the nth term.

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);

printf("Prime numbers up to %d are:\n", n);


for (int i = 2; i <= n; i++) {
bool is_prime = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
51
is_prime = false;
break;
}
}
if (is_prime) {
printf("%d ", i);
}
}
printf("\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);

printf("GCD of %d and %d is %d\n", a, b, gcd(a,


b));
return 0;
53
}
10. Dynamic Memory Allocation with Structures
Exercise: Write a program to dynamically allocate
memory for an array of structures and print their
contents.

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

struct Student *students = (struct Student *)


malloc(n * sizeof(struct Student));

if (students == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

for (int i = 0; i < n; i++) {


printf("Enter name of student %d: ", i + 1);
fgets(students[i].name,
sizeof(students[i].name), stdin);
// Remove newline character from the name
students[i].name[strcspn(students[i].name,

55
"\n")] = '\0';

printf("Enter age of student %d: ", i + 1);


scanf("%d", &students[i].age);
getchar(); // to consume the newline
character after the integer input
}

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

You might also like