Q:

Ruby conditional statements – Find output programs (set 2)

0

Program 1:

num = 8.54;

if (num % 2 == 0)
  println("Even Number");
else
  println("Odd Number");
end

Program 2:

num = print("hello\n");

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

Program 3:

num = 10;

if true
  printf("Hello: %d", num);
else
  printf("Hi: %d", num);
end

Program 4:

num = 10;

if (num == 10) == true
  printf "Hello";
else
  printf "Hi";
end

Program 5:

num1 = 10;
num2 = 20;
num3 = 30;
large = 0;

if num1 > num2 && num1 > num3
  large = num1;
else if num2 > num1 && num2 > num3
  large = num2;
else
  large = num3;
end

print("Largest value is : ", large);

All Answers

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

Answer Program  1:

Output:

HelloWorld.rb:6:in `<main>': undefined method `println' for 
main:Object (NoMethodError)
Did you mean?  print
               printf

Explanation:

The above program will generate a syntax error because println is not an inbuilt function in ruby.

Answer Program 2:

Output:

HelloWorld.rb:3:in `<main>': undefined method `%' for nil:NilClass (NoMethodError)

Explanation:

The above program will generate a runtime error because the print() function returns "nil" and we cannot use the "%" operator with the "nil" value.

Answer Program 3:

Output:

Hello: 10

Explanation:

There is no error in this program. We can use true or false as the conditional expression.

Answer Program 4:

Output:

Hello

Explanation:

In the above program, we created a variable num initialized with 10. Then we checked the value of num in the if condition and printed the appropriate message.

Answer Program 5:

Output:

HelloWorld.rb:14: syntax error, unexpected end-of-input, expecting keyword_end
...("Largest value is : ", large);
...                               ^

Explanation:

The above program will generate a syntax error because we cannot use else if in the ruby program. The correct program is given below,

num1 = 10;
num2 = 20;
num3 = 30;
large = 0;

if num1 > num2 && num1 > num3
  large = num1;
elsif num2 > num1 && num2 > num3
  large = num2;
else
  large = num3;
end

print("Largest value is : ", large);

# Output: Largest value is : 30

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