ADVERTISEMENT
ADVERTISEMENT

Ruby program to insert an item into the array without using library function

Ruby Example: Write a program to insert an item into the array without using library function.
Submitted by Nidhi, on January 22, 2022

Problem Solution:

In this program, we will create an array of integers and then we will read an item from the user and insert the input item into the array.

Program/Source Code:

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

# Ruby program to insert an item into array without 
# using library function

arr = [10,20,30,40,50];

print "Enter item: ";
item = gets.chomp.to_i;  

i = 0;
while (i < 6) 
    if (arr[i] >= item) 
      j = 4;
      while (j >= i) 
        arr[j + 1] = arr[j];
        j = j - 1;
      end
      arr[i] = item;
      break;
    end
    i = i + 1;
end
      
print "Array elements after insertion: \n";
i=0;
while(i<6)
    print arr[i]," ";
    i=i+1;
end

Output:

Enter item: 35

Array elements after deletion: 
10 20 30 35 40 50

Explanation:

In the above program, we created an array of integer elements. Then we read an item from the user. After that, we inserted the input item into the array without using the library function. After that, we printed the updated array.

Ruby Arrays Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.