Monday, December 25, 2017

While (loop)

ChallengeWrite a program that computes all powers of 2 from 20 up to 220, using a WHILE loop. 

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);
   }

}


Challenge : Write a program that reads a line of input as a string and prints the string, with all vowels replaced by an underscore.





import java.util.Scanner;

class lab6_4
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);

System.out.print("Enter string: ");

String myString = in.nextLine();

String[] vowels = {"a", "u", "o", "e", "i","A","E","I","O","U"};

for(String newString : vowels)
    myString = myString.replaceAll(newString, "_");
System.out.println(myString);

   }      

}


Challenge : Write a program that reads an integer and displays, using asterisks, a hollow square. For example, if the side length is 5, the program should display 

****
*    *  
*    *
*    *
*    *
****

import java.util.Scanner;
class lab6_5
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);

System.out.print("Enter an integer: ");

int number = in.nextInt();
for(int i=0;i<number;i++)
{
System.out.print("*");

for(int j=0;j<number-1;j++)
{
if(j==number-2)

System.out.print("*");




else 
    if(i==0 || i==number-1)
    {
System.out.print("*");
    }
else
    {
    System.out.print(" ");
       } 
    }
System.out.println("");
      }
   }


}

No comments:

Post a Comment