## Wednesday, October 11, 2017

### for-loop

Challenge: Write a program that computes all powers of 2 from 0 up to 20 .

class lab6_1
{
public static void main(String[] args)
{
int number=2;

for(int i=0;i<21;i++)
{
System.out.println("2 to the power of " + i + " is equal to: " + (Math.pow(2,i)) );
}
}
}

Challenge: Write a program that computes the sum of all even numbers between 2 and 100 (inclusive).
class lab6_2
{
public static void main(String[] args)
{
int sum=0;
for(int i=2;i<=100;i=i+2)
{
sum=sum+i;
}
System.out.println(sum);

}

}

Challenge: Write a program that computes the sum of all odd numbers between a and b (inclusive), where a and b are inputs.
import java.util.Scanner;

class lab6_3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Please enter 2 integers: "); //prompts user for ints
int firstNumber = in.nextInt();
int secondNumber= in.nextInt();
int sum = 0;

for (int i = firstNumber; i <= secondNumber; i++)
{
if (i % 2 == 1)
sum += i;
}
System.out.println("The sum of all odd numbers between " +"\n" + firstNumber + " and "+ secondNumber + " is " + sum);
}

}