A+    A−    B  
Home
Algebra
Math Games
  • Decimals in Space
  • Integers in Space
  • Fraction Balls
  • Math Man
  • Number Balls
  • Geometry
    Interactive
    Trigonometry
    Teacher Resources
    Teaching Jobs USA
    Good Links

    Example problems for Loops in Java

    "Problematic" examples

    This page will provide different examples of loops that students might use. However, the loops by and large have a small 'issue' that is need of attention. The goal of this page is to give students working examples that they could improve by examining the loop.

    Factorial Example Code #1

    The code below will calcute the factorial of any number. The problem that you'd have to solve is the extra "*" symbol appended to the final output. The example below uses a "for" loop.
    
    	public static  void main(String[] args) {
    		double numberTofactirialize = 10;
    
    		double factorial = 0;
    		String outputFactorial = "";
    		for(int i =0;i< numberTofactirialize ; i++)
    			{
    			outputFactorial += i + "*";
    			}
    	System.out.println(outputFactorial);
    	}
    

    How to watch a loop execute at staggered intervals: use Thread.sleep()

     public static void main(String[] args) throws InterruptedException{
    	 String[]strs = {"a","b", "c", "d", "e"};
    	 	int i =0;
    	 	while(i < strs.length)
    	 		{
    	 		 Thread.sleep(1000); //will iterate once a second
    	 		System.out.println(strs[i]);
    	 		i++;
    	 		}
     }
    

    Factorial Example Code #2

    The code below will calcute the factorial of any number. The problem that you'd have to solve is the extra "*" symbol appended to the final output. The example below uses a "while" loop but has an error simliar to the first. Try to fix it
    
    	

    Factorial Example Code #1

    The code below will calcute the factorial of any number. The problem that you'd have to solve is the extra "*" symbol appended to the final output. The example below uses a "for" loop.
    
    	public static  void main(String[] args) {
    		double numberTofactirialize = 10;
    
    		double factorial = 0;
    		String outputFactorial = "";
    		for(int i =0;i< numberTofactirialize ; i++)
    			{
    			outputFactorial += i + "*";
    			}
    	System.out.println(outputFactorial);
    	}
    

    Top