Um loop aninhado (nested loops) é quando temos um loop dentro de outro loop. Isso é muito útil para trabalhar com matrizes (arrays bidimensionais), pois precisamos percorrer linhas e colunas.
Loop aninhado:
for (int i = 0; i < linhas; i++) { // Loop externo - linhas
for (int j = 0; j < colunas; j++) { // Loop interno - colunas
// Código para processar matriz[i][j]
}
}
Convenção:
i = índice de linhaj = índice de coluna
public class ConstruirMatriz {
public static void main(String[] args) {
// Criando uma matriz 3x4 vazia
int[][] matriz = new int[3][4];
// Preenchendo a matriz com loop aninhado
for (int i = 0; i < matriz.length; i++) { // Linhas
for (int j = 0; j < matriz[i].length; j++) { // Colunas
matriz[i][j] = i + j;
}
}
// Exibindo a matriz
System.out.println("Matriz 3x4:");
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
System.out.print(matriz[i][j] + "\t");
}
System.out.println();
}
}
}
Matriz 3x4:
0 1 2 3
1 2 3 4
2 3 4 5
Em Java, matriz[i] representa uma linha inteira da matriz.
Isso é útil quando queremos referenciar ou trabalhar com uma linha completa.
public class AcessarFileira {
public static void main(String[] args) {
int[][] matriz = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
// matriz[i] é uma linha inteira
System.out.println("Primeira linha: matriz[0]");
for (int j = 0; j < matriz[0].length; j++) {
System.out.print(matriz[0][j] + " ");
}
System.out.println("\n\nSegunda linha: matriz[1]");
for (int j = 0; j < matriz[1].length; j++) {
System.out.print(matriz[1][j] + " ");
}
}
}
Primeira linha: matriz[0]
10 20 30
Segunda linha: matriz[1]
40 50 60
matriz[i].length retorna o número de colunas da linha i.
public class ComprimentoFileira {
public static void main(String[] args) {
int[][] matriz = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Mostrando o comprimento de cada linha
System.out.println("Número de linhas: " + matriz.length);
for (int i = 0; i < matriz.length; i++) {
System.out.println("Linha " + i + " tem " + matriz[i].length + " colunas");
}
}
}
Número de linhas: 3
Linha 0 tem 4 colunas
Linha 1 tem 4 colunas
Linha 2 tem 4 colunas
public class Tabuada {
public static void main(String[] args) {
// Criando uma matriz 10x10 para tabuada
int[][] tabuada = new int[10][10];
// Preenchendo com loop aninhado
for (int i = 0; i < tabuada.length; i++) {
for (int j = 0; j < tabuada[i].length; j++) {
tabuada[i][j] = (i + 1) * (j + 1);
}
}
// Exibindo a tabuada
System.out.println("=== TABUADA 10x10 ===");
System.out.print("\t");
for (int j = 1; j <= 10; j++) {
System.out.print(j + "\t");
}
System.out.println();
for (int i = 0; i < tabuada.length; i++) {
System.out.print((i + 1) + "\t");
for (int j = 0; j < tabuada[i].length; j++) {
System.out.print(tabuada[i][j] + "\t");
}
System.out.println();
}
}
}
=== TABUADA 10x10 ===
1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 2 4 6 8 10 12 14 16 18 20
3 3 6 9 12 15 18 21 24 27 30
4 4 8 12 16 20 24 28 32 36 40
5 5 10 15 20 25 30 35 40 45 50
6 6 12 18 24 30 36 42 48 54 60
7 7 14 21 28 35 42 49 56 63 70
8 8 16 24 32 40 48 56 64 72 80
9 9 18 27 36 45 54 63 72 81 90
10 10 20 30 40 50 60 70 80 90 100
public class MatrizInteiros {
public static void main(String[] args) {
// Criando matriz 5x5
int[][] matriz = new int[5][5];
// Preenchendo com valores sequenciais
int valor = 1;
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
matriz[i][j] = valor;
valor++;
}
}
// Exibindo
System.out.println("Matriz 5x5 com valores de 1 a 25:");
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
System.out.printf("%3d ", matriz[i][j]);
}
System.out.println();
}
}
}
Matriz 5x5 com valores de 1 a 25:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
public class MatrizDecimais {
public static void main(String[] args) {
// Matriz de temperaturas (3 dias x 4 horários)
double[][] temperaturas = new double[3][4];
// Preenchendo com valores simulados
for (int i = 0; i < temperaturas.length; i++) {
for (int j = 0; j < temperaturas[i].length; j++) {
temperaturas[i][j] = 20.0 + (i * 2) + (j * 1.5);
}
}
// Exibindo
System.out.println("Temperaturas (3 dias x 4 horários):");
System.out.println("Dia\t06h\t12h\t18h\t00h");
System.out.println("----------------------------------------");
for (int i = 0; i < temperaturas.length; i++) {
System.out.print((i + 1) + "\t");
for (int j = 0; j < temperaturas[i].length; j++) {
System.out.printf("%.1f\t", temperaturas[i][j]);
}
System.out.println();
}
}
}
Temperaturas (3 dias x 4 horários):
Dia 06h 12h 18h 00h
----------------------------------------
1 20.0 21.5 23.0 24.5
2 22.0 23.5 25.0 26.5
3 24.0 25.5 27.0 28.5
public class MatrizIdentidade {
public static void main(String[] args) {
int[][] identidade = new int[4][4];
// Diagonal principal recebe 1
for (int i = 0; i < identidade.length; i++) {
for (int j = 0; j < identidade[i].length; j++) {
if (i == j) {
identidade[i][j] = 1;
} else {
identidade[i][j] = 0;
}
}
}
System.out.println("Matriz Identidade 4x4:");
for (int i = 0; i < identidade.length; i++) {
for (int j = 0; j < identidade[i].length; j++) {
System.out.print(identidade[i][j] + " ");
}
System.out.println();
}
}
}
Matriz Identidade 4x4:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
public class TabuleiroXadrez {
public static void main(String[] args) {
int[][] tabuleiro = new int[8][8];
// Alternando 0 e 1
for (int i = 0; i < tabuleiro.length; i++) {
for (int j = 0; j < tabuleiro[i].length; j++) {
tabuleiro[i][j] = (i + j) % 2;
}
}
System.out.println("Padrão de Tabuleiro 8x8:");
for (int i = 0; i < tabuleiro.length; i++) {
for (int j = 0; j < tabuleiro[i].length; j++) {
System.out.print(tabuleiro[i][j] + " ");
}
System.out.println();
}
}
}
Padrão de Tabuleiro 8x8:
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
public class SomaMatriz {
public static void main(String[] args) {
int[][] matriz = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int soma = 0;
// Somando todos os elementos
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
soma += matriz[i][j];
}
}
System.out.println("Soma de todos os elementos: " + soma);
}
}
Soma de todos os elementos: 45
public class MaiorValorMatriz {
public static void main(String[] args) {
int[][] matriz = {
{15, 23, 8},
{42, 19, 35},
{27, 31, 12}
};
int maior = matriz[0][0];
// Encontrando o maior valor
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
if (matriz[i][j] > maior) {
maior = matriz[i][j];
}
}
}
System.out.println("Maior valor na matriz: " + maior);
}
}
Maior valor na matriz: 42
public class SistemaNotas {
public static void main(String[] args) {
// Matriz: 4 alunos x 3 provas
double[][] notas = {
{7.5, 8.0, 9.0},
{6.5, 7.5, 8.5},
{9.0, 9.5, 8.0},
{5.5, 6.0, 7.0}
};
System.out.println("=== SISTEMA DE NOTAS ===");
System.out.println("Aluno\tP1\tP2\tP3\tMédia");
System.out.println("----------------------------------------");
// Calculando média de cada aluno
for (int i = 0; i < notas.length; i++) {
System.out.print((i + 1) + "\t");
double soma = 0;
for (int j = 0; j < notas[i].length; j++) {
System.out.print(notas[i][j] + "\t");
soma += notas[i][j];
}
double media = soma / notas[i].length;
System.out.printf("%.2f\n", media);
}
// Média geral da turma
double somaGeral = 0;
int totalNotas = 0;
for (int i = 0; i < notas.length; i++) {
for (int j = 0; j < notas[i].length; j++) {
somaGeral += notas[i][j];
totalNotas++;
}
}
double mediaGeral = somaGeral / totalNotas;
System.out.println("\nMédia geral da turma: " + String.format("%.2f", mediaGeral));
}
}
=== SISTEMA DE NOTAS ===
Aluno P1 P2 P3 Média
----------------------------------------
1 7.5 8.0 9.0 8.17
2 6.5 7.5 8.5 7.50
3 9.0 9.5 8.0 8.83
4 5.5 6.0 7.0 6.17
Média geral da turma: 7.67
Teste seus conhecimentos sobre Loop Aninhado para Matrizes:
matriz[i][j]matriz[i] = linha inteiramatriz.length = número de linhasmatriz[i].length = número de colunas da linha iReforce o conteúdo desta aula com mais dois exercícios práticos: