Q:

Ruby conditional statements – Find output programs (set 1)

0

Program 1:

var = "Hello World";

if (var == "Hello World") {
  print("Hello");
} else {
  print("Hiii");
}

Program 2

var = "Hello World";

if (var == "Hello World") {
  print("Hello");
} else {
  print("Hiii");
}
end

Program 3:

val = 1;

if (val)
  print("Hello");
else
  print("Hiii");
end

Program 4:

if (0)
  print("Hello");
else
  print("Hiii");
end

Program 5:

num = 8.54;

if (num.to_i() % 2 == 0)
  print("Even Number");
else
  print("Odd Number");
end

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

HelloWorld.rb:3: syntax error, unexpected '{', expecting keyword_then or ';' or '\n'
if (var == "Hello World") {
                          ^
HelloWorld.rb:5: syntax error, unexpected '}', expecting end-of-input
} else {
^

Explanation:

The above program will generate a syntax error due to the syntax of the if statement. The correct program is given below,

var = "Hello World";

if (var == "Hello World")
  print("Hello");
else
  print("Hiii");
end

# Output: Hello

 

Answer Program 2:

Output:

HelloWorld.rb:3: syntax error, unexpected '{', expecting keyword_then or ';' or '\n'
if (var == "Hello World") {
                          ^
HelloWorld.rb:5: syntax error, unexpected '}', expecting end-of-input
} else {
^

Explanation:

The above program will generate a syntax error because we cannot use curly braces with an if statement like this. The correct program is given below,

var = "Hello World";

if (var == "Hello World")
  print("Hello");
else
  print("Hiii");
end

# Output: Hello

Answer Program 3"

Output:

Hello

Explanation:

In the above program, we created a variable val initialized with 1. Then we used the value of variable val to check the if statement and printed the "Hello" message.

Answer Program 4:

Output:

Hello

Explanation:

In the above program, we used the if statement. if statement will be false, only when we use false into if statement.

Answer Program 5:

Output:

Even Number

Explanation:

In the above program, we created a float variable num initialized with 8.54. Then we converted the variable num from float to integer using the to_i() function and checked the condition to find out the resulting number is an Even number or Odd number.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now