Introdução
Em C, um array (vetor) é uma coleção de tipos de dados semelhantes armazenados em locais de memória contíguos. Ele ajuda a armazenar múltiplos valores sob um único nome de variável, economizando espaço de memória e simplificando a estrutura do código. Neste laboratório, aprenderemos como inserir um elemento em um array em uma posição específica.
Nota: Você precisa criar o arquivo
~/project/main.cpor conta própria para praticar a codificação e aprender como compilar e executá-lo usando o gcc.
cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main
Criando um Array
Nesta etapa, criaremos um array (vetor) com alguns elementos iniciais e exibiremos seus valores.
#include <stdio.h>
int main() {
// Define variáveis e array
int array[5] = {10, 20, 30, 40, 50};
int n = 5, i;
printf("Initial array: ");
for(i=0; i<n; i++) {
printf("%d ", array[i]);
}
return 0;
}
Recebendo Entrada do Usuário
Nesta etapa, receberemos a entrada do usuário para o novo valor a ser inserido e o índice onde o valor será inserido.
#include <stdio.h>
int main() {
// Define variáveis e array
int array[5] = {10, 20, 30, 40, 50};
int n = 5, i, value, position;
printf("Initial array: ");
for(i=0; i<n; i++) {
printf("%d ", array[i]);
}
// Take input for new value and position
printf("\n\nEnter the value to insert: ");
scanf("%d", &value);
printf("Enter the position to insert: ");
scanf("%d", &position);
return 0;
}
Inserindo o Elemento
Nesta etapa, inseriremos o novo elemento no array na posição fornecida. Deslocaremos os elementos existentes para a direita da posição e adicionaremos o novo elemento no índice da posição.
#include <stdio.h>
int main() {
// Define variáveis e array
int array[5] = {10, 20, 30, 40, 50};
int n = 5, i, value, position;
printf("Initial array: ");
for(i=0; i<n; i++) {
printf("%d ", array[i]);
}
// Take input for new value and position
printf("\n\nEnter the value to insert: ");
scanf("%d", &value);
printf("Enter the position to insert: ");
scanf("%d", &position);
// Shift the existing elements to right of the position
for(i=n-1; i>=position-1; i--) {
array[i+1] = array[i];
}
// Insert the new element at the position index
array[position-1] = value;
return 0;
}
Exibindo o Resultado
Nesta etapa, exibiremos o novo array com o elemento inserido.
#include <stdio.h>
int main() {
// Define variáveis e array
int array[5] = {10, 20, 30, 40, 50};
int n = 5, i, value, position;
printf("Initial array: ");
for(i=0; i<n; i++) {
printf("%d ", array[i]);
}
// Take input for new value and position
printf("\n\nEnter the value to insert: ");
scanf("%d", &value);
printf("Enter the position to insert: ");
scanf("%d", &position);
// Shift the existing elements to right of the position
for(i=n-1; i>=position-1; i--) {
array[i+1] = array[i];
}
// Insert the new element at the position index
array[position-1] = value;
// Display the new array
printf("\n\nNew array with the inserted element: ");
for(i=0; i<n+1; i++) {
printf("%d ", array[i]);
}
return 0;
}
Código Final
Abaixo está o código final para inserir um elemento em um array:
#include <stdio.h>
int main() {
// Define variáveis e array
int array[5] = {10, 20, 30, 40, 50};
int n = 5, i, value, position;
printf("Initial array: ");
for(i=0; i<n; i++) {
printf("%d ", array[i]);
}
// Take input for new value and position
printf("\n\nEnter the value to insert: ");
scanf("%d", &value);
printf("Enter the position to insert: ");
scanf("%d", &position);
// Shift the existing elements to right of the position
for(i=n-1; i>=position-1; i--) {
array[i+1] = array[i];
}
// Insert the new element at the position index
array[position-1] = value;
// Display the new array
printf("\n\nNew array with the inserted element: ");
for(i=0; i<n+1; i++) {
printf("%d ", array[i]);
}
return 0;
}
Resumo
Neste laboratório, aprendemos como inserir um elemento em um array em uma posição específica usando C. Criamos um array inicial, recebemos a entrada do usuário para o novo elemento e a posição, inserimos o elemento no array na posição especificada deslocando os elementos existentes para a direita e exibimos o novo array resultante.



