Q:

Ruby program to reverse an array without using library function

belongs to collection: Ruby Arrays Programs

0

In this program, we will create an array of integer elements. Then we will reverse the array elements and assign them to another array.

All Answers

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

Program/Source Code:

The source code to reverse an array without using the library function is given below. The given program is compiled and executed successfully.

# Ruby program to reverse an array without 
# using library function

arr = [12,45,23,39,38];
RevArray = Array.new(arr.size());
count1 = 0;
count2 = arr.size()-1;

while(count1<arr.size())
    RevArray[count1]=arr[count2];
    
    count1=count1 + 1;
    count2=count2 - 1;
end

print "Array:\n";
count1=0;
while(count1<arr.size)
    print arr[count1]," ";
    count1=count1 + 1;
end

print "\nReversed Array:\n";
count1=0;
while(count1<RevArray.size)
    print RevArray[count1]," ";
    count1=count1 + 1;
end

Output:

Array:
12 45 23 39 38 
Reversed Array:
38 39 23 45 12 

Explanation:

In the above program, we created an array of integer elements. Then we reversed the array elements and assigned them to the RevArray. After that, we printed the original and reversed the array.

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

total answers (1)

Ruby Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to find the prime numbers from the ar... >>
<< Ruby program to calculate the sum of array element...