Escolar Documentos
Profissional Documentos
Cultura Documentos
Array unidimensional
Definição
• É a forma mais comum de dados
estruturados na linguagem C. Um
vetor é simplesmente um conjunto
de variáveis do mesmo tipo,
igualmente acessíveis por um
índice.
Declaração
tipo nome[qtd_elementos]
Exemplo:
int main(){
int vetor[3]; //vetor com 3 posições
vetor[0] = 1;
vetor[1] = 5;
vetor[2] = -2;
printf("%d", vetor[1] + vetor[2]); // 3
return 0;
}
Inicialização de vetores
#include <stdio.h>
int main(){
int vetor[4] = {5,9,-7,10};
printf("%d", vetor[1] + vetor[3]); //19
return 0;
}
Preenchendo e imprimindo um
vetor
#include <stdio.h>
int main(){
int i; //índice
int vetor[3]; //vetor com 3 posições
return 0;
}
Elementos de um vetor na memória
Memória
# Var Valor
função rand();
int main(){
int i, vetor[3];
/* preenchendo o vetor com números
aleatórios. */
for (i = 0; i < 3; i++)
vetor[i] = rand();
return 0;
}
Definindo intervalo dos números
gerados
Ex:
srand(time(NULL));
Exercício
• Preencha um vetor automaticamente
de tamanho n com valores
aleatórios de 0 a n
Resposta
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, n;
do {
printf("Tam do vetor: ");
scanf("%d", &n);
} while (n < 1);
srand(time(NULL));
int v[n];
return 0;
}
Matrizes
Array bidimensional
Definição
• Da mesma forma dos vetores, porem,
seus valores podem ser organizados
em linhas e colunas
Declaração
tipo nome[qtd_linhas][qtd_colunas]
Exemplo:
int main(){
int mat[3][3]; //matriz com 9 posições
mat[0][0] = 5;
mat[1][1] = 3;
mat[2][2] = 0;
printf("%d", mat[0][0] + mat[1][1]); // 8
return 0;
}
Preenchendo (automaticamente) e
imprimindo uma matriz (formatada)
#include <stdio.h>
int main(){
int m[2][2], i, j;
for (i = 0; i < 2; i++){
for (j = 0; j < 2; j++)
m[i][j] = rand() % 10;
}
for (i = 0; i < 2; i++){
for (j = 0; j < 2; j++)
printf("%d ", m[i][j]);
printf("\n");
}
return 0;
}
Passando uma matriz para
função
• Pesquisem!
Strings
Array de caracteres
Definição
• Uma string é uma sequência de
caracteres adjacentes na memória
do computador. Uma string termina
em '\o'.
• Essa sequência de caracteres, que
pode ser uma palavra ou frase, é
armazenada na memória do
computador na forma de um array do
tipo char.
Declaração
• char nome[20];
• char frase[100];
Manipulando os valores
nome[3] = 'J';
nome[5] = 't'; //manJet
Preencher e imprimir uma
String
char nome[50];
• Preencher
– scanf("%s", nome);
– gets(nome);
• Imprimir
– printf("%s", nome);
– puts(nome);
O que será impresso?
#include <stdio.h>
int main(){
char nome = "Computador";
nome[4] = '\0';
printf("%s", nome);
return 0;
}
Array de Strings
A biblioteca string
• A biblioteca padrão string da linguagem
C contém várias funções de manipulação
de strings. Para usar essas funções, o
seu programa deve incluir o arquivo-
interface string.h
#include <string.h>
• Funções para manipulação de Strings
– unsigned int strlen(char *str);
– int strcmp(char *str, char *str2);
– char *strcpy(char *str, char *str2);
– char *strcat(char *str, char *str2);
strlen
• Retorna um inteiro referente ao
tamanho da string
Exemplo
#include <stdio.h>
int main() {
char s1[10] = "Computador";
printf("%d", strlen(s1)); //10
return 0;
}
strcmp
• Compara duas strings e retorna
– 0, se strings iguais
– 1, se primeira string for maior
– -1, se segunda string for maior
Exemplo
#include <stdio.h>
int main() {
char s1[10] = "Computador";
char s2[10] = "Internet";
printf("%d", strcmp(s1, s2)); //-1
return 0;
}
strcat
• Concatena a primeira string com a
segunda e retorna a string concatenada.
Exemplo
#include <stdio.h>
int main() {
char s1[10] = "Computador";
char s2[10] = "Internet";
printf("%s ", strcat(s1, s2));
//ComputadorInternet
return 0;
}
O que será impresso?
#include <stdio.h>
int main() {
char s1[10] = "Computador";
char s2[10] = "Internet";
printf("%s ", s1);
printf("%s ", s2);
strcat(s1, s2)
printf("%s ", s1);
printf("%s ", s2);
return 0;
}
strcpy
• Copia o valor da segunda string para a
primeira. Retorna o valor copiado.
Exemplo
#include <stdio.h>
int main() {
char s1[10] = "Computador";
char s2[10] = "Internet";
printf("%s ", strcpy(s1, s2));
//Internet
return 0;
}
O que será impresso?
#include <stdio.h>
int main() {
char s1[10] = "Computador";
char s2[10] = "Internet";
printf("%s ", s1);
printf("%s ", s2);
strcpy(s1, s2)
printf("%s ", s1);
printf("%s ", s2);
return 0;
}
Pesquise!
• Funções
– strncpy
– strncat
– memset
– memcpy
– memcmp
– memchr