Ruby program to delete an item from the array without using the library function

Ruby Example: Write a program to delete an item from the array without using the 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 to delete from the array.

Program/Source Code:

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

# Ruby program to delete an item from the array 
# without using library function

arr = [12,69,49,87,68];

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

i=0;
flag = 0;
while (i < 6) 
    if (arr[i] == item) 
        flag = 1;
        j = i;
        while (j < 5) 
            arr[j] = arr[j + 1];
            j = j + 1;
        end
        break;
    end
    i = i + 1;
end

if (flag == 1)
  printf "Item %d deleted successfully.\n", item;
else
  printf "Item %d not found.\n", item;
end

print "\nArray elements after deletion: \n";
i=0;
while(i<5)
    print arr[i]," ";
    i=i+1;
end

Output:

Enter item: 49
Item 49 deleted successfully.

Array elements after deletion: 
12 69 87 68

Explanation:

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

Ruby Arrays Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.