Q:

Ruby basics – Find output programs (set 2)

0

Program 1:

def main
    num = 20;
    msg = "Hello World"
    
    printf "Num: %d\n", num;
    printf "Message: %s\n", msg;
end

main();

Program 2:

def main
    num = 20;
    msg = "Hello World"
    
    printf("%d,%s\n"), num, msg;
end

main();

Program 3:

ret = puts "Hello";

if ret == nil
    print "ABC\n";
else
    print "XYZ\n";
end

Program 4:

var1 = var2 = "hello";

print "var1: ", var1, "\n";
print "var2: ", var2, "\n";

Program 5:

var1 = "hello ";
var2 = "hi ";

var3 = var1 + var2;

print "var3: ", var3, "\n";

All Answers

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

Answer Program 1:

Output:

Num: 20
Message: Hello World

Explanation:

In the above program, we created an integer variable num and a string variable msg. Then we printed the value of variables in a formatted manner using the printf() method.

Answer Program 2:

Output:

HelloWorld.rb:5: syntax error, unexpected ',', expecting keyword_end
    printf("%d,%s\n"), num, msg;
                     ^
HelloWorld.rb:5: syntax error, unexpected ';', expecting '='
...   printf("%d,%s\n"), num, msg;
...                              ^
HelloWorld.rb:8: syntax error, unexpected end-of-input, expecting keyword_end
main();
       ^

Explanation:

The above program will generate syntax errors due to the syntax of the printf() method. The correct source code is given below:

def main
    num = 20;
    msg = "Hello World";
    
    printf("%d,%s\n", num, msg);
end

main();

Answer Program 3:

Output:

Hello
ABC

Explanation:

In the above program, we printed the "Hello" message using the puts() method. The puts() method returns nil, that's why "ABC" is also printed.

 

Answer Program 4:

Output:

var1: hello
var2: hello

Explanation:

In the above program, we created two variables var1, var2 that were initialized with "hello". Then we printed the value of both variables.

Answer Program 5:

Output:

var3: hello hi 

Explanation:

In the above program, we created two string variables var1, var2 that were initialized with "hello ", "hi ". Then we concatenated the strings using the "+" operator and assigned the result to the variable var3. After that, we printed the result.

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