For+Loop+Practice


 * For Loop Practice Problems**

What is returned for each of these codes when the call //loop// (10) is made?
 * PART1**

How many times did the loop execute?

1) public int loop (int x) { int sum = 0; for ( int i = 0; i < x; i++) { sum += i; } return sum; }

2) public int loop (int x) { int sum = 0; for ( int i = 3; i < x ; i ++) { sum += i ; } return sum; }

3) public int loop (int x) { int sum = 0; for ( int = 0; i < x; i ++) { sum += i; i++; } return sum; }

4) public int loop (int x) { int sum = 0; for (int i = 20; i > x; i --) { sum -= i; } return sum; }

5) public int loop (int x) { int i = 0, sum = 1; for (i <x; i += 2) { sum *= i; } return sum; }

6) public int loop (int x) { int sum = 0; for (int i = 0; i < x; i++) { if ( i % 2 == 0) sum ++; else sum *= 2; } return sum; }

7) public int loop (int x) { int sum = 0; for ( int i = 1; i < x; i ++) { if (i % 5 ==0) return sum; else sum +=i; } return sum; }

8) public int loop (int x) { int sum = 0; for (int i = 0; i < x; i++) { x --; sum += i + x; } return sum; }

--
 * PART 2**

1.) What is the output of the following program fragment? code for ( int j = 10; j >  5; j-- ) {  System.out.print( j + " " ); } System.out.println;

code

2.)What is the output of the following program fragment? code for ( int j = 0; j <  5; j++ ) {  System.out.print( j + " " ); } System.out.println;

code

3.) What is the output? code for ( int j = 5; j > -5; j-- )  System.out.print( j + " " );

System.out.println;

code

4.) Fill the blank so that the following fragment prints out 0.2, 0.4, 0.6, 0.8, 1.0,

code for ( int j = 2; j <= 10; j+=2  ) System.out.print( __________ + ", " );

System.out.println;

code

5.) What is the output? code for ( int count=0; count <= 9; ++count )  System.out.print( count + " " );

System.out.println;

code

6.) What is the output? code for ( int count = 0; count <= 20;  count+=2 )  System.out.print( count + " " );

System.out.println;

code

7.) Fill in the blank so that the following adds up the **odd** numbers from 1 to 99 code int sum = 0; for ( int num = 1; num <=99; __________ ) sum += num;

System.out.println( sum );

code

ANSWERS