If and else statements:
1a.)
Given the following declaration:
int temperature;
Write an if statement that prints the message "The number is valid" if the variable temperature is within the range of -50 trough 150 (both values excluded).
1b.)
Given the following declarations
int x;
int y;
Write an if statement that assigns 100 to x when y is equal to 0.
1c.)
Given the following declaration:
int grade;
Write an if statement that prints the message "The number is valid" if the variable grade is within the range of 0 trough 100 (both inclusive).
1d.)
Given the following declaration:
int year;
Write an if statement that prints the message "The year is not valid" if the variable year is outside the 20th century (1901 - 2000).
1e.)
Given the following declaration:
int hours;
Write an if statement that prints the message "The number is not valid" if the variable hours is outside the range of 0 trough 80 (0 and 80 are valid values).
1f.)
Given the following declarations:
int x;
int y;
Write an if-else statement that assigns 0 to x when y is equal to 10. Otherwise, it should assign 1 to x.
1g.)
Given the following declarations:
int hours;
boolean minimum;
Write an if statement that sets the variable hours to 10 when the boolean flag variable minimun is true.
Answers:
1a)
//&& - And - Logical operator
if(temperature>-50 && temperature<150) //-50 trough
150 (both values excluded).
{
System.out.print("The number is valid"); //using print() as a
function to print
}
1b.)
//== relational operator ,equal equal to - to compare two values
if(y==0)
{
x=100;
}
1.c)
//&& - And - Logical operator
if(grade>=0 && grade<=100) //0 & 100 (both
inclusive).
{
print("The number is valid");
}
1.d)
// ! - Not - Logical operator
if(!(year>=1901 && year<=2000))
{
print("The year is not valid");
}
1.e)
// ! - Not - Logical operator
if(!(hours>=0 && hours<=80))
{
print("The number is not valid");
}
1.f)
//== - Realational operator
if(y==10)
{
x=0;
}
else
{
x=1;
}
1.
g)
//To compare two boolean values, we need to use == relational
operator
if(minimum== true)
{
hours=10;
}
Get Answers For Free
Most questions answered within 1 hours.