Search This Blog

Tuesday, December 14, 2010

Program to generate a triangle or an inverted triangle till n terms based upon the user's choice of triangle to be displayed - ICSE BOARD QUESTION 2009

/**
 * Write a program to generate a triangle or an inverted triangle
 * till n terms based upon the user's choice of triangle to be displayed.
 *
 * Example 1:
 * Input: Type 1 for a triangle and
 *        Type 2 for an inverted triangle
 *       
 *        1
 *        Enter the number of terms
 *        5
 *        OUTPUT:
 *        1
 *        2 2
 *        3 3 3
 *        4 4 4 4
 *        5 5 5 5 5
 *       
 */
import java.io.*;
class questionFIVE2009
{
    public static void main(String args[]) throws IOException
    {
        int i,j;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("**************MENU*************");
        System.out.println("Type 1 for a triangle and ");
        System.out.println("Type 2 for an inverted triangle");
       
        int ch=Integer.parseInt(br.readLine());
        System.out.println("Enter the number of terms");
        int terms=Integer.parseInt(br.readLine());
       
        switch(ch)
        {
            case 1:          
            for(i=1; i<=terms; i++)
            {
                for(j=1; j<=i; j++)
                {
                    System.out.print(i);
                }
                System.out.println("");
            }
            break;
    
            case 2:
            for(i=terms; i>=1; i--)
            {
                for(j=1; j<=i; j++)
                {
                    System.out.print(i);
                }
                System.out.println("");
            }
            break;
           
            default:
            System.out.println("Wrong choice");
        }
    }
}

4 comments: