Java Program to Create and Count Nodes in a Singly Linked List

In this article, we are going to see how we can create and count nodes in a singly linked list by using Java programming language.

Java Program to Create and Count Nodes in a Singly Linked List

Each element in linkedlist is called as a node. Here we need to first create nodes and then count the number of nodes. To create nodes we need to add elements into the linkedlist and to count the number of nodes traverse the linkedlist starting from head to tail and keep a track on its total count.

Let’s see the program to understand it clealry.

Approach:

  • Create a linked list by creating an object of that class.
  • Call the user defined count( ) method to print the number of nodes in the list.
  • Add some elements to the list.
  • Print the linked list by calling user defined method show() in which we will traverse each element one by one and print it.
  • Call the count( ) method again and see the number of nodes after the elements have been added.

Program:

import java.util.*;
// Main class
public class Main
{
    // Class Node that defines the two linked list variables
    class Node
    {
        int data;
        Node nextNode;
        // constructor to create a node
        public Node(int data) 
        {    
            this.data = data;    
            this.nextNode = null;    
        }    
    }

    // Setting the head and end of the node as NULL  
    public Node head = null;    
    public Node tail = null;  
    // Count the number of nodes in the linked list
    public void count()
    {
        int c = 0;
        Node curr = head;
        //continue it till curr refers to null
        while(curr!=null)
        {
            c++;
            curr = curr.nextNode;
        }
        System.out.println("The number of nodes in the linked list currently are: "+c);
    }
    
    // method to add a node to the linked list
    public void add(int data)
    {
        Node newNode = new Node(data);
        // Checks if there was any previous node
        //if the list is empty then head and tail both will point to newNode
        if(head==null)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail.nextNode = newNode;
            tail = newNode;
        }
    }
    
    // Method to display all the nodes of the linked list
    public void show()
    {
        Node curr = head;
        // If the head is pointing to no node then the linked list is empty
        if(head==null)
            System.out.println("Linked List is empty");
        else
        {
            System.out.println("The nodes are:");
            while(curr!=null)
            {
                System.out.print(curr.data+",");
                curr = curr.nextNode;
            }
            System.out.println();
        }
    }
    
    //Driver method
    public static void main(String[] args) 
    {
        // create an object of the main class
        Main ll = new Main();
        // Counts the number of nodes in the linked list
        ll.count();
        // add elements to the linked list
        ll.add(10);
        ll.add(20);
        ll.add(30);
        ll.add(40);
        ll.add(50);
        // display the nodes
        ll.show();
        // Again counts the number of nodes
        ll.count();
    }
}
Output:

The number of nodes in the linked list currently are: 0
The nodes are:
10,20,30,40,50,
The number of nodes in the linked list currently are: 5

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Java Program to Create a Singly Linked List, Add Elements to it and Display

In this article, we are going to see how we can create a singly linked list, add elements to it and display it by using Java programming language.

Java Program to Create a Singly Linked List, Add Elements to it and Display

Singly LinkedList:

In Java singly linkedlist is a data structure which contains a series of elements. Each element in the list contains the element and a pointer to next element which is called a node. Where the first node is termed as head and last node is termed as tail of the linkedlist. Last node pointer contains null.

Approach:

  • Create a class node to contain the data and the link of all nodes.
  • Initialize the head and tail as null as the list is initially empty.
  • Create a method add() which adds the element to the node.
  • Create another method that checks if the linked list is empty else displays the elements.
  • Now from the main function create an object of the class which creates an empty linked list for us.
  • Now add some elements to the list using the add() method.
  • Finally, call the show() method to display the linked list.

Program:

import java.util.*;
// Main class
public class Main
{
    // Class Node that defines the two linked list variables
    class Node
    {
        int data;
        Node nextNode;
        // constructor to create a node
        public Node(int data) 
        {    
            this.data = data;    
            this.nextNode = null;    
        }    
    }

    // Setting the head and tail of the linkedlist as NULL  
    public Node head = null;    
    public Node tail = null;  
    // method to add a node to the linked list
    public void add(int data)
    {
        Node newNode = new Node(data);
        // Checks if there was any previous node
        //if the list is empty then head and tail both will point to newNode
        if(head==null)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail.nextNode = newNode;
            tail = newNode;
        }
        System.out.println(data+" has been added to the list.");
    }
    
    // Method to display all the nodes of the linked list
    public void show()
    {
        //Node curr refers to the head element
        Node curr = head;
        System.out.println("Trying to display the linked list...");
        // If the head is pointing to no node then the linked list is empty
        if(head==null)
            System.out.println("Linked List is empty");
        else
        {
            System.out.println("The nodes are:");
            while(curr!=null)
            {
                System.out.print(curr.data+",");
                curr = curr.nextNode;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) 
    {
        // create an object of the main class
        Main ll = new Main();
        // add elements to the linked list
        ll.add(10);
        ll.add(20);
        ll.add(30);
        ll.add(40);
        ll.add(50);
        // display the nodes
        ll.show();
    }
}
Output:

10 has been added to the list.
20 has been added to the list.
30 has been added to the list.
40 has been added to the list.
50 has been added to the list.
Trying to display the linked list...
The nodes are:
10,20,30,40,50,

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Java Program to Convert Year to Decade and Decade to Year

In this article we will see how to convert Year to Decade and Decade to Year by using Java programming language.

Java Program to Convert Year to Decade and Decade to Year

Before jumping into the program let’s know the relationship between Year and Decade and how we can convert Year to Decade and vice versa.

Year is a time period of 12 months starting from January to December. While Decade is a period of 10 years.

1 Year = 0.1 Decade
1 Decade = 10 Year

Formula to convert Decade to Year.

Year = Decade * 10

Formula to convert Year to Decade.

Decade = Year / 10

Let’s see different ways to convert Year to Decade and Decade to Year.

Method-1: Java Program to Convert Year to Decade and Decade to Year By Using Static Input Value

Approach:

  • Declare Year and Decade value.
  • Then convert Year to Decade and Decade to Year by using the formula.
  • Print result.

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //initialized value of year
        double year = 1;
        //initialized value of decade
        double decade = 1;
        
        //converting year to decade
        double d = year / 10;
        //converting decade to year
        double y = decade * 10;
        //printing result
        System.out.println("Value of "+year+" year in decade: "+ d);   
        System.out.println("Value of "+decade+" decade in year: "+ y);   
   }
}
Output:

Value of 1.0 year in decade: 0.1
Value of 1.0 decade in year: 10.0

Method-2: Java Program to Convert Year to Decade and Decade to Year By Using User Input Value

Approach:

  • Take user input of Year and Decade value.
  • Then convert Year to Decade and Decade to Year by using the formula.
  • Print result.

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //Taking the value input of double variable year
        System.out.println("Enter value of year: ");  
        double year = sc.nextDouble();
        //Taking the value input of double variable decade
        System.out.println("Enter value of decade: ");  
        double decade = sc.nextDouble();
        
        //converting year to decade
        double d = year / 10;
        //converting decade to year
        double y = decade * 10;
        //printing result
        System.out.println("Value of "+year+" year in decade: "+ d);   
        System.out.println("Value of "+decade+" decade in year: "+ y);   
   }
}
Output:

Enter value of year: 
12
Enter value of decade: 
2
Value of 12.0 year in decade: 1.2
Value of 2.0 decade in year: 20.0

Method-3: Java Program to Convert Year to Decade and Decade to Year By Using User Defined Method

Approach:

  • Take user input of Year and Decade value.
  • Call a user defined method by passing Year and Decade value as parameter.
  • Inside method convert Year to Decade and Decade to Year by using the formula.
  • Print result.

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //Taking the value input of double variable year
        System.out.println("Enter value of year: ");  
        double year = sc.nextDouble();
        //Taking the value input of double variable decade
        System.out.println("Enter value of decade: ");  
        double decade = sc.nextDouble();
         //calling user defined method convert()
        convert(year, decade);
   }
   
   //convert() method to convert year to decade and vice versa
   public static void convert(double year, double decade)
   {
        //converting year to decade
        double d = year / 10;
        //converting decade to year
        double y = decade * 10;
        //printing result
        System.out.println("Value of "+year+" year in decade: "+ d);   
        System.out.println("Value of "+decade+" decade in year: "+ y);   
   }
}
Output:
Enter value of year: 
24
Enter value of decade: 
1.5
Value of 24.0 year in decade: 2.4
Value of 1.5 decade in year: 15.0

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Related Java Programs:

Java Program to Convert Year to Century and Century to Year

In this article we will see how to convert Year to Century and Century to Year by using Java programming language.

Java Program to Convert Year to Century and Century to Year

Before jumping into the program let’s know the relationship between Year and Century and how we can convert Year to Century and vice versa.

Year is a time period of 12 months starting from January to December. While 100 years called as a Century.

1 Year = 0.01 Century
1 Century = 100 Year

Formula to convert Century to Year.

Year = Century * 100

Formula to convert Year to Century.

Century = Year / 100

Let’s see different ways to convert Year to Century and Century to Year.

Method-1: Java Program to Convert Year to Century and Century to Year By Using Static Input Value

Approach:

  • Declare Year and Century value.
  • Then convert Year to Century and Century to Year by using the formula.
  • Print result.

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //initialized value of year
        double year = 1;
        //initialized value of century
        double century = 1;
        
        //converting year to century
        double c = year / 100;
        //converting decade to year
        double y = century * 100;
        //printing result
        System.out.println("Value of "+year+" year in century: "+ c);   
        System.out.println("Value of "+century+" century in year: "+ y);   
   }
}
Output:

Value of 1.0 year in century: 0.01
Value of 1.0 century in year: 100.0

Method-2: Java Program to Convert Year to Century and Century to Year By Using User Input Value

Approach:

  • Take user input of Year and Century value.
  • Then convert Year to Century and Century to Year by using the formula.
  • Print result.

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //Taking the value input of double variable year
        System.out.println("Enter value of year: ");  
        double year = sc.nextDouble();
        //Taking the value input of double variable century
        System.out.println("Enter value of century: ");  
        double century = sc.nextDouble();
        
        //converting year to century
        double c = year / 100;
        //converting decade to year
        double y = century * 100;
        //printing result
        System.out.println("Value of "+year+" year in century: "+ c);   
        System.out.println("Value of "+century+" century in year: "+ y);   
   }
}
Output:

Enter value of year: 
200
Enter value of century: 
3
Value of 200.0 year in century: 2.0
Value of 3.0 century in year: 300.0

Method-3: Java Program to Convert Year to Century and Century to Year By Using User Defined Method

Approach:

  • Take user input of Year and Century value.
  • Call a user defined method by passing Year and Century value as parameter.
  • Inside method convert Year to Century and Century to Year by using the formula.
  • Print result.

Program:

import java.util.*;
public class Main 
{
   public static void main(String args[])
   {
        //Scanner class object created
        Scanner sc=new Scanner(System.in);
        //Taking the value input of double variable year
        System.out.println("Enter value of year: ");  
        double year = sc.nextDouble();
        //Taking the value input of double variable century
        System.out.println("Enter value of century: ");  
        double century = sc.nextDouble();
         //calling user defined method convert()
        convert(year, century);
   }
   
   //convert() method to convert year to century and vice versa
   public static void convert(double year, double century)
   {
        //converting year to century
        double c = year / 100;
        //converting decade to year
        double y = century * 100;
        //printing result
        System.out.println("Value of "+year+" year in century: "+ c);   
        System.out.println("Value of "+century+" century in year: "+ y);   
   }
}
Output:

Enter value of year: 
167
Enter value of century: 
4
Value of 167.0 year in century: 1.67
Value of 4.0 century in year: 400.0

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Related Java Programs:

Operators in Java

Operators in Java (Prerequisite Topic)

In this article we will discuss about what is operators and what are the operators supported in Java. So, let’s start exploring the concept.

Multiple types operators are supported by Java programming language. Operators are one of integral part of programming language. As with out operator we can not perform any single logical or arithmetical calculation/operation.

Operators:

Operators are the symbols which instructs the compiler to perform some calculation/operation. An operator perform it’s operations on operands, in more simple words on variables and values.

Types of Operators:

Java supports many types of operators and based on their unique functionality they are categorized into a set of operators. They are

  1. Arithmetic Operator
  2. Assignment Operator
  3. Unary Operator
  4. Relational Operator
  5. Logical Operator
  6. Bitwise Operator
  7. Shift Operator
  8. Ternary Operator
  9. Instanceof Operator

Let’s know little more about these operators.

1. Arithmetic Operator:

Arithmetic operators are used arithmetic/mathematical operations.

  • + : Addition operator : Adds two values.
  • - : Subtraction operator : Subtracts two values.
  • * : Multiplication operator : Multiply two values.
  • / : Division operator : Divides one value by another.
  • % : Modulo operator/Reminder operator : Returns reminder of division.

2. Assignment Operator:

Assignment operator is used to simply assign a value to a variable.

  • = : Assignment operator : Assign value to a variable.

3. Unary Operator:

Unary operator uses only one operand to perform operation. That’s why name is like Unary(means one) operator.

  • var++ and var-- : Postfix operator : First Assign value then increment or decrement.
  • ++var and --var : Prefix operator : First Increment or decrement  value hen assign.

4. Relational Operator:

Relational operators are used to check relation between two operands (variables/values). It is also called as comparison operator.

  • == : Equal to operator : Checks two values are equal.
  • != : Not equal to : Checks two values are not equal.
  • > : Greater than operator : Checks left operand is greater than right operand.
  • < : Less than operator : Checks left operand is less than right operand.
  • >= : Greater than equal to operator : Checks left operand is greater than or equal to right operand.
  • <= : Less than equal to operator : Checks left operand is less than or equal to right operand.

5. Logical Operator:

Logical operators are used to determine logic between two variables/values. Checks condition is true or false.

  • && : Logical AND : Returns True if both side conditions are true else false.
  • || : Logical OR : Returns True if any one side condition is true else false.
  • ! : Logical NOT : Returns the reversed result means true becomes false and vice versa.

6. Bitwise Operator:

Bitwise operators are used to perform any operation on individual bits.

  • ~ : Bitwise Complement : Returns 1 value as 0 and 0 value as 1.
  • | :  Bitwise OR : Returns 1 if at least one operand is 1
  • & : Bitwise AND : Returns 1 if both the value are 1
  • ^ : Bitwise XOR : Returns 1 if one of operand is 1, If both operands are 0 or 1 then returns 0

7. Shift Operator:

Shift operators are used to shift bits to left or right of a number.

  • << : Left Shift : Shifts all bits to left based on specified bits.
  • >> : Signed Right Shift : Shifts all bits to right based on specified bits.
  • >>> : Unsigned Right Shift : Performs right shift and vacant left bits filled with 0 instead of sign bit.

8. Ternary Operator:

It is another version of if-else operation. It is also called as conditional operator. As it uses 3 operands so it is called as ternary operator.

  • ? : Ternary Operator : (expression) ? value if true : value if false If condition is true then statement after ? and if condition is false then executes statement after :

9. Instanceof Operator:

Instanceof operator compares an object to a specified type.

  • instanceof : Checks if a reference variable is of a given type of object reference.

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs:

Java Program to Print Zig Zag Number Pattern

Print Zig Zag Number Pattern

In the previous article, we have discussed Java Program to Print Window Number Pattern

In this article we will see how to print zig-zag number pattern.

Example:

Enter the no of characters in a line = 3
Enter the no of zig zag line = 4

1  
  2   
    3 
    1 
  2 
3 
1     
  2   
    3 
    1 
  2 
3 
1     
  2   
    3 
    1 
  2 
3 
1     
  2   
    3 
    1 
  2 
3

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Approach :

  1. Print one backward slash first then one forward slash and continue.
  2. Enter total characters in a row and store it an integer variable say row.
  3. Enter total no. of zig zag lines and store in an integer variable say count.
  4. To print Backward slash :
  5. Take first for loop to print all the rows.
  6. Take a inner loop to print the column values.
  7. Then go on printing the numbers according to the iteration.
  8. To print forward slash :
  9. Take first for loop to print all the rows.
  10. Take inner loop to print the column values.
  11. Then go on printing the numbers according to the iteration.

Java Code to Print Zig Zag Number Pattern

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
        // Take user input for no fo rows 
        System.out.print("Enter the no of characters in a line = ");
        Scanner sc= new Scanner(System.in);
        int r,c,row;
        //starting ASCII value taken 64
        int ascii=64;
        // store the input value in row
        row=sc.nextInt();
         System.out.print("Enter the no of zig zag line = ");
        int count=sc.nextInt();
        
        for (int i=1;i<=count;i++)
        {
        
            // backward
           for(r=1; r<=row; r++)
           {   
               // inner loop to print number
              for(c=1; c<=row; c++)
              {   
                  // if row and column have same value print symbol     
                 if(r==c)      
                    System.out.print(r+" ");      
                 else          
                    System.out.print("  ");      
              } 
              System.out.println("");
           } 
           
           // forward
            for(r=1;r<=row;r++)
            {
              // loop for printing number 
              for(c=1;c<=row;c++)
              {
                    // if c<= row+1-r print symbol else spaces
                    if(c <= (row+1-r))
                    {
                       if( c == (row+1-r) )
                          System.out.print(r+" ");
                       else
                          System.out.print("  ");
                    }
              }
              System.out.println("");
           }
        }
    }
}

 

Output:

Enter the no of characters in a line = 3
Enter the no of zig zag line = 4

1     
  2   
    3 
    1 
  2 
3 
1     
  2   
    3 
    1 
  2 
3 
1     
  2   
    3 
    1 
  2 
3 
1     
  2   
    3 
    1 
  2 
3

Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.

Related Java Number Pattern Programs:

JSP Implicit Objects: 9 Implicit Objects in JSP | Complete Tutorial on Implicit Objects in JSP

JSP Implicit Objects- 9 Implicit Objects in JSP

In the earlier tutorial, we have seen JSP Scripting Elements with Example. In this tutorial, we will discuss & understand JSP implicit objects with examples. Primarily, there are 9 implicit objects in JSP. Let’s learn all these implicit objects in detail. But first, learn what is JSP implicit objects?

This Implicit Objects in JSP Tutorial Contains: 

What are JSP Implicit Objects?

Implicit objects are the set of predefined objects readily available for use. These objects are created by the JSP container, while a JSP page translates into Servlet. Implicit Objects are being created inside the service() method so we can use implicit objects directly within scriptlets without initializing and declaring them. Total 9 Implicit objects are available in JSP.

Implicit Objects and their corresponding classes

out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
page java.lang.Object
pageContext javax.servlet.jsp.PageContext
config javax.servlet.ServletConfig

Also Check: 

How many Implicit Objects are available in JSP?

There are 9 types of implicit objects available in the container:

  1. out
  2. request
  3. response
  4. page
  5. pageContext
  6. config
  7. application
  8. session
  9. exception

Let’s check out one by one from the below sections:

1. out:

It is used for writing content to the client browser. It is an object of the JSP Writer. In servlet you need to write PrintWriter out = response.getWriter() for writing content to the browser, but in JSP you don’t need to write this.

2. request:

It is an object of HttpServletRequest.This object is created for each JSP request by the web container. The main purpose of this object is to get the data on a JSP page which is entered by the user. This object is used to get request information like a parameter, header information, content type, server name, etc.

JSP Implicit Objects 9 Implicit Objects in JSP 1

JSP Implicit Objects 9 Implicit Objects in JSP 2

JSP Implicit Objects 9 Implicit Objects in JSP 3

JSP Implicit Objects 9 Implicit Objects in JSP 4

3. response:

It is an object of HttpServletResponse. This object will be created by the container for each request. We can use the response object to set content type, adding cookies, and redirecting the request to another resource.

JSP Implicit Objects 9 Implicit Objects in JSP 5

JSP Implicit Objects 9 Implicit Objects in JSP 6

4. page:

JSP page implicit object is an object of java.lang.Object class. This object represents the current JSP page. It is rarely used. It provides a reference to the generated servlet class.

5. pageContext:

JSP pageContext object is an object of javax.servlet.jsp.PageContext class. It is used for accessing page, application, request and session scope.

JSP Implicit Objects 9 Implicit Objects in JSP 7

JSP Implicit Objects 9 Implicit Objects in JSP 8

JSP Implicit Objects 9 Implicit Objects in JSP 9

6. config:

JSP config implicit object is an instance of java.servlet.ServletConfig class. This object is created by the container for each JSP page. It is used to get the initialization parameter in the deployment descriptor(web.xml) file.

JSP Implicit Objects 9 Implicit Objects in JSP 10

JSP Implicit Objects 9 Implicit Objects in JSP 11

JSP Implicit Objects 9 Implicit Objects in JSP 12

7. application:

JSP application implicit object is an instance of java.servlet.servletContext class.It is used to obtain the context information and attributes in JSP.The servlet context obtained from the servlet configuration object by using the getServletConfig().getServletContext() method.One application object is created by the container for one JSP application when the application is deployed.

JSP Implicit Objects 9 Implicit Objects in JSP 13

JSP Implicit Objects 9 Implicit Objects in JSP 14

JSP Implicit Objects 9 Implicit Objects in JSP 15

8. session:

JSP Session implicit object is an instance of javax.servlet.http.HttpSession class.The session object is created for the requesting clients(if any). This variable is only valid for HTTP-based protocol. we can use this object to get, set, and remove an attribute from the session scope.

JSP Implicit Objects 9 Implicit Objects in JSP 16

JSP Implicit Objects 9 Implicit Objects in JSP 17

JSP Implicit Objects 9 Implicit Objects in JSP 18

JSP Implicit Objects 9 Implicit Objects in JSP 19

JSP Implicit Objects 9 Implicit Objects in JSP 20

JSP Implicit Objects 9 Implicit Objects in JSP 21

9. Exception:

JSP exception implicit object is an instance of java.lang.Throwable class. It is used for exception handling in JSP. It can be only used for the JSP error page.

Java Program to Print Reverse Floyd’s Triangle Number Pattern

Print Reverse Floyd’s Triangle Number Pattern

In the previous article, we have discussed Java Program to Print Floyd’s Triangle Number Pattern

In this article we are going to see how to print reverse Floyd’s triangle number pattern.

Example-1

When rows value = 5

15 14 13 12 11
10 9 8 7
6 5 4
3 2
1
Example-2:

When rows value=7

28 27 26 25 24 23 22
21 20 19 18 17 16
15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

Now, let’s see the actual program to print it.

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Approach:

  • Enter total number of rows and store it in an integer variable rows
  • Take one outer for loop to iterate the rows.
  • Take one inner for loop to iterate the columns.
  • After each iteration print a new line.

Java Code to Print Reverse Floyd’s Triangle Number Pattern

import java.util.Scanner;
class pattern
{
//Function to set the counter
static int calculateCounter(int rows)
{
    int sum = 0;
    for (int i = 1; i <= rows; i++)
    {
        sum += i;
    }
    return sum;
}

//Main Function
public static void main(String[] args)
{
    //Create a new Scanner object
    Scanner scan = new Scanner(System.in);

    //Taking total number of rows as input from user
    System.out.print("Rows : ");
    int rows= scan.nextInt();

   //Row and column are the iterators and counter to print
    int numberOfRows, numberOfColumns, counter = calculateCounter(rows);

    //Outer loop to iterate the rows
    //Iterates from 1 to the number of rows entered by the user(backwards)
    for (numberOfRows = rows; numberOfRows >= 1; --numberOfRows)
    {
        //Inner loop to print number
        //Iterator iterates from 1 to the numberOfRows 
        for (numberOfColumns = 1; numberOfColumns <= numberOfRows; ++numberOfColumns)
        {
            System.out.print(counter-- + " ");
        }
    //Prints a newline
    System.out.println();
    }
}
}

Output:

Rows : 5

15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

C Code to Print Reverse Floyd’s Triangle Number Pattern

#include <stdio.h>
//Function to set the counter
int calculateCounter(int rows)
{
   int sum = 0;
   for (int i = 1; i <= rows; i++)
   {
      sum += i;
   }
   return sum;
}

//Main Function
int main()
{
   //Taking total number of rows as input from user
   printf("Rows : ");
   int rows;
   scanf("%d", &rows);

   //Row and column are the iterators and counter to print
   int numberOfRows, numberOfColumns, counter = calculateCounter(rows);

   //Outer loop to iterate the rows
   //Iterates from 1 to the number of rows entered by the user(backwards)
   for (numberOfRows = rows; numberOfRows >= 1; --numberOfRows)
   {
      //Inner loop to print number
      //Iterator iterates from 1 to the numberOfRows
      for (numberOfColumns = 1; numberOfColumns <= numberOfRows; ++numberOfColumns)
      {
         printf("%d ", counter--);
      }
      //Prints a newline
      printf("\n");
   }
   return 0;
}
Output:

Rows : 5

15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

C++ Code to Print Reverse Floyd’s Triangle Number Pattern

#include <iostream>
using namespace std;

//Function to set the counter
int calculateCounter(int rows)
{
    int sum = 0;
    for (int i = 1; i <= rows; i++)
    {
        sum += i;
    }
    return sum;
}

//Main Function
int main(int argc, char const *argv[])
{
    //Taking total number of rows as input from user
    cout << "Rows : ";
    int rows;
    cin >> rows;

    //Row and column are the iterators and counter to print
    int numberOfRows, numberOfColumns, counter = calculateCounter(rows);

    //Outer loop to iterate the rows
    //Iterates from 1 to the number of rows entered by the user(backwards)
    for (numberOfRows = rows; numberOfRows >= 1; --numberOfRows)
    {
        //Inner loop to print number
        //Iterator iterates from 1 to the numberOfRows
        for (numberOfColumns = 1; numberOfColumns <= numberOfRows; ++numberOfColumns)
        {
            cout << counter-- << " ";
        }
        //Prints a newline
        cout << endl;
    }
    return 0;
}

Output:

Rows : 5

15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.

Related Java Number Pattern Programs:

Java Program to Print Square with Repeated Number Decreasing Order Pattern

Printing Square with Repeated Number Decreasing Order Pattern

In the previous article, we have discussed Java Program to Print Square with Repeated Number Increasing Order Pattern

In this program we are going to see how to print the square with repeated number decreasing number pattern.

Example-1

When size value=5 and 
starting number = 9

9 9 9 9 9
8 8 8 8 8
7 7 7 7 7
6 6 6 6 6
5 5 5 5 5
Example-2:

When size value=3 and 
starting number = 5

5 5 5
4 4 4
3 3 3

Now, let’s see the actual program to print it.

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Approach:

  • Enter total size and number store them in integer variables size & num .
  • Take one outer for loop to iterate the rows.
  • Take one inner for loop to iterate the columns and print the column values.
  • After each iteration print a new line.

Java Code to Print Square with Repeated Number Decreasing Order Pattern

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
     // Create a new Scanner object
    Scanner scan = new Scanner(System.in);

    //Taking size as input from user
    System.out.print("Size of square : ");
    int size = scan.nextInt();

    //Taking number as input from user
    System.out.print("Number to print from : ");
    int num = scan.nextInt();

    //Row and column are the iterators
    int numberOfRows, numberOfColumns;

    //Outer loop to iterate the rows
    //Iterates from 1 to the size entered by the user
    for (numberOfRows = 1; numberOfRows <= size; numberOfRows++)
    {
        //Inner loop to iterate the columns
        //Iterates from 0 to one less than the size entered by the user
        for (numberOfColumns = 0; numberOfColumns < size; numberOfColumns++)
        {
            //Prints the num value
            System.out.print(num+" ");
        }
        //Incrementing the num variable after each row
        num--;
        //Prints a newline
        System.out.println();
    }
}
}

Output:

Size of square : 5
Number to print from : 9

9 9 9 9 9 
8 8 8 8 8 
7 7 7 7 7 
6 6 6 6 6 
5 5 5 5 5

C Code to Print Square with Repeated Number Decreasing Order Pattern

#include <stdio.h>

int main()
{
    //Taking size as input from user
    printf("Size of square : ");
    int size;
    scanf("%d", &size);

    //Taking number as input from user
    printf("Number to print from : ");
    int num;
    scanf("%d", &num);

    //Row and column are the iterators
    int numberOfRows, numberOfColumns;

    //Outer loop to iterate the rows
    //Iterates from 1 to the size entered by the user
    for (numberOfRows = 1; numberOfRows <= size; numberOfRows++)
    {
        //Inner loop to iterate the columns
        //Iterates from 0 to one less than the size entered by the user
        for (numberOfColumns = 0; numberOfColumns < size; numberOfColumns++)
        {
            //Prints the num value
            printf("%d ", num);
        }
        //Incrementing the num variable after each row
        num--;
        //Prints a newline
        printf("\n");
    }
    return 0;
}

Output:

Size of square : 5
Number to print from : 9

9 9 9 9 9 
8 8 8 8 8 
7 7 7 7 7 
6 6 6 6 6 
5 5 5 5 5

C++ Code to Print Square with Repeated Number Decreasing Order Pattern

#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
    //Taking size as input from user
    printf("Size of square : ");
    int size;
    cin >> size;

    //Taking number as input from user
    printf("Number to print from : ");
    int num;
    cin >> num;

    //Row and column are the iterators
    int numberOfRows, numberOfColumns;

    //Outer loop to iterate the rows
    //Iterates from 1 to the size entered by the user
    for (numberOfRows = 1; numberOfRows <= size; numberOfRows++)
    {
        //Inner loop to iterate the columns
        //Iterates from 0 to one less than the size entered by the user
        for (numberOfColumns = 0; numberOfColumns < size; numberOfColumns++)
        {
            //Prints the num value
            cout << num << " ";
        }
        //Incrementing the num variable after each row
        num--;
        //Prints a newline
        cout << endl;
    }
    return 0;
}

Output:

Size of square : 5
Number to print from : 9

9 9 9 9 9 
8 8 8 8 8 
7 7 7 7 7 
6 6 6 6 6 
5 5 5 5 5

Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.

Related Java Number Pattern Programs:

Java Program to Print the Series 2 1 1/2 1/4 1/8 …N

Java Program to Print the Series 2 1 1/2 1/4 1/8 … N

In the previous article we have discussed about Java Program to Print the Series 2 3 12 37 86 166 … N

In this article we are going to see how to print the series 6 11 21 36 56 …N by using Java programming language.

Java Program to Print the Series 2 1 1/2 1/4 1/8 …N

On observing the pattern carefully, we can see first number starts from 2

Then the next number follows a logic i.e previous element/2

2
2/2 = 1
1/2
1/2 / 2 = 1/4
1/4 / 2 = 1/8 and so on.

Example:

2 1 1/2 1/4 1/8 1/16 …… N

Let’s see different ways to print the series 6 11 21 36 56 …N

Method-1: Java Program to Print the Series 2 1 1/2 1/4 1/8 …N By Using For Loop

Approach:

  • Create Scanner class object.
  • Declare an integer variable say ‘n’ which holds the number of terms in the series.
  • Prompt the user to enter a number as value of n.
  • Let declare an double variable say ‘result’ and initialize it to 2
  • Use a for loop from i=1 to i<=n-1 where the loop is incremented by 1
  • Inside the for loop we will find the value of result=result/2
  • Print the result in the series.

Program:

import java.util.*;
public class Main
{
    public static void main(String [] args)
    {
        //creating object of Scanner class 
        Scanner s = new Scanner(System.in);
        //Taking input of number of elements in the series
        System.out.println("Enter the number of terms ");
        int n = s.nextInt();
        double result = 2;
        System.out.print(result);
        //for loop to print the series
        for (int i = 1; i <= n-1; i++) 
        {
            result /=2; 
            System.out.print(" "+result);
        } 
    }
}
Output:

Enter the number of terms
5
2.0 1.0 0.5 0.25 0.125

Method-2: Java Program to Print the Series 2 1 1/2 1/4 1/8 …N By Using While Loop

Approach:

  • Create Scanner class object.
  • Declare an integer variable say ‘n’ which holds the number of terms in the series.
  • Prompt the user to enter a number as value of n.
  • Let declare an double variable say ‘result’ and initialize it to 2
  • Declare and initialize an integer variable i=1
  • Continue a while loop till i<=n-1, where i is incremented by 1.
  • Inside the while loop we will find the value of result=result/2
  • Print the result in the series.

Program:

import java.util.*;
public class Main
{
    public static void main(String [] args)
    {
        //creating object of Scanner class 
        Scanner s = new Scanner(System.in);
        //Taking input of number of elements in the series
        System.out.println("Enter the number of terms ");
        int n = s.nextInt();
        double result=2;
        System.out.print(result);
        int i=1;
        while(i<=n-1)
        {
            result /=2; 
            System.out.print("  "+result);
            i++;
        }      
    }
}
Output:

Enter the number of terms
7
2.0 1.0 0.5 0.25 0.125 0.0625 0.03125

Method-3: Java Program to Print the Series 2 1 1/2 1/4 1/8 …N By Using User Defined Method

Approach:

  • Create Scanner class object.
  • Declare an integer variable say ‘n’ which holds the number of terms in the series.
  • Prompt the user to enter a number as value of n.
  • Then call a user defined method printSeries() by passing n as parameter.
  • Inside method declare an double variable say ‘result’ and initialize it to 2
  • Use a for loop from i=1 to i<=n-1 where the loop is incremented by 1
  • Inside the for loop we will find the value of result=result/2
  • Print the result in the series.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // creating object of scanner class 
        Scanner s = new Scanner(System.in);
        //Taking input of number of elements in the series
        System.out.println("Enter the number of terms ");
        int n = s.nextInt();
        // calling printSeries method to print the series
        printSeries(n);
    }
    
    //printSeries metthod to print the series
    public static void printSeries(int n)
    {
        double result = 2;
        System.out.print(result);
        //for loop to print the series
        for (int i = 1; i <=n-1; i++) 
        {
            result /=2; 
            System.out.print(" "+result);
        } 
    }
}
Output:

Enter the number of terms
9
2.0 1.0 0.5 0.25 0.125 0.0625 0.03125 0.015625 0.0078125

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Related Java Programs: