0% found this document useful (0 votes)
17 views

Oop Lab Assignment 1

Uploaded by

samra.15986.ac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Oop Lab Assignment 1

Uploaded by

samra.15986.ac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 121

SAMRA SULEMAN (15986) :-

ASSIGNMENT NO: 01 :-
OBJECT ORIENTED
PROGRAMMING (LAB) :-
BACHELORS IN
COMPUTER SCIENCE (BSCS) :-
CHAPTER # 03
PROGRAM : (AverageScore.java)
import javax.swing.JOptionPane; // Needed for JOptionPane

/**

This program demonstrates the if statement.

*/

public class AverageScore

public static void main(String[] args)

double score1; // To hold score #1

double score2; // To hold score #2

double score3; // To hold score #3

double average; // To hold the average score

String input; // To hold the user's input

// Get the first test score.

input = JOptionPane.showInputDialog("Enter score #1:");

score1 = Double.parseDouble(input);

// Get the second score.

input = JOptionPane.showInputDialog("Enter score #2:");

score2 = Double.parseDouble(input);

// Get the third test score.

input = JOptionPane.showInputDialog("Enter score #3:");

score3 = Double.parseDouble(input);

// Calculate the average score.

average = (score1 + score2 + score3) / 3.0;

// Display the average score.


JOptionPane.showMessageDialog(null,

"The average is " + average)

// If the score was greater than 95, let the user know

// that's a great score.

if (average > 95)

Chapter 3 Decision Structures

JOptionPane.showMessageDialog(null,

"That's a great score!");

System.exit(0);

}
PROGRAM 3.1:-(LoanQualifier.java)
import javax.swing.JOptionPane; // Needed for JOptionPane class

/**

This program demonstrates a nested if statement.

*/

public class LoanQualifier

public static void main(String[] args)

double salary; // Annual salary

double yearsOnJob; // Years at current job

String input; // To hold string input

// Get the user's annual salary.

input = JOptionPane.showInputDialog("Enter your " +

"annual salary.");

salary = Double.parseDouble(input);

// Get the number of years at the current job.

input = JOptionPane.showInputDialog("Enter the number of " +

"years at your current job.");

yearsOnJob = Double.parseDouble(input);

// Determine whether the user qualifies for the loan.

if (salary >= 30000)

if (yearsOnJob >= 2)

JOptionPane.showMessageDialog(null, "You qualify " +

"for the loan.");

}
else

JOptionPane.showMessageDialog(null, "You must have " +

"been on your current job for at least " +

"two years to qualify.");

else

JOptionPane.showMessageDialog(null, "You must earn " +

"at least $30,000 per year to qualify.");

System.exit(0);

PROGRAM 3.2 (NestedDecision.java)


import javax.swing.JOptionPane; // Needed for JOptionPane

/**

This program asks the user to enter a numeric test

score and displays a letter grade for the score. The

program uses nested decision structures

to determine the grade.

*/

public class NestedDecision

public static void main(String[] args)

int testScore; // Numeric test score


String input; // To hold the user's input

// Get the numeric test score.

input = JOptionPane.showInputDialog("Enter your numeric " +

"test score and I will tell you the grade: ");

testScore = Integer.parseInt(input);

// Display the grade.

if (testScore < 60)

JOptionPane.showMessageDialog(null, "Your grade is F.");

else

if (testScore < 70)

JOptionPane.showMessageDialog(null, "Your grade is D.");

else

if (testScore < 80)

JOptionPane.showMessageDialog(null, "Your grade is C.");

else

if (testScore < 90)

JOptionPane.showMessageDialog(null, "Your grade is B.");

else
{

JOptionPane.showMessageDialog(null, "Your grade is A.");

System.exit(0);

}
PROGRAM 3.3(TestResults.Java)
import javax.swing.JOptionPane; // Needed for JOptionPane

public class TestResults

public static void main(String[] args)

14 int testScore; // Numeric test score

String input; // To hold the user's input

// Get the numeric test score.

input = JOptionPane.showInputDialog("Enter your numeric " +

"test score and I will tell you the grade: ");

testScore = Integer.parseInt(input);

// Display the grade.

if (testScore < 60)

JOptionPane.showMessageDialog(null, "Your grade is F.");

else if (testScore < 70)

JOptionPane.showMessageDialog(null, "Your grade is D.");

else if (testScore < 80)

JOptionPane.showMessageDialog(null, "Your grade is C.");

else if (testScore < 90)

JOptionPane.showMessageDialog(null, "Your grade is B.");

else

JOptionPane.showMessageDialog(null, "Your grade is A.");

System.exit(0);

}
}

PROGRAM 3.4(TrailingElse.java)
import javax.swing.JOptionPane; // Needed for JOptionPane

/**

This program asks the user to enter a numeric test

score and displays a letter grade for the score. The

program displays an error message if an invalid

numeric score is entered.

*/

The if-else-if Statement 135

public class TrailingElse

public static void main(String[] args)

int testScore; // Numeric test score

String input; // To hold the user's input

// Get the numeric test score.

input = JOptionPane.showInputDialog("Enter your numeric " +

"test score and I will tell you the grade: ");

testScore = Integer.parseInt(input);

// Display the grade.

if (testScore < 60)

JOptionPane.showMessageDialog(null, "Your grade is F.");

else if (testScore < 70)

JOptionPane.showMessageDialog(null, "Your grade is D.");

else if (testScore < 80)

JOptionPane.showMessageDialog(null, "Your grade is C.");

else if (testScore < 90)


JOptionPane.showMessageDialog(null, "Your grade is B.");

else if (testScore <= 100)

JOptionPane.showMessageDialog(null, "Your grade is A.");

else

JOptionPane.showMessageDialog(null, "Invalid score.");

System.exit(0);

PROGRAM 3.5(LogicalAnd.java)
import javax.swing.JOptionPane; // Needed for JOptionPane class

/**

This program demonstrates the logical && operator.

*/

public class LogicalAnd

public static void main(String[] args)

double salary; // Annual salary

double yearsOnJob; // Years at current job

String input; // To hold string input

// Get the user's annual salary.

input = JOptionPane.showInputDialog("Enter your " +

"annual salary.");

salary = Double.parseDouble(input);

// Get the number of years at the current job.

input = JOptionPane.showInputDialog("Enter the number of " +

"years at your current job.");


yearsOnJob = Double.parseDouble(input);

// Determine whether the user qualifies for the loan.

if (salary >= 30000 && yearsOnJob >= 2)

JOptionPane.showMessageDialog(null, "You qualify " +

"for the loan.");

else

JOptionPane.showMessageDialog(null, "You do not " +

"qualify for the loan.");

System.exit(0);

PROGRAM 3.6(LOGICAL.OPERATOR)
import javax.swing.JOptionPane; // Needed for JOptionPane class

/**

This program demonstrates the logical || operator.

*/

public class LogicalOr

public static void main(String[] args)

double salary; // Annual salary

double yearsOnJob; // Years at current job

String input; // To hold string input


// Get the user's annual salary.

input = JOptionPane.showInputDialog("Enter your " +

"annual salary.");

salary = Double.parseDouble(input);

/ Get the number of years at the current job.

input = JOptionPane.showInputDialog("Enter the number of " +

"years at your current job.");

yearsOnJob = Double.parseDouble(input);

// Determine whether the user qualifies for loan.

if (salary >= 30000 || yearsOnJob >= 2)

JOptionPane.showMessageDialog(null, "You qualify " +

"for the loan.");

else

JOptionPane.showMessageDialog(null, "You do not " +

"qualify for the loan.");

System.exit(0);

PROGRAM 3.7 (CurrencyFormat3.java):-


import javax.swing.JOptionPane;

/**

This program demonstrates how to use the String.format

method to format a number as currency.

*/
public class CurrencyFormat

public static void main(String[] args)

double monthlyPay = 5000.0;

double annualPay = monthlyPay * 12;

JOptionPane.showMessageDialog(null,

String.format("Your annual pay is $%,.2f", annualPay));

PROGRAM 3.8(CurrencyFormat2.java)
import javax.swing.JOptionPane;

/**

This program demonstrates how to use the String.format

method to format a number as currency.

*/

public class CurrencyFormat2

public static void main(String[] args)

double monthlyPay = 5000.0;

double annualPay = monthlyPay * 12;

String output = String.format("Your annual pay is $%,.2f", annualPay);

JOptionPane.showMessageDialog(null, output);

PROGRAM 3.9 (LeftJustified.java):-


/**
This program displays a variety of

numbers left-justified in columns.

*/

public class LeftJustified

public static void main(String[] args)

// Declare a variety of int variables.

int num1 = 123;

int num2 = 12;

int num3 = 45678;

int num4 = 456;

int num5 = 1234567;

int num6 = 1234;

// Display each variable left-justified

// in a field of 8 spaces.

System.out.printf("%-8d%-8d\n", num1, num2);

System.out.printf("%-8d%-8d\n", num3, num4);

System.out.printf("%-8d%-8d\n", num5, num6);

PROGRAM 3.10(LeadingZeros.java)
/**

This program displays numbers padded with leading zeros.

*/

public class LeadingZeros

{
public static void main(String[] args)

// Declare a variety of double variables.

double number1 = 1.234;

double number2 = 12.345;

double number3 = 123.456;

// Display each variable with leading

// zeros, in a field of 9 spaces, rounded

// to 2 decimal places.

System.out.printf("%09.2f\n", number1);

System.out.printf("%09.2f\n", number2);

System.out.printf("%09.2f\n", number3);

PROGRAM 3.11(CurrencyFormat.java)
/**

This program demonstrates how to use the System.out.printf

method to format a number as currency.

*/

public class CurrencyFormat

public static void main(String[] args)

double monthlyPay = 5000.0;

double annualPay = monthlyPay * 12;

System.out.printf("Your annual pay is $%,.2f\n", annualPay);


}

PROGRAM 3.12(Columns.java)
/**

This program displays a variety of

floating-point numbers in a column

with their decimal points aligned.

*/

public static void main(String[] args)

// Declare a variety of double variables.

double num1 = 127.899;

double num2 = 3465.148;

double num3 = 3.776;

double num4 = 264.821;

double num5 = 88.081;

double num6 = 1799.999;

// Display each variable in a field of

// 8 spaces with 2 decimal places.

System.out.printf("%8.2f\n", num1);

System.out.printf("%8.2f\n", num2);

System.out.printf("%8.2f\n", num3);

System.out.printf("%8.2f\n", num4);

System.out.printf("%8.2f\n", num5);

System.out.printf("%8.2f\n", num6);

}
}

PROGRAM 3.13(StringCompare.java)
/**

This program correctly compares two String objects using

the equals method

*/

public class StringCompare

public static void main(String[] args)

String name1 = "Mark",

name2 = "Mark",

name3 = "Mary";

// Compare "Mark" and "Mark"

if (name1.equals(name2))

System.out.println(name1 + " and " + name2 +

" are the same.");

else

System.out.println(name1 + " and " + name2 +

" are NOT the same.");

// Compare "Mark" and "Mary"

if (name1.equals(name3))
{

System.out.println(name1 + " and " + name3 +

" are the same.");

else

System.out.println(name1 + " and " + name3 +

" are NOT the same.");

}
(StringCompareTo.java)

/**

This program compares two String objects using

3 the compareTo method.

*/

public class StringCompareTo

public static void main(String[] args)

String name1 = "Mary",

name2 = "Mark";

// Compare "Mary" and "Mark"

if (name1.compareTo(name2) < 0)

System.out.println(name1 + " is less than " + name2);

else if (name1.compareTo(name2) == 0)

System.out.println(name1 + " is equal to " + name2);

}
else if (name1.compareTo(name2) > 0)

System.out.println(name1 + " is greater than " + name2);

PROGRAM 3.14(VariableScope.java)

import javax.swing.JOptionPane; // Needed for JOptionPane

/**

This program demonstrates how variables may be declared

in various locations throughout a program.

*/

public class VariableScope

public static void main(String[] args)

// Get the user's first name.

String firstName;

firstName = JOptionPane.showInputDialog("Enter your " +

"first name.");

// Get the user's last name.

String lastName;

lastName = JOptionPane.showInputDialog("Enter your " +

"last name.");

JOptionPane.showMessageDialog(null, "Hello, " + firstName +


" " + lastName);

System.exit(0);

PROGRAM 3.15(Columns.java)
/**

This program displays a variety of

floating-point numbers in a column

with their decimal points aligned.

*/

public class Columns

public static void main(String[] args)

// Declare a variety of double variables.

double num1 = 127.899;

double num2 = 3465.148;

double num3 = 3.776;

double num4 = 264.821;

double num5 = 88.081;

double num6 = 1799.999;

// Display each variable in a field of

// 8 spaces with 2 decimal places.

System.out.printf("%8.2f\n", num1);

System.out.printf("%8.2f\n", num2);

System.out.printf("%8.2f\n", num3);

System.out.printf("%8.2f\n", num4);
System.out.printf("%8.2f\n", num5);

System.out.printf("%8.2f\n", num6);

}
CHAPTER # 04
PROGRAM :4..1 (IncrementDecrement.java)
/**

This program demonstrates the ++ and -- operators.

*/

public class IncrementDecrement

public static void main(String[] args)

int number = 4; // number starts out with 4

// Display the value in number.

System.out.println("number is " + number);

System.out.println("I will increment number.");

// Increment number.

number++;

// Display the value in number again.

System.out.println("Now, number is " + number);

System.out.println("I will decrement number.");

// Decrement number.

number--;

// Display the value in number once more.

System.out.println("Now, number is " + number);

PROGRAM 4.2:- (Prefix.java)


/**

This program demonstrates the ++ and -- operators

in prefix mode.

*/

public class Prefix

public static void main(String[] args)

int number = 4; // number starts out with 4

// Display the value in number.

System.out.println("number is " + number);

System.out.println("I will increment number.");

// Increment number.

++number;

// Display the value in number again.

System.out.println("Now, number is " + number);

System.out.println("I will decrement number.");

// Decrement number.

--number;

// Display the value in number once again.

System.out.println("Now, number is " + number);

PROGRAM4-3 (WhileLoop.java)
/**

This program demonstrates the while loop.


*/

public class WhileLoop

public static void main(String[] args)

int number = 1;

while (number <= 5)

System.out.println("Hello");

number++;

System.out.println("That's all!");

}
PROGRAM 4.4 (TestAverage1.java)
import java.util.Scanner; // Needed for the Scanner class

/**

This program demonstrates a user controlled loop.

*/

public class TestAverage1

public static void main(String[] args)

int score1, score2, score3; // Three test scores

double average; // Average test score

char repeat; // To hold 'y' or 'n'

String input; // To hold input

System.out.println("This program calculates the " +

"average of three test scores.");

// Create a Scanner object for keyboard input.

Scanner keyboard = new Scanner(System.in);

// Get as many sets of test scores as the user wants.

do

// Get the first test score in this set.

System.out.print("Enter score #1: ");

score1 = keyboard.nextInt();

// Get the second test score in this set.

System.out.print("Enter score #2: ");

score2 = keyboard.nextInt();

boolean
// Get the third test score in this set.

System.out.print("Enter score #3: ");

score3 = keyboard.nextInt();

// Consume the remaining newline.

keyboard.nextLine();

// Calculate and print the average test score.

average = (score1 + score2 + score3) / 3.0;

System.out.println("The average is " + average);

System.out.println(); // Prints a blank line

// Does the user want to average another set?

System.out.println("Would you like to average " +

"another set of test scores?");

System.out.print("Enter Y for yes or N for no: ");

input = keyboard.nextLine(); // Read a line.

repeat = input.charAt(0); // Get the first char.

} while (repeat == 'Y' || repeat == 'y');

PROGRAM 4.5(Square .java)


/**

2 This program demonstrates the for loop.

3 */

5 public class Squares

6{

7 public static void main(String[] args)

8{
9 int number; // Loop control variable

10

11 System.out.println("Number Number Squared");

12 System.out.println("------------------------");

13

14 for (number = 1; number <= 10; number++)

15 {

16 System.out.println(number + "\t\t" +

17 number * number);

18 }

19 }

20 }

PROGRAM 4.6(UserSquares.java)
1 import java.util.Scanner; // Needed for the Scanner class

3 /**

4 This program demonstrates a user controlled for loop.

5 */

7 public class UserSquares

8{

9 public static void main(String[] args)

10 {

11 int number; // Loop control variable

12 int maxValue; // Maximum value to display

13

14 System.out.println("I will display a table of " +

15 "numbers and their squares.");


16

17 // Create a Scanner object for keyboard input.

18 Scanner keyboard = new Scanner(System.in);

19

20 // Get the maximum value to display.

21 System.out.print("How high should I go? ");

22 maxValue = keyboard.nextInt();

23

24 // Display the table.

25 System.out.println("Number Number Squared");

26 System.out.println("-----------------------");

27 for (number = 1; number <= maxValue; number++)

28 {

29 System.out.println(number + "\t\t" +

30 number * number);

31 }

32 }

PROGAM 4.7 (SpeedConverter.java)


1 /**

2 This program displays a table of speeds in

3 kph converted to mph.

4 */

6 public class SpeedConverter

7{

8 public static void main(String[] args)

9{

10 // Constants
11 final int STARTING_KPH = 60; // Starting speed

12 final int MAX_KPH = 130; // Maximum speed

13 final int INCREMENT = 10; // Speed increment

14

15 // Variables

16 int kph; // To hold the speed in kph

17 double mph; // To hold the speed in mph

18

19 // Display the table headings.

20 System.out.println("KPH\t\tMPH");

21 System.out.println("-------------------");

22

23 // Display the speeds.

24 for (kph = STARTING_KPH; kph <= MAX_KPH; kph += INCREMENT)

25 {

26 // Calculate the mph.

27 mph = kph * 0.6214;

28

29 // Display the speeds in kph and mph.

30 System.out.printf("%d\t\t%.1f\n", kph, mph);

31 }

32 }

33 }

PROGRAM 4.8(TotalSales.java)
1 import javax.swing.JOptionPane;

3 /**

4 This program calculates a running total.


5 */

7 public class TotalSales

8{

9 public static void main(String[] args)

218 Chapter 4 Loops and Files

10 {

11 int days; // The number of days

12 double sales; // A day's sales figure

13 double totalSales; // Accumulator

14 String input; // To hold the user's input

15

16 // Get the number of days.

17 input = JOptionPane.showInputDialog("For how many days " +

18 "do you have sales figures?");

19 days = Integer.parseInt(input);

20

21 // Set the accumulator to 0.

22 totalSales = 0.0;

23

24 // Get the sales figures and calculate a running total.

25 for (int count = 1; count <= days; count++)

26 {

27 input = JOptionPane.showInputDialog("Enter the sales " +

28 "for day " + count + ": ");

29 sales = Double.parseDouble(input);

30 totalSales += sales; // Add sales to totalSales.

31 }

32
33 // Display the total sales.

34 JOptionPane.showMessageDialog(null,

35 String.format("The total sales are $%,.2f", totalSales));

36

37 System.exit(0);

38 }

39 }

Program 4.9(SoccerPoints.java)
1 import java.util.Scanner; // Needed for the Scanner class

3 /**

4 This program calculates the total number of points a

5 soccer team has earned over a series of games. The user

6 enters a series of point values, then -1 when finished.

7 */

9 public class SoccerPoints

220 Chapter 4 Loops and Files

10 {

11 public static void main(String[] args)

12 {

13 int points; // Game points

14 int totalPoints = 0; // Accumulator initialized to 0

15

16 // Create a Scanner object for keyboard input.

17 Scanner keyboard = new Scanner(System.in);

18

19 // Display general instructions.


20 System.out.println("Enter the number of points your team");

21 System.out.println("has earned for each game this season.");

22 System.out.println("Enter -1 when finished.");

23 System.out.println();

24

25 // Get the first number of points.

26 System.out.print("Enter game points or -1 to end: ");

27 points = keyboard.nextInt();

28

29 // Accumulate the points until -1 is entered.

30 while (points != -1)

31 {

32 // Add points to totalPoints.

33 totalPoints += points;

34

35 // Get the next number of points.

36 System.out.print("Enter game points or -1 to end: ");

37 points = keyboard.nextInt();

38 }

39

40 // Display the total number of points.

41 System.out.println("The total points are " +

42 totalPoints);

(PROGRAM 4.10Clock.java)
1 /**

2 This program uses nested loops to simulate a clock.

3 */

4
5 public class Clock

6{

7 public static void main(String[] args)

8{

9 // Simulate the clock.

10 for (int hours = 1; hours <= 12; hours++)

11 {

12 for (int minutes = 0; minutes <= 59; minutes++)

13 {

14 for (int seconds = 0; seconds <= 59; seconds++)

222 Chapter 4 Loops and Files

15 {

16 System.out.printf("%02d:%02d:%02d\n", hours, minutes, seconds);

17 }

18 }

19 }

20 }

21 }

PROGRAM 4.11(RectangularPattern.java)
1 import java.util.Scanner;

3 /**

4 This program displays a rectangular pattern

5 of asterisks.

6 */

8 public class RectangularPattern

9{
10 public static void main(String[] args)

11 {

12 int rows, cols;

13

14 // Create a Scanner object for keyboard input.

15 Scanner keyboard = new Scanner(System.in);

16

17 // Get the number of rows and columns.

18 System.out.print("How many rows? ");

19 rows = keyboard.nextInt();

20 System.out.print("How many columns? ");

21 cols = keyboard.nextInt();

22

23 for (int r = 0; r < rows; r++)

24 {

25 for (int c = 0; c < cols; c++)

4.7 Nested Loops 225

226 Chapter 4 Loops and Files

26 {

27 System.out.print("*");

28 }

29 System.out.println();

30 }

31 }

32 }

PROGRAM 4.12(FileWriteDemo.java)
1 import java.util.Scanner; // Needed for Scanner class

2 import java.io.*; // Needed for File I/O classes


3

4 /**

5 This program writes data to a file.

6 */

8 public class FileWriteDemo

9{

10 public static void main(String[] args) throws IOException

11 {

12 String filename; // File name

13 String friendName; // Friend's name

14 int numFriends; // Number of friends

15

16 // Create a Scanner object for keyboard input.

17 Scanner keyboard = new Scanner(System.in);

18

19 // Get the number of friends.

20 System.out.print("How many friends do you have? ");

21 numFriends = keyboard.nextInt();

22

23 // Consume the remaining newline character.

24 keyboard.nextLine();

25

26 // Get the filename.

27 System.out.print("Enter the filename: ");

28 filename = keyboard.nextLine();

29

30 // Open the file.

31 PrintWriter outputFile = new PrintWriter(filename);


32

33 // Get data and write it to the file.

34 for (int i = 1; i <= numFriends; i++)

35 {

36 // Get the name of a friend.

37 System.out.print("Enter the name of friend " +

38 "number " + i + ": ");

39 friendName = keyboard.nextLine();

40

41 // Write the name to the file.

42 outputFile.println(friendName);

43 }

44

45 // Close the file.

46 outputFile.close();

47 System.out.println("Data written to the file.");

48 }

49 }

Program 4.13 (RollDice.java)


1 import java.util.Scanner;

2 import java.util.Random;

4 /**

5 This program simulates the rolling of dice.

6 */

8 public class RollDice

9{
10 public static void main(String[] args)

11 {

12 String again = "y"; // To control the loop

13 int die1; // To hold the value of die #1

14 int die2; // to hold the value of die #2

15

16 // Create a Scanner object to read keyboard input.

17 Scanner keyboard = new Scanner(System.in);

18

19 // Create a Random object to generate random numbers.

20 Random rand = new Random();

21

22 // Simulate rolling the dice.

23 while (again.equalsIgnoreCase("y"))

24 {

25 System.out.println("Rolling the dice ...");

26 die1 = rand.nextInt(6) + 1;

27 die2 = rand.nextInt(6) + 1;

28 System.out.println("Their values are:");

29 System.out.println(die1 + " " + die2);

30

31 System.out.print("Roll them again (y = yes)? ");

32 again = keyboard.nextLine();

33 }

34 }

35 }

PROGRAM 4.15(CoinToss.java)
1 import java.util.Random;
2

3 /**

4 This program simulates 10 tosses of a coin.

5 */

7 public class CoinToss

8{

9 public static void main(String[] args)

10 {

11 // Create a Random object to generate random numbers.

12 Random rand = new Random();

13

14 // Simulate the coin tosses.

15 for (int count = 0; count < 10; count++)

16 {

17 if (rand.nextInt(2) == 0)

18 System.out.println("Tails");

19 else

20 System.out.println("Heads");

21 }

22 }

23 }
PATTERN PRINTING PROGRAMS :-
1. Right Triangle Star Pattern

public class RightTrianglePattern


{
public static void main(String args[])
{
int i, j, row=6;
for(i=0; i<row; i++)
{
for(j=0; j<=i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
2. Left Triangle Star Pattern

public class LeftTrianglePattern


{
public static void main(String args[])
{
int i, j, row = 6;
for (i=0; i<row; i++)
{
for (j=2*(row-i); j>=0; j--)
{
System.out.print(" ");
}
for (j=0; j<=i; j++ )
{
System.out.print("* ");
}
System.out.println();
}
}
}

Output:

3. Pyramid Star Pattern

public class PyramidPattern


{
public static void main(String args[])
{
int i, j, row = 6;
for (i=0; i<row; i++)
{
for (j=row-i; j>1; j--)
{
System.out.print(" ");
}
for (j=0; j<=i; j++ )
{
System.out.print("* ");
}
System.out.println();
}
}
}

Output:

How to Print Pattern in Java


4. Diamond Shape Pattern

import java.util.Scanner;
public class DiamondPattern
{
public static void main(String args[])
{
int row, i, j, space = 1;
System.out.print("Enter the number of rows you want
to print: ");
Scanner sc = new Scanner(System.in);
row = sc.nextInt();
space = row - 1;
for (j = 1; j<= row; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
space = 1;
for (j = 1; j<= row - 1; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space++;
for (i = 1; i<= 2 * (row - j) - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
}
Output:

How to Print Pattern in Java


5. Downward Triangle Star Pattern

public class DownwardTrianglePattern


{
public static void main(String[] args)
{
int rows=7;
for (int i= rows-1; i>=0 ; i--)
{
for (int j=0; j<=i; j++)
{
System.out.print("*" + " ");
}
System.out.println();
}
}
}
Output:

You might also like