Java Programming 1 ( Ex 2 )

Name : section#:

ID:

What is the output of the programs below :

public class Test {

public static void main(String args[]) {

int x = 10;

while( x < 20 ) {

System.out.print("value of x : " + x );

x++;

System.out.print("\n");

}

}

}

Answer:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19

public class Test {

public static void main(String args[]) {

for(int x = 4; x <= 8; x+=2) {

System.out.print(" x : " + x );

System.out.print("\n");

}

}

}

Answer:

x : 4

x : 6

x : 8

public class Test {

public static void main(String args[]){

int a , b;

a = 10;

b = (a == 1) ? 20: 30;

System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;

System.out.println( "Value of b is : " + b );

}

}

Answer:

Value of b is : 30

Value of b is : 20

public class Test {

public static void main(String args[]){

int x = 30;

if( x == 10 ){

System.out.print("Value of X is 10");

}else if( x == 20 ){

System.out.print("Value of X is 20");

}else if( x == 30 ){

System.out.print("Value of X is 30");

}else{

System.out.print("This is else statement");

}

}

}

Answer:

Value of X is 30

public class Test {

public static void main(String args[]){

//char grade = args[0].charAt(0);

char grade = 'C';

switch(grade)

{

case 'A' :

System.out.println("Excellent!");

break;

case 'B' :

case 'C' :

System.out.println("Well done");

break;

case 'D' :

System.out.println("You passed");

case 'F' :

System.out.println("Better try again");

break;

default :

System.out.println("Invalid grade");

}

System.out.println("Your grade is " + grade);

}

}

Answer:

Well done

Your grade is a C

public class Test {

public static void main(String args[]){

int x = 30;

if( x < 20 ){

System.out.print("This is if statement");

}else{

System.out.print("This is else statement");

}

}

}

Answer:

This is else statement

Write A program to find odd numbers using while loop between 1 and 20 ?

Public class number

{

Public static void main(string [] args )
{
int i=1;
while(i<=20)
{
system.out .printf("%d",i);
i=i+2
}}

Write a while loop to compute n! Hint n!=n*(n-1)

k = 1 ;

fact = 1;

while ( k < n ) {

k++;

fact *= k;

}

Write a program that prints the following output:

1

212

32123

4321234

543212345

public class triangle5 {

public static void main (String[] args) {

int i, j ;

String oneline;

for ( i = 1 ; i <= 5 ; i++) {//i shows line number

oneline = "" ;

for ( j = 1 ; j <= 5-i ; j++) //spaces

oneline += " " ;

for ( j = i ; j >= 2 ; j--) //down to 1

oneline += j ;

oneline += 1 ;

for ( j = 2 ; j <= i ; j++) //unto i

oneline += j ;

System.out.println(oneline) ;//print one line

}

}

}

TA. Mona Alhumuod