/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sampleProgram;
import java.util.Random;
/**
*
* @author
*/
public class ArrayLoopingExercise {
public static void arrayTesting(){
int [] intArray1 = {1, 2, 3};
int intArray2 [];
intArray2 = new int[4];
intArray2[0] = 4;
intArray2[1] = 5;
intArray2[3] = 7;
int a = intArray2[1];
int [][] iaa = {{1,2},{3, 4, 5}};
int [][] iaa2 = new int[2][3];
iaa2[0][0] = 5;
}
public static void loopConversion()
{
int a = 3, n = 6, result;
//We will use different loop to calculate result = a ^ n.
//Note that java has no exponent operator.
result = 1;
for (int i = 0; i < n; ++i)
{
result *= a;
}
System.out.println("for loop: result = " + result);
result = 1;
int j = 0;
while (j < n)
{
result *= a;
++j;
}
System.out.println("while loop: result = " + result);
result = 1;
int k = 0;
do
{
if (n == 0) break;
result *= a;
++k;
} while (k < n);
System.out.println("do/while loop: result = " + result);
}
public static void loopWithSorting()
{
int [] intArray = new int[20];
//Generate random numbers in the range [0, 99] to fill the array.
Random rand = new Random();
rand.setSeed(System.nanoTime());
for (int i = 0; i < intArray.length; ++ i)
{
intArray[i] = rand.nextInt(100);
}
//Print out the random array.
for (int i = 0; i < intArray.length; ++ i)
{
System.out.print (intArray[i] + ", ");
}
System.out.println();
//Sorting the array using bubble sort.
for (int i = 1; i < intArray.length; i++)
{
for (int j = intArray.length - 1; j >= i; j--)
{
if (intArray[j-1] > intArray[j])
{
int temp = intArray[j-1];
intArray [j-1] = intArray[j];
intArray [j] = temp;
}
}
}
//Print out the sorted array.
for (int i = 0; i < intArray.length; ++ i)
{
System.out.print (intArray[i] + ", ");
}
System.out.println();
}
public static void matrixMultiplication()
{
int [][] m1 = { {1, 2, 3},
{4, 5, 6} };
int [][] m2 = { {1, 2},
{3, 4},
{5, 6} };
int [][] mp = { {0, 0},
{0, 0} };
for (int i = 0; i < mp.length; ++i)
{
for (int j = 0; j < mp[i].length; ++j)
{
for (int k = 0; k < m1[0].length; ++k)
{
mp[i][j] += m1[i][k] * m2[k][j];
}
}
}
//Print out the matrix multiplication result.
for (int i = 0; i < mp.length; ++i)
{
for (int j = 0; j < mp[0].length; ++j)
{
System.out.print (mp[i][j] + ", ");
}
System.out.println();
}
}
}
版权所有:编程辅导网 2021 All Rights Reserved 联系方式:QQ:99515681 微信:codinghelp 电子信箱:99515681@qq.com
免责声明:本站部分内容从网络整理而来,只供参考!如有版权问题可联系本站删除。