SlideShare une entreprise Scribd logo
1  sur  26
©Todos os direitos reservados Klais®
Curso de Java
Vetores e Matrizes
Roteiro
©Todos os direitos reservados Klais®
• Declaração de um vetor
• Lista de valores
• Acesso aos elementos
• Valor inicial de um vetor
• Matriz
• Vetor de vetores
• Tamanho de um vetor
©Todos os direitos reservados Klais®
Vetores e Matrizes
• Java oferece diversos mecanismos para a
criação de novos tipos de dados a partir
de tipos já existentes.
• Um desses mecanismos é o que permite a
construção de vetores e matrizes.
©Todos os direitos reservados Klais®
Declaração de um Vetor
Um exemplo:
int[] v = new int[10];
– v é declarado com um vetor de inteiros
©Todos os direitos reservados Klais®
– a expressão new int[10] cria
efetivamente um vetor de inteiros, de
tamanho 10.
– o comando de atribuição associa o vetor
criado ao vetor v.
Declaração de um Vetor
©Todos os direitos reservados Klais®
• Tendo declarado a variável int[] v, esta pode
ser associada a qualquer vetor de inteiros. Um
exemplo:
...
int[] v10 = new
int[10]; int[] v20 =
new int[20]; int i =
x+10/16; int[] v;
...
switch(i) {
case 10: v = v10; break;
case 20: v = v20; break;
default: v = new int[i]; break;
}
©Todos os direitos reservados Klais®
...
Lista de Valores
• Um vetor também ser pode ser criado a
partir de uma lista de valores entre { e } e
separadospor vírgula.
• Exemplos:
©Todos os direitos reservados Klais®
int[] primos = { 2,3,5,7,11,13,17,19 };
char[] dd = {
'd','s','t','q','q','s','s'}; String[]
meses = {"jan","fev","mar","abr" };
Acesso aos elementos
©Todos os direitos reservados Klais®
• Tendo criado um vetor, o acesso aos seus
elementos é feito a partir da sua posição,ou
índice, no vetor.
• Se um vetor tem N elementos, os índices dos
seus elementos vão variar entre 0 e N-1.
• O índice para acesso ao elementos deve ser
um valor inteiro entre 0 e N-1, definido por
uma expressão.
©Todos os direitos reservados Klais®
Um exemplo
©Todos os direitos reservados Klais®
...
int[] f = new int[10];
f[0] = 0; f[1] = 1;
for( int i = 2; i < 10; i++ )
f[i] = f[i-1]+f[i-2];
...
©Todos os direitos reservados Klais®
Outro exemplo
©Todos os direitos reservados Klais®
public static void main(String[] args){
int[] primos = { 2,3,5,7,11,13,17,19,23,29,31 };
int[] somas = new int[11];
for(int i = 0; i < 11; i++){
somas[i] = 0;
for(int j = 0; j <= i; j++)
somas[i] += primos[j];
}
System.out.print("somas:“+somas);
for(int i = 0; i < 11; i++)
System.out.print(" “+somas[i]);
System.out.println();
}
©Todos os direitos reservados Klais®
Valor inicial de um vetor
• A criação de um vetor através de new apenas aloca a
memória necessária para o vetor, sem definir um valor
inicial para o mesmo.
• O valor inicial de um vetor pode ser definido através de
uma tupla da forma
{ valor, valor, ... , valor }
©Todos os direitos reservados Klais®
• O número de valores na tupla e o seu tipo devem ser
compatíveis com o vetor.
©Todos os direitos reservados Klais®
Um exemplo
©Todos os direitos reservados Klais®
...
int[] p = { 2,3,5,7,11, 13 };
int[] s = { p[0]+p[1], p[2]+p[3 ,] p[4]+p[5] };
string[] dias = {
"seg","ter","qua","qui",
"sex","sab","dom“
};
...
©Todos os direitos reservados Klais®
Matriz
• Uma matriz é basicamente um vetor onde cada
elemento é por sua vez um vetor.
• Um exemplo:
...
int[][] tab = new int[10][9]; for(int i =
0; i < 10; i++) for(int j = 0; j < 9;
j++) tab[i][j] = i*j; ...
©Todos os direitos reservados Klais®
• Neste exemplo, tab é uma matriz com 10 linhas
e 9 colunas.
Vetor de Vetores
• Uma matriz é um vetor de vetores, todos de
mesmo tamanho.
• Em Java, é possível criar um vetor de vetores onde
cada elemento tem um tamanho diferente.
©Todos os direitos reservados Klais®
• Nesse caso, cada elemento deve ser criado de
forma independente.
• Exemplo:
...
int[][] p = new
int[10][]; for(int i = 0;
i <= 10; i++) p[i] = new
int[i+1]; ...
©Todos os direitos reservados Klais®
Um exemplo
©Todos os direitos reservados Klais®
public static void main(String[] args){
int[][] p = new int[10][];
for(int i = 0; i < 10; i++)
p[i =] new int[i+1];
for(int i = 0; i < 10; i++){
p[i][0] = 1;
p[i][i] = 1;
for(int j = 1; j < i; j++)
p[i][j] = p[i-1][j-1]+p[i-1][j];
}
}
©Todos os direitos reservados Klais®
Outro exemplo
©Todos os direitos reservados Klais®
public static void main(String[] args){
int[] dias_mes = {
31,29,31,30,31,30,
31,31,30,31,30,31
};
float[][] gastos = new float[12][];
for(int m = 0; m < 12; m++) {
gastos[m] = new float[dias_mes[m]];
for(int d = 0; d < dias_mes[m]; d++)
gastos[m][d] = 0.0F;
}
}
©Todos os direitos reservados Klais®
Tamanho de um vetor
• Todo vetor em Java tem o atributo length que
define o seu número de elementos.
• Esse atributo pode ser usada pelo programa.
• Exemplo:
...
for(int m = 0; m < dias_mes.length;
m++){ gastos[m] = new
©Todos os direitos reservados Klais®
float[dias_mes[m]]; for(int d = 0; d <
gastos[m].length; d++) gastos[m][d] =
0.0F;
}
...

Contenu connexe

Dernier

ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx2m Assessoria
 
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docxATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx2m Assessoria
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploDanilo Pinotti
 
Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsDanilo Pinotti
 
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx2m Assessoria
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx2m Assessoria
 

Dernier (6)

ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
 
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docxATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemplo
 
Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object Calisthenics
 
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
 

En vedette

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

En vedette (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Vetores e matrizes

  • 1. ©Todos os direitos reservados Klais® Curso de Java Vetores e Matrizes Roteiro
  • 2. ©Todos os direitos reservados Klais® • Declaração de um vetor • Lista de valores • Acesso aos elementos • Valor inicial de um vetor • Matriz • Vetor de vetores • Tamanho de um vetor
  • 3. ©Todos os direitos reservados Klais® Vetores e Matrizes • Java oferece diversos mecanismos para a criação de novos tipos de dados a partir de tipos já existentes. • Um desses mecanismos é o que permite a construção de vetores e matrizes.
  • 4. ©Todos os direitos reservados Klais® Declaração de um Vetor Um exemplo: int[] v = new int[10]; – v é declarado com um vetor de inteiros
  • 5. ©Todos os direitos reservados Klais® – a expressão new int[10] cria efetivamente um vetor de inteiros, de tamanho 10. – o comando de atribuição associa o vetor criado ao vetor v. Declaração de um Vetor
  • 6. ©Todos os direitos reservados Klais® • Tendo declarado a variável int[] v, esta pode ser associada a qualquer vetor de inteiros. Um exemplo: ... int[] v10 = new int[10]; int[] v20 = new int[20]; int i = x+10/16; int[] v; ... switch(i) { case 10: v = v10; break; case 20: v = v20; break; default: v = new int[i]; break; }
  • 7. ©Todos os direitos reservados Klais® ... Lista de Valores • Um vetor também ser pode ser criado a partir de uma lista de valores entre { e } e separadospor vírgula. • Exemplos:
  • 8. ©Todos os direitos reservados Klais® int[] primos = { 2,3,5,7,11,13,17,19 }; char[] dd = { 'd','s','t','q','q','s','s'}; String[] meses = {"jan","fev","mar","abr" }; Acesso aos elementos
  • 9. ©Todos os direitos reservados Klais® • Tendo criado um vetor, o acesso aos seus elementos é feito a partir da sua posição,ou índice, no vetor. • Se um vetor tem N elementos, os índices dos seus elementos vão variar entre 0 e N-1. • O índice para acesso ao elementos deve ser um valor inteiro entre 0 e N-1, definido por uma expressão.
  • 10. ©Todos os direitos reservados Klais® Um exemplo
  • 11. ©Todos os direitos reservados Klais® ... int[] f = new int[10]; f[0] = 0; f[1] = 1; for( int i = 2; i < 10; i++ ) f[i] = f[i-1]+f[i-2]; ...
  • 12. ©Todos os direitos reservados Klais® Outro exemplo
  • 13. ©Todos os direitos reservados Klais® public static void main(String[] args){ int[] primos = { 2,3,5,7,11,13,17,19,23,29,31 }; int[] somas = new int[11]; for(int i = 0; i < 11; i++){ somas[i] = 0; for(int j = 0; j <= i; j++) somas[i] += primos[j]; } System.out.print("somas:“+somas); for(int i = 0; i < 11; i++) System.out.print(" “+somas[i]); System.out.println(); }
  • 14. ©Todos os direitos reservados Klais® Valor inicial de um vetor • A criação de um vetor através de new apenas aloca a memória necessária para o vetor, sem definir um valor inicial para o mesmo. • O valor inicial de um vetor pode ser definido através de uma tupla da forma { valor, valor, ... , valor }
  • 15. ©Todos os direitos reservados Klais® • O número de valores na tupla e o seu tipo devem ser compatíveis com o vetor.
  • 16. ©Todos os direitos reservados Klais® Um exemplo
  • 17. ©Todos os direitos reservados Klais® ... int[] p = { 2,3,5,7,11, 13 }; int[] s = { p[0]+p[1], p[2]+p[3 ,] p[4]+p[5] }; string[] dias = { "seg","ter","qua","qui", "sex","sab","dom“ }; ...
  • 18. ©Todos os direitos reservados Klais® Matriz • Uma matriz é basicamente um vetor onde cada elemento é por sua vez um vetor. • Um exemplo: ... int[][] tab = new int[10][9]; for(int i = 0; i < 10; i++) for(int j = 0; j < 9; j++) tab[i][j] = i*j; ...
  • 19. ©Todos os direitos reservados Klais® • Neste exemplo, tab é uma matriz com 10 linhas e 9 colunas. Vetor de Vetores • Uma matriz é um vetor de vetores, todos de mesmo tamanho. • Em Java, é possível criar um vetor de vetores onde cada elemento tem um tamanho diferente.
  • 20. ©Todos os direitos reservados Klais® • Nesse caso, cada elemento deve ser criado de forma independente. • Exemplo: ... int[][] p = new int[10][]; for(int i = 0; i <= 10; i++) p[i] = new int[i+1]; ...
  • 21. ©Todos os direitos reservados Klais® Um exemplo
  • 22. ©Todos os direitos reservados Klais® public static void main(String[] args){ int[][] p = new int[10][]; for(int i = 0; i < 10; i++) p[i =] new int[i+1]; for(int i = 0; i < 10; i++){ p[i][0] = 1; p[i][i] = 1; for(int j = 1; j < i; j++) p[i][j] = p[i-1][j-1]+p[i-1][j]; } }
  • 23. ©Todos os direitos reservados Klais® Outro exemplo
  • 24. ©Todos os direitos reservados Klais® public static void main(String[] args){ int[] dias_mes = { 31,29,31,30,31,30, 31,31,30,31,30,31 }; float[][] gastos = new float[12][]; for(int m = 0; m < 12; m++) { gastos[m] = new float[dias_mes[m]]; for(int d = 0; d < dias_mes[m]; d++) gastos[m][d] = 0.0F; } }
  • 25. ©Todos os direitos reservados Klais® Tamanho de um vetor • Todo vetor em Java tem o atributo length que define o seu número de elementos. • Esse atributo pode ser usada pelo programa. • Exemplo: ... for(int m = 0; m < dias_mes.length; m++){ gastos[m] = new
  • 26. ©Todos os direitos reservados Klais® float[dias_mes[m]]; for(int d = 0; d < gastos[m].length; d++) gastos[m][d] = 0.0F; } ...