×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby nested until loop with examples

By IncludeHelp Last updated : November 16, 2024

Nested Until Loop

Alike for, while, and do...while, until loop can also be nested for meeting the specific purpose. In this type of nesting, two until loops work in the combination such that at first, the outer loop is triggered which results in the execution of the inner loop. The outer Until loop is not invoked as long as the inner loop does not comes out to be true. It is a kind of Entry control loop which simply means that first the outer Boolean expression is processed; if it is false then the pointer will move to the inner loop to check inner condition. The whole execution will take place in the same manner.

Syntax

until conditional [do]
  until conditional [do]
    # code to be executed
  end     
  # code to be executed
end

Example 1: Find the Sum of Digits for Numbers Between Two Limits Using Nested until Loops

=begin
  Ruby program to find the sum of digits for numbers lying
  between two limits using nested until loop
=end

puts "Enter the upper limit:"
ul = gets.chomp.to_i
puts "Enter the lower limit:"
ll = gets.chomp.to_i

if ul < ll
  puts "Invalid input! Upper limit must be>= the lower limit."
else
  until ul < ll
    num = ul
    temp = ul
    sum = 0

    # Inner until loop to calculate the sum of digits
    until num == 0
      rem = num % 10
      num = num / 10
      sum += rem
    end

    # Output the sum of digits for the current number
    puts "The sum of digits of #{temp} is #{sum}"
    ul -= 1  # Decrement the upper limit to process the next number
  end
end

Output

Enter the Upper limit
1000
Enter the Lower limit
980
The sum of 1000 is 1
The sum of 999 is 27
The sum of 998 is 26
The sum of 997 is 25
The sum of 996 is 24
The sum of 995 is 23
The sum of 994 is 22
The sum of 993 is 21
The sum of 992 is 20
The sum of 991 is 19
The sum of 990 is 18
The sum of 989 is 26
The sum of 988 is 25
The sum of 987 is 24
The sum of 986 is 23
The sum of 985 is 22
The sum of 984 is 21
The sum of 983 is 20
The sum of 982 is 19
The sum of 981 is 18

Example 2: Print a Given Pattern Using until Loops

=begin
  Ruby program to print the given pattern using until loop.
=end

num = 0

# Outer until loop for rows
until num == 6
  j = 0
  
  # Inner until loop for printing numbers in each row
  until j == num
    print j
    j += 1
  end
  
  # Move to the next line after each row
  puts ""
  
  num += 1  # Increment for the next row
end

Output

  0
  01
  012
  0123
  01234

Comments and Discussions!

Load comments ↻





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