For Loops While Loops AP Computer Science A

  • Slides: 7
Download presentation
For Loops, While Loops AP Computer Science A

For Loops, While Loops AP Computer Science A

For Loop Array. List<Integer> array 1; String array 2[ ]; for( int i =

For Loop Array. List<Integer> array 1; String array 2[ ]; for( int i = 0; blank ; i++ ) { // to go thru array 1 what would you put in the blank } for( int j = 0; blank; j++ ) { // to go thru array 2 what would you put in the blank }

Answer Array. List<Integer> array 1; String array 2[ ]; for( int i = 0;

Answer Array. List<Integer> array 1; String array 2[ ]; for( int i = 0; i < array 1. size( ); i++ ) { // What would you put here to get each element // of array 1? } for( int j = 0; j < array 2. length; j++ ) { // What would you put here to get each element // of array 2? }

Answer Array. List<Integer> array 1; String array 2[ ]; for( int i = 0;

Answer Array. List<Integer> array 1; String array 2[ ]; for( int i = 0; i < array 1. size( ); i++ ) { Integer temp = array 1. get( i ); } for( int j = 0; j < array 2. length; j++ ) { String temp = array 2[ j ]; } Note: you do not have to call your variable temp, but everything else should be the same.

You can do the same thing with a while loop int i = 0;

You can do the same thing with a while loop int i = 0; while( i < array 1. size( ) ) { Integer temp = array 1. get( i ); if( temp. equals( new Integer( 1 ) ) System. out. println( “Found a 1”); i++; } This is equivalent to for( int i = 0; i < array 1. size( ); i++ ) { Integer temp = array 1. get( i ); if( temp. equals( new Integer( 1 ) ) System. out. println( “Found a 1”); }

Single For Loops You typically use single for loops to search through an array

Single For Loops You typically use single for loops to search through an array or Array. List looking for a specific value. You might also use a for loop to print out all of the elements in an array or Array. List. You can adjust the values , and search or print only a portion of the array or Array. List. for( int i = 2; i < array 1. size( ); i++ ) { // do something } The above code will only traverse those elements in array 1 starting with index 2 to the end.

Double For Loops You typically use double for loops to print things such as.

Double For Loops You typically use double for loops to print things such as. * ** *** OR 1 12 123 OR 111 11 1