Loops and Arrays
Loops and Arrays
LOOPS
•A control structure that is used to execute a
particular part of the program repeatedly if a
given condition evaluates to be true.
•Comes into three types:
• For loop
• For-each loop
• While loop
• Do-While loop
Elements required to perform counter-
controlled repetition
1. a control variable (or loop counter)
2. the initial value of the control variable
3. the increment/decrement by which the control
variable is modified each time through the loop
(also known as each iteration of the loop)
4. the loop-continuation condition that determines
if looping should continue.
PROBLEM 1:
int n1=0, n2=1 ,n3 ,i , count=10;
System.out.print(n1+" "+n2);
for(i=2;i<count;++i) {
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
PROBLEM 2
int count = 0;
do {
System.out.print (count +" ");
count++ ;
} while ( count < 6 );
PROBLEM 3
int x = 0;
while ( x < 20 )
{
System.out.print( x + " " );
x = x + 5;
}
PROBLEM 4
int x = 0;
while ( x < 20 )
{
x = x + 5;
}
System.out.print(x);
}
PROBLEM 5
• multi-dimensional array
are used to store data as a tabular form, like a table with
rows and columns.
ACCESSING THE ELEMENTS OF AN ARRAY
• To access an element, refer to the index number.
Example:
//For 1D array
String[] motors = {“Suzuki", “Yamaha", “Honda", “Kawasaki"};
System.out.println(motors[3]);
//For 2D array
int[][] numbers = {{0,2,4}, {1,3,5}};
System.out.println(numbers[1][2]);
CHANGING THE ELEMENTS OF AN ARRAY
• To change the value of a specific element, refer to the index number:
Example:
//For 1D array
String[] motors = {"Suzuki", "Yamaha", "Honda", "Kawasaki"};
motors[3] = "Duke";
for (int i = 0; i < motors.length; i++) {
String motor = motors[i];
System.out.println(motor+" ");
}
CHANGING THE ELEMENTS OF AN ARRAY
• To change the value of a specific element, refer to the index number:
Example:
//For 2D array
int[][] numbers = {{0,2,4}, {1,3,5}};
numbers [1][1] = 7;
for (int i = 0; i < numbers.length; ++i) {
for(int a = 0; a < numbers[i].length; ++a) {
System.out.println(numbers[i][a]);
}
}
DETERMINING THE LENGTH OF AN ARRAY
• To access an element, refer to the index number.
Example:
//For 1D Array
String[] motors = {“Suzuki", “Yamaha", “Honda", “Kawasaki"};
System.out.println(motors.length);
//For 2D Array
int[][] numbers = {{0,2,4}, {1,3,5}};
System.out.println(numbers.length);
DETERMINING THE LENGTH OF AN ARRAY
• To access an element, refer to the index number.
Example:
//For 1D Array
String[] motors = {“Suzuki", “Yamaha", “Honda", “Kawasaki"};
System.out.println(motors.length);
//For 2D Array
int[][] numbers = {{0,2,4}, {1,3,5}};
System.out.println(numbers.length);
PROBLEM 1
int array_length = 0;
double[][] av = { {1.2, 9.0}, {9.2, 0.5, 0.0},
{7.3, 7.9, 1.2, 3.9} } ;
array_length = av.length;
System.out.println(array_length);
PROBLEM 2
int[][] a = { {10, 11, 31, 14}, {24, 32, 29, 20, 72 },
{33, 82} } ;