Thursday, October 23, 2014


Building Java Programs A Back To Basics Approach - 3rd Edition
by Stuart Reges and Marty Stepp



Chapter 2 Exercise 6

Write nested for loops to produce the following output:

7777777
666666
55555
4444
333
22
1


/* Copyright Mihai George Forlafu @ 2014
 * Copenhagen School of Design and Technology
 * Building Java Programs A Back To Basics Approach 5th edition
 * Chapter 2 Exercise 6, page 156
 */
package ch2_ex6_v2;
public class Ch2_Ex6_v2 
{
    public static void main(String[] args) 
    {
        for (int line = 7; line>=1; line--)
        {
            for (int num = 1; num<=line; num++)
            {
                System.out.print(line);
            }
            System.out.println("");
        }
    } 
}

Another solution for this exercise is the one below. This solution fulfill all the requirements of the exercise but as you can see it takes to many lines of code. It is a very rudimentary way of solving the exercise. 

package ch2_ex6;
public class Ch2_Ex6 {

    public static void main(String[] args) {
        for (int line = 1; line <= 1; line = line + 1) {
            for (int seven = 1; seven <= 7; seven = seven + 1) {
                System.out.print("7");
            }
            System.out.println("");
        }

        for (int line = 1; line <= 1; line = line + 1) {
            for (int six = 1; six <= 6; six = six + 1) {
                System.out.print("6");
            }
            System.out.println("");
        }

        for (int line = 1; line <= 1; line = line + 1) {
            for (int five = 1; five <= 5; five = five + 1) {
                System.out.print("5");
            }
            System.out.println("");
        }

        for (int line = 1; line <= 1; line = line + 1) {
            for (int four = 1; four <= 4; four = four + 1) {
                System.out.print("4");
            }
            System.out.println("");
        }
        for (int line = 1; line <= 1; line = line + 1) {
            for (int three = 1; three <= 3; three = three + 1) {
                System.out.print("3");
            }
            System.out.println("");
        }
        for (int line = 1; line <= 1; line = line + 1) {
            for (int two = 1; two <= 2; two = two + 1) {
                System.out.print("2");
            }
            System.out.println("");
        }

        for (int line = 1; line <= 1; line = line + 1) {
            for (int one = 1; one <= 1; one = one + 1) {
                System.out.print("1");
            }
            System.out.println("");
        }
    }

}

0 comments:

Post a Comment