Home
Preface
Chapter Selection
Programming Examples
Homework Problems
Homework Solutions MEA's
Search Useful Links

Programming Examples

Chapter 4 Programming Examples

Counting from 0 to n Using While Loop
1	#! /usr/bin/ruby
2	puts "Count from 0 to ?  ==> "
3	n = gets.to_i
4	i = 0
5	while (i <= n)  
6	    puts i
7	    i = i + 1
8	end

 
 
Counting from 0 to n Using Until Loop
1	#! /usr/bin/ruby
2	puts "Count from 0 to ?  ==> "
3	n = gets.to_i
4	i = 0
5	until (i > n)  
6	    puts i
7	    i = i + 1
8	end
 
 
Counting Even Numbers from 0 to n
1	#! /usr/bin/ruby
2	puts "Count from 0 to ?  ==> "
3	n = gets.to_i
4	i = 0
5	while (i <= n)  
6	    puts i
7	    i = i + 2
8	end
 
 
Prime-Hunting
1	#! /usr/bin/ruby
2	i = 1
3	while  (i <= 100)
4	      primeFlag = true
5	      j = 2
6	      while (j <=  i / 2)
7	            # puts " i ==> "+ i.to_s + " j ==> "+ j.to_s
8	            if (i % j == 0) 
9	               primeFlag = false
10	               #  break
11	            end
12	            j = j + 1
13	         end
14	         if primeFlag == true  
15	             puts "Prime ==> " + i.to_s
16	        end
17	        i = i + 1
18	end