Java Program to Find the Sums of Primary Diagonal and Secondary Diagonal

Java Program to Find the Sums of Primary Diagonal and Secondary Diagonal

In the previous article, we have discussed Java Program to find the Difference Between Sums of Two Diagonals of a Matrix

In this article we are going to see how we can find the sums of Primary Diagonal and Secondary Diagonal of the matrix in JAVA language.

Java Program to Find the Sums of Primary Diagonal and Secondary Diagonal

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

Let’s see different ways to find sums of Primary Diagonal and Secondary Diagonal of the matrix in JAVA language.

Method-1: Java Program to Find the Sums of Primary Diagonal and Secondary Diagonal By Static Initialization of Array Elements

Approach:

  • Initialize an array of size 3×3 with values.
  • Show the array to the user.
  • Similarly use two for loops to iterate the rows and columns, then calculate the main diagonal sum.
  • Repeat the above step to calculate the counter diagonal sum.
  • Add both of them and print the output.

Program:

import java.util.Scanner;

public class Matrix
{
    public static void main(String args[])
    {
        //Scanner class to take input
        Scanner scan = new Scanner(System.in);

        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = {{19,25,32},{40,54,62},{70,20,60}}, mainSum = 0, counterSum = 0;
        int row, col;
        
        System.out.print("The array elements are : ");
        
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");

        // Loop to take the sum of main diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row==col)
                    mainSum+=arr[row][col];
                // if(row+col==2)
            }

        // Loop to take the sum of counter diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row+col==2)
                    counterSum+=arr[row][col];
            }
            
        // Printing both the diagonals sum
        System.out.println("\nThe sum of both diagonals are : "+(mainSum+counterSum));
    }
}

Output:

The array elements are :
19 25 32
40 54 62
70 20 60

The sum of both diagonals are : 289

Method-2: Java Program to Find the Sums of Primary Diagonal and Secondary Diagonal By Dynamic Initialization of Array Elements

Approach:

  • Initialize an array of size 3×3.
  • Ask the user for input of array elements.
  • Use two for loops to iterate the rows and columns to input the array elements.
  • Show the array to the user.
  • Similarly use two for loops to iterate the rows and columns, then calculate the main diagonal sum.
  • Repeat the above step to calculate the counter diagonal sum.
  • Add both of them and print the output.

Program:

import java.util.Scanner;

public class matrix
{
    public static void main(String args[])
    {
        //Scanner class to take input
        Scanner scan = new Scanner(System.in);

        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = new int[3][3];

        System.out.println("Enter the 3x3 matrix elements :");
        int row, col, mainSum = 0, counterSum = 0;
        // Loop to take user input
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                arr[row][col] = scan.nextInt();

        
        System.out.print("The array elements are : ");
        
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");

        // Loop to take the sum of main diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row==col)
                    mainSum+=arr[row][col];
                // if(row+col==2)
            }

        // Loop to take the sum of counter diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row+col==2)
                    counterSum+=arr[row][col];
            }
            
        // Printing both the diagonals sum
        System.out.print("\nThe sum of both diagonals is "+(mainSum+counterSum));
    }
}


Output:

Enter the 3x3 matrix elements : 1 2 3 4 5 6 7 8 9
The array elements are : 
1 2 3 
4 5 6 
7 8 9

The sum of both diagonals is 30

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:

Java Program to Find the Product Between Sum of Two Diagonals of a Matrix

Java Program to Find the Product Between Sum of Two Diagonals of a Matrix

In the previous article, we have discussed Java Program to Find the Sums of Primary Diagonal and Secondary Diagonal

In this article we are going to see how we can write a program to find the product of sum of primary diagonal elements and secondary diagonal elements of a matrix in JAVA language.

Java Program to Find the Product Between Sum of Two Diagonals of a Matrix

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

Let’s see different ways to find product between sum of Primary Diagonal and Secondary Diagonal of the matrix.

Method-1: Java Program to Find the Product Between Sum of Two Diagonals of a Matrix By Static Initialization of Array Elements

Approach:

  • Initialize an array of size 3×3 with values.
  • Show the array to the user.
  • Similarly use two for loops to iterate the rows and columns, then calculate the main diagonal sum.
  • Repeat the above step to calculate the counter diagonal sum.
  • Multiply both of them and print the output.

Program:

import java.util.Scanner;
public class matrix{
    public static void main(String args[])
    {
        //Scanner class to take input
        Scanner scan = new Scanner(System.in);

        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = {{19,25,32},{40,54,62},{70,20,60}}, mainSum = 0, counterSum = 0;
        int row, col;
        
        System.out.print("The array elements are : ");
        
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");

        // Loop to take the sum of main diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row==col)
                    mainSum+=arr[row][col];
                // if(row+col==2)
            }
        System.out.println("Sum of main diagonal : "+mainSum);

        // Loop to take the sum of counter diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row+col==2)
                    counterSum+=arr[row][col];
            }
        System.out.println("Sum of counter diagonal : "+counterSum);

        // Printing product betweeen both diagonals sum
        System.out.print("\nProduct between sum of both diagonal : "+(mainSum*counterSum));
    }
}
Output:

The array elements are : 
19 25 32 
40 54 62 
70 20 60 
Sum of main diagonal : 133
Sum of counter diagonal : 156

Product between sum of both diagonal : 20748

Method-2: Java Program to Find the Product Between Sum of Two Diagonals of a Matrix By Dynamic Initialization of Array Elements

Approach:

  • Declare an array of size 3×3.
  • Ask the user for input of array elemnts.
  • Use two for loops to iterate the rows and columns to input the array elements.
  • Show the array to the user.
  • Similarly use two for loops to iterate the rows and columns, then calculate the main diagonal sum.
  • Repeat the above step to calculate the counter diagonal sum.
  • Multiply both of them and print the output.

Program:

import java.util.Scanner;
public class matrix{
    public static void main(String args[])
    {
        //Scanner class to take input
        Scanner scan = new Scanner(System.in);

        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = new int[3][3];

        System.out.print("Enter the 3x3 matrix elements :");
        int row, col, mainSum = 0, counterSum = 0;
        // Loop to take user input
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                arr[row][col] = scan.nextInt();

        
        System.out.println("\nThe array elements are : ");
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");

        // Loop to take the sum of main diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row==col)
                    mainSum+=arr[row][col];
                // if(row+col==2)
            }
        System.out.println("Sum of counter diagonal : "+mainSum);
        
        // Loop to take the sum of counter diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row+col==2)
                    counterSum+=arr[row][col];
            }
        System.out.println("Sum of counter diagonal : "+counterSum);
        
        // Printing product betweeen both diagonals sum
       System.out.print("\nDifference between sum of both diagonal : "+(mainSum*counterSum));
    }
}
Output:

Enter the 3x3 matrix elements : 1 2 3 4 5 6 7 8 9
The array elements are : 
1 2 3 
4 5 6 
7 8 9 
Sum of counter diagonal : 15
Sum of counter diagonal : 15

Difference between sum of both diagonal : 225

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Related Java Programs:

Java Program to Count the Numbers of 0’s in a Binary Matrix

Java Program to Count the Numbers of 0’s in a Binary Matrix

In the previous article, we have discussed Java Program to Count the Numbers of 1’s in a Binary Matrix

In this article we are going to see how we can write a program to count number of zero’s in a binary matrix in JAVA language.

Java Program to Count the Numbers of 0’s in a Binary Matrix

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

A binary matrix is a matrix that has only 0 or 1 as its elements.

Let’s see different ways to count the Numbers of 0’s in a Binary Matrix.

Method-1: Java Program to Count the Numbers of 0’s in a Binary Matrix By Static Initialization of Array Elements

Approach:

  • Initialize and an array of size 3×3, with elements.
  • Use two for loops to iterate the rows and columns .
  • Inside the for loops count all zero’s using a counter.
  • Print the result.

Program:

public class matrix
{
    public static void main(String args[])
    {
        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = {{1,0,0},{0,0,0},{1,1,1}};
        int row, col ,count = 0;

        System.out.print("The matrix elements are : ");
        printMatrix(arr);

        // Loops to total number of zero's in a binary matrix
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(arr[row][col]==0)
                    count++;
            }   
        
        System.out.println("\nNumber of zeros' in the binary matrix are : "+count);
    }

    // Function to print the matrix
    static void printMatrix(int arr[][])
    {
        int row, col;
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");
    }
}


Output:

The matrix elements are : 
1 0 0 
0 0 0 
1 1 1

Number of zeros' in the binary matrix are : 5

Method-2: Java Program to Count the Numbers of 0’s in a Binary Matrix By Dynamic Initialization of Array Elements

Approach:

  • Declare one array of size 3×3.
  • Ask the user for input of array elements and store them in the array using two for loops.
  • Use two for loops to iterate the rows and columns .
  • Inside the for loops count all zero’s using a counter.
  • Print the result.

Program:

import java.util.Scanner;
public class matrix{
    public static void main(String args[])
    {
        //Scanner class to take input
        Scanner scan = new Scanner(System.in);

        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = new int[3][3];
        int row, col ,count = 0;

        // Taking matrix1 input
        System.out.println("Enter matrix elements : ");
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                arr[row][col] = scan.nextInt();

        System.out.print("The matrix elements are:");
        printMatrix(arr);

        // Loops to total number of zeros' in a binary matrix
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(arr[row][col]==0)
                    count++;
            }   
        
        System.out.println("\nNumber of zeros' in the binary matrix are : "+count);
    }

    // Method to print the matrix
    static void printMatrix(int arr[][])
    {
        int row, col;
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");
    }
}


Output:

Enter matrix elements : 
The matrix elements are:
1 1 1 
1 1 1 
1 0 0

Number of zeros' in the binary matrix are : 2

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language.

Related Java Programs:

Java Program to find the Difference Between Sum of Two Diagonals of a Matrix

Java Program to find the Difference Between Sum of Two Diagonals of a Matrix

In the previous article, we have discussed Java Program to Print Boundary Elements of a Matrix

In this article we are going to see how we can write a program to find the difference between sum of primary diagonal and secondary diagonal elements of a matrix in JAVA language.

Java Program to find the Difference Between Sums of Two Diagonals of a Matrix

A 3*3 Matrix is having 3 rows and 3 columns where this 3*3 represents the dimension of the matrix. Means there are 3*3 i.e. total 9 elements in a 3*3 Matrix.

Let’s understand it in more simpler way.

                   | A00   A01   A02 |
Matrix A =  | A10   A11   A12 |
                   | A20   A21   A22 | 3*3
  • Matrix A represents a 3*3 matrix.
  • A‘ represents the matrix element
  • Aij‘ represents the matrix element at it’s matrix position/index.
  • i‘ represents the row index
  • j‘ represents the column index
  • Means A00=Aij  where i=0 and j=0,  A01=aij where i=0 and j=1 and like this.
  • Here we have started row value from 0 and column value from 0.

Let’s see different ways to find difference between sum of primary diagonal and secondary diagonal elements of a matrix.

Method-1: Java Program to find the Difference Between Sum of Two Diagonals of a Matrix By Static Initialization of Array Elements

Approach:

  • Initialize an array of size 3×3 with values.
  • Show the array to the user.
  • Similarly use two for loops to iterate the rows and columns, then calculate the main diagonal sum.
  • Repeat the above step to calculate the counter diagonal sum.
  • Print the difference.

Program:

import java.util.Scanner;
public class matrix{
    public static void main(String args[])
    {
        //Scanner class to take input
        Scanner scan = new Scanner(System.in);

        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = {{19,25,32},{40,54,62},{70,20,60}}, mainSum = 0, counterSum = 0;
        int row, col;
        
        System.out.print("The array elements are : ");
        
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");

        // Loop to take the sum of main diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row==col)
                    mainSum+=arr[row][col];
                // if(row+col==2)
            }
        System.out.println("Sum of main diagonal : "+mainSum);

        // Loop to take the sum of counter diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row+col==2)
                    counterSum+=arr[row][col];
            }
        System.out.println("Sum of counter diagonal : "+counterSum);

        // Printing difference betweeen both diagonals sum
        System.out.print("\nDifference between sum of both diagonal : "+(mainSum-counterSum));
    }
}

Output:

The array elements are : 
19 25 32 
40 54 62 
70 20 60 
Sum of main diagonal : 133
Sum of counter diagonal : 156

Difference between sum of both diagonal : -23

Method-2: Java Program to find the Difference Between Sum of Two Diagonals of a Matrix By Dynamic Initialization of Array Elements

Approach:

  • Declare an array of size 3×3.
  • Ask the user for input of array elements.
  • Use two for loops to iterate the rows and columns to input the array elements.
  • Show the array to the user.
  • Similarly use two for loops to iterate the rows and columns, then calculate the main diagonal sum.
  • Repeat the above step to calculate the counter diagonal sum.
  • Print the difference.

Program:

import java.util.Scanner;
public class matrix{
    public static void main(String args[])
    {
        //Scanner class to take input
        Scanner scan = new Scanner(System.in);

        // Initializing the 3X3 matrix i.e. 2D array
        int arr[][] = new int[3][3];

        System.out.print("Enter the 3x3 matrix elements :");
        int row, col, mainSum = 0, counterSum = 0;
        // Loop to take user input
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
                arr[row][col] = scan.nextInt();

        
        System.out.print("The array elements are : ");
        // Loop to print the elements
        for(row=0;row<3;row++)
        {
            // Used for formatting
            System.out.print("\n");
            for(col=0;col<3;col++)
            {
                System.out.print(arr[row][col]+" ");
            }
        }
        System.out.print("\n");

        // Loop to take the sum of main diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row==col)
                    mainSum+=arr[row][col];
                // if(row+col==2)
            }
        System.out.println("Sum of counter diagonal : "+mainSum);
        
        // Loop to take the sum of counter diagonal elements
        for(row=0;row<3;row++)
            for(col=0;col<3;col++)
            {
                if(row+col==2)
                    counterSum+=arr[row][col];
            }
        System.out.println("Sum of counter diagonal : "+counterSum);
        
        // Printing difference betweeen both diagonals sum
       System.out.print("\nDifference between sum of both diagonal : "+(mainSum-counterSum));
    }
}


Output:

Enter the 3x3 matrix elements :The array elements are
20 20 30 
40 50 60 
70 80 90 
Sum of counter diagonal : 160
Sum of counter diagonal : 150

Difference between sum of both diagonal : 10

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs:

C++ Program to Calculate Average Percentage Marks

In the previous article, we have discussed C++ Program to Find Sum of Natural Numbers. In this article, we will see C++ Program to Calculate Average Percentage Marks.

C++ Program to Calculate Average Percentage Marks

  • Write a C++ program to find average marks of five subjects using loop.

In this C++ program, we will calculate the Total Marks, Average and Percentage Marks of N subjects entered by user. We will first ask user to enter the number of subjects and then the marks of individual subjects. Then we will print Total marks of all subjects, average and percentage marks of all subjects on screen. Here is the formulae to calculate Total Average and percentage marks.

Let Number of subjects be N and each subject is of 100 marks.

Total_Marks : Sum of marks of all Subjects.
Average_Marks = Total_Marks/N.
Percentage = (Total_Marks/(N x 100)) x 100;

C++ Program to find Total, Average and Percentage Marks

C++ Program to find Total, Average and Percentage Marks

// C++ program to calculate total, average and 
// percentage marks of all subjects 
    
#include <iostream>
using namespace std; 
    
int main(){
    int subjects, i;  
    float marks, total=0.0f, averageMarks, percentage;
    
    // Input number of subjects 
     
    cout << "Enter number of subjects\n";  
    cin >> subjects;  
    
    //  Take marks of subjects as input 
    cout << "Enter marks of subjects\n";
    
    for(i = 0; i < subjects; i++){
       cin >> marks;
       total += marks; 
    }
     
    // Calculate Average
    averageMarks = total / subjects;
     
    // Each subject is of 100 Marks 
    percentage = (total/(subjects * 100)) * 100;  
    
    cout << "Total Marks = " << total;  
    cout << "\nAverage Marks = " << averageMarks;  
    cout << "\nPercentage = " << percentage;  
 
    return 0;  
}

Output

Enter number of subjects
5
Enter marks of subjects
34 65 96 47 62
Total Marks = 304
Average Marks = 60.8
Percentage = 60.8

In above program, we first ask user to enter the number of subjects and store it in variable “subjects”. Then using a for loop, we take the marks of each subject as input from user and add it to variable “total”. After for loop, we will have total marks of all subjects in variable “total”.

Then we calculate the value of average marks and percentage marks as per expression given above. Finally, we print the value of Total Marks, Average Marks and Percentage Marks on screen using cout.

Bridge your knowledge gap by practicing with Examples of C++ Programs on daily basis and learn the concepts of weak areas efficiently & easily.

How to run Python scripts

In this article, we will learn more about how to run Python scripts. You should be familiar with Python syntax. If you don’t know many about Python check our guide here. You need to have Python installed in your machine. To know how to install python on your system check our installation guide.

We will discuss:

  • How to update python
  • Run Python scripts
  • Run python in the terminal
  • Comments in Python

How to update Python:

We discussed in a previous article how to install Python. It’s always recommended to have the latest version of Python. This will let you avoid a lot of issues. In each update, Python adds new fixes and enhancements. Updating python will let take the advantage or new fixes. To update the Python version you need to first check your operating system.

Updating Python in widows

  1. Visit Python official page
  2. Download the latest Python version
  3. It’ll download a .exe file.
  4. open it and proceed like the installation.
  5. It’ll update the Python version installed on your machine.

Updating Python in widows

Updating Python in Ubuntu

Updating Python in Ubuntu is a simple easy command.

  1. Update apt package manager
    sudo apt update && sudo apt-get upgrade
  2. Install the latest version of Python.
    sudo apt install python3.8.2

This will update the Python version to 3.8.2.

Updating Python in Mac

  1. Visit Python official page
  2. Download the latest Python version
  3. It’ll download a file.
  4. open it and proceed like the installation.
  5. It’ll update the Python version installed on your macOS.

Updating Python globally might not be a good idea. We learned in a previous article that it’s better to use a virtual environment in Python projects. In most cases, you will need to only update the python version in your virtual environment.

python -m venv --upgrade <env_directory>

This will only update the python version inside your virtual environment.

After making sure that you have Python installed. And it is the latest version. Now you can run Python scripts.

Run Python scripts

Usually, a python script will look like this

import os 

def main():
    path = input("Enter folder path: ")
    folder = os.chdir(path)

    for count, filename in enumerate(os.listdir()): 
        dst ="NewYork" + str(count) + ".jpeg"
        os.rename(src, dst) 

if __name__ == '__main__':
    main()

It has the main function that will have the script logic. This code is the main functionality of the script. It actually defines what you need to do. The other part which invokes the main function is

if __name__ == '__main__':
    main()

First, define the function contains your code. Python will enter the if __name__ == ‘__main__’: condition and invoke your main() function. We need to know what happens behind the scene.

  1. The interpreter reads the python source file. interpreter sets the __name__ special variable and assigns it to the “__main__” string.
  2. This will tell the interpreter to run the function called inside it. In our case, it’s the main() function.

Scripting is one of the biggest features of Python. To achieve this Python needs to make its code executable in different places.

Run python scripts in the terminal

You can run Python code from the terminal. You can write python <file_name.py>. This will tell the Python interpreter to run the code in this file.

python my_script.py

This will invoke the main function inside the script and execute the logic. A feature like this is useful if you need to automate some of your work from the terminal. Let’s say that you’re a DevOps and every time you power the machine you need to log the time and the user. You can write Python code that will check the time and the username of logged in user. It’ll update the log file with these data each time someone logs in and run the machine. In such a case, you can’t open the file manually. You will add to system bootup commands the command that will run this script.

You can open a Python shell in the terminal. It’ll help you execute your code directly. With this, you don’t need every time you want to test new changes to run the script again. You can write your script and test it in the same place. It’ll help you develop the script faster.

Comments in Python scripts

Python is shining for its readability. Commenting helps you explain more logic that could be difficult to understand from code. Adding comments helps your colleagues to understand the complex logic. Comments are very helpful in teams. It helps team members to know the reason for each part of the code. This makes it easy to work and make the development process faster. Adding comments in python is simply by adding hash.

# the below code will print items from 1 to 5
for x in range(1, 5):
    print(x)

Notice that the code after the # symbol will not be run. Python sees this code as a comment. It’ll not execute it

conclusion

You can run a Python script from the system GUI or from the terminal. It depends on how you want to use it. The comments in Python used to add human-readable text in the code. Python comments start with a hash symbol. Python interpreter skips the hashed text. Updating python is very important. It makes you up to date with new fixes. You can update Python globally across your entire system. The most efficient is to update the Python version in your virtual environment. It helps in big projects to keep things safe and not break it.

exit and atexit function in C

exit and atexit function in C

Interview Questions

  • What is exit function in C.
  • What is atexit function and can we call it more than once in a C program.

What is exit function in C.

The function void exit(int status); terminates calling process normally. Before terminating a process, it performs the following operations:

  • Functions registered with atexit are called.
  • All streams/files are closed and flushed if buffered, and all files created with tmpfile are removed.
  • Control is returned to the calling(host) environment.

Function prototype of exit function

void exit(int status);

exit and atexit function in C

#include <stdio.h>
#include <stdlib.h>
 
int main(){
    printf("Program start\n");
    /* Terminating program using exit */
    exit(0);
    printf("It won't get printed ever\n");  
    return 0;
}

Output

Program start

What is atexit function and can we call it more than once in a C program.

The stdlib C Library function int atexit(void (*func)(void)); registers the function pointed to by func to be called when the program terminates. Upon normal termination of the program, function pointed by func is automatically called without arguments. You can register your termination function anywhere in program.

This function returns zero value, if the function was successfully registered, otherwise a non-zero value if unsuccessful.

What is atexit function and can we call it more than once in a C program

#include <stdio.h>
#include <stdlib.h>
 
void myFunction(){
    printf("Program end, Bye Bye\n");
    getch();
}
 
int main(){
    printf("Program start\n");
    atexit(myFunction);  
    return 0;
}

Output

Program start
Program end, Bye Bye

You can call atexit function more than once, they are all executed in reverse order of their call(the last function to be registered will be the first function to be called).

Java Lecture Notes PDF Free Download

java lecture notes

Java Lecture Notes: Students who are pursuing B.Tech, MTech, BCA, and MCA can graduate Java Lecture Notes and Study Material can access the best sources to start their preparation process of the subject.

The Java Lecture Notes and Study Material is the main source that can enhance the knowledge of the subject. Students can start their preparation for the Java course with the help of the Java Lecture Notes and Study Material. When students refer to and study from the study material, they are improving their performance in the subject. With an improvement in the performance, the student can improve their core and score better marks.

Java Lecture Notes and Study Material provides students with a major advantage as they can access the best notes and study material through this article. Students get a review of the latest syllabus, the best reference boos and the list of the important questions. Students can easily download the Java Lecture Notes and Study Material PDFs and access them for free. Their preparation will improve, and they can approach their examination with confidence.

Introduction to Java

Java programming is a language of programming. Students learn the concept of Java with the help of object-oriented programming principles. Java programme helps students learn about concepts like Structure of Java program, Data types, Variables, Operators, Keywords, Naming convention and other concepts.

Java Programming Lecture Notes and Study Material PDF Free Download

Students who are pursuing Bachelors in Technology, MTech, BCA and MCA can access and download the best Java Lecture Notes and other important Study Material from this article. The sources of study material are the best tools for starting their preparation for their examination.

Aspirants can download the pdf of the notes and study materials for free and can refer to them when they start their preparation process for their examination. The reference to the Java Lecture Notes and Study Material will guide the students with a better understanding of the concepts. Understanding the concepts helps students enhance their performance and score better marks.

Here is a list of a few important Java Lecture Notes for thorough preparation for the Java course programme:

  • Java Lecture Notes PDF
  • Java Programming Study Material PDF
  • List of Important Questions for Java Lecture Notes
  • Java Programming Questions PDF
  • Java Programing PPT

Java Programming Reference Books

The best way to prepare for any subject is to refer to reference books. Books are very important and useful for furthering their knowledge of Java programming. They provide excellent information and the best books for Java programming according to the recommendations of the experts in the field. This article provides you with the best reference books that students can refer to Java programming.

The list of the best and most recommended books for Java programming preparations are as follows. Students should refer to books that meet their needs and requirements.

  • Core Java Volume 1
  • Java: A Beginner’s Guide
  • Effective Java
  • Java- The Complete Reference
  • Head First Java
  • Java Concurrency in Practice
  • Java Performance: The Definite Guide

Java Programming Syllabus

The latest syllabus is an important tool that all students must have to start their preparation for their Java examination. All students must read and go through the syllabus. It helps students stay up to date with all the important concepts and topics that are a part of the syllabus. This article provides students with a detailed and up to date view of the syllabus, with the needs of all the student’s needs and requirements.

The Java Syllabus gives students a clear idea of what topics and concepts they should study. The unit-wise break-up of the topics helps students understand what concepts to enlist and what are the important concept.

Students should cover all the important topics in the Java programme syllabus. When students study all the topics, they will be able to easily and comfortably write the Java programming examination. One advantage of reviewing the syllabus is that students can avoid studying irrelevant topics.

The unit-wise break up of the Java programming course syllabus is as follows:

Unit 1: Introduction to Java

  • Features of Java
  • JDK Environment & tools
  • OOPs Concepts
  • Class
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Difference between C++ and Java
  • Structure of Java program
  • Data types
  • Variables
  • Operators
  • Keywords
  • Naming convention
  • Decision making
  • Looping
  • Typecasting
  • Array
  • Creating an array
  • Types of array
  • String

Unit 2: Classes and Objects

  • Creating Classes and Objects
  • Memory allocation for objects
  • Constructor
  • Implementation of inheritance simple and multilevel
  • Interfaces
  • Abstract classes and methods
  • Implementation of polymorphism
  • Method overload
  • Method overriding
  • Nested and inner classes
  • Modifiers and access control
  • Packages
  • Packages concept
  • Creating user-defined packages
  • Java built-in packages
  • Java built-in packages
  • Wrapped classes

Unit 3: Collection

  • Collection Framework
  • Interfaces
  • Collection
  • List
  • Set
  • Sorted set
  • Enumeration
  • Iterator
  • List iterator
  • Classes
  • Linked list
  • Array list
  • Vector
  • Hash set
  • Tree set
  • Hash table
  • Working with maps
  • Map interface
  • Map Classes
  • Hash map
  • Treemap

Unit 4: File and Exception Handling

  • Exception
  • Exception types
  • Using try-catch and multiple catches
  • Nested try
  • Throw
  • Throws
  • Finally
  • Creating user-defined exceptions
  • File handling
  • Stream
  • Byte stream classes
  • Character stream classes
  • File IO basics
  • File operations
  • Creating file
  • Reading file
  • Writing file

Unit 5: Applet, AWT, and Swing Programming

  • Applet
  • Introduction
  • Types Applet
  • Applet life cycle
  • Creating applet
  • Applet tag
  • Applet classes
  • Color
  • Graphics
  • Font
  • AWT
  • Components and containers used in AWT
  • Layout managers
  • Listeners and Adapter Classes
  • Event delegation model
  • Swing
  • Introduction to swing components and container Classes

List of Important Questions for Java Lecture Notes

Students who are pursuing Bachelors in Technology (B.Tech), MTech, BCA, or MCA can go through the list of essential questions mentioned below for Java programming course programme. All the questions in the list below aim at helping students further their knowledge about the subject.

  1. Write a short note on Java. Mention the feature of java programming language.
  2. Make a comparative study between C++ and Java.
  3. What is Java Virtual Machine? Mention a few examples.
  4. What is the Java Runtime Environment?
  5. Define a classloader.
  6. How would you define an objected-oriented programme language?
  7. With the help of examples describe how many constructors are used in java?.
  8. With the help of an example, explain the concept of the copy constructor.

FAQs on Java Lecture Notes

Question 1.
What is Java?

Answer:
Java programming is a language of programming. Students learn the concept of Java with the help of object-oriented programming principles. Java programme helps students learn about concepts like Structure of Java program, Data types, Variables, Operators, Keywords, Naming convention and other concepts.

Question 2.
What are some of the reference materials that students can download for Java Lecture Notes?

Answer:
Here are some of the reference material that students can refer to for the Java course:

  • Java Lecture Notes PDF
  • Java Programming Study Material PDF
  • Java Programming Questions PDF
  • Java Programing PPT

Question 3.
What are some of the reference books that students can refer to for Java?

Answer:
Here are some of the important books that students can refer to for Java programming:

  • Core Java Volume 1
  • Java: A Beginner’s Guide
  • Effective Java
  • Java- The Complete Reference
  • Head First Java
  • Java Concurrency in Practice
  • Java Performance: The Definite Guide

Question 4.
List of some of the important question answers that students can review and download for Java.

Answer:
Here are some of the important questions that students can review when they are studying for a Java course examination:

  1. Write a short note on Java. Mention the feature of java programming language.
  2. Make a comparative study between C++ and Java.
  3. What is Java Virtual Machine? Mention a few examples.
  4. What is the Java Runtime Environment?
  5. Define a classloader.

Conclusion

The article on Java Lecture Notes is credible and reliable for all students. The books and other study material help to enhance the knowledge of student’s knowledge of Java. Students can refer to and download the Java Lecture Notes and Study Material, read through the books and practice and review the important questions.

Java Program to Check Whether two Strings are Equal or Not

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.

Java Program to Check Whether two Strings are Equal or Not

In this java program, to check whether two strings are equal or not we will use equals() method. This method compares this string with another string object and returns true only if both strings are equal else it returns false.

Java program to check whether two strings are equal or not

In this java program, we first ask user to enter two strings and store them in String objects “str1” and “str2”. Then we check whether str1 and str2 are equal or not by calling “equals” method.
Java program to check whether two strings are equal or not

package com.tcc.java.programs;
 
import java.util.Scanner;
 
public class StringEquality {
    public static void main(String args[]) {
        String str1, str2;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter first String");
        str1 = scanner.nextLine();
 
        System.out.println("Enter second String");
        str2 = scanner.nextLine();
        // Comparing two input string
        if (str1.equals(str2))
            System.out.print("Equal Strings");
        else
            System.out.print("UnEqual Strings");
    }
}

Output

Enter first String
Apple
Enter second String
Apple
Equal Strings
Enter first String
Apple
Enter second String
Banana
UnEqual Strings

Storage Classes in C Programming

  • In this tutorial, we will learn about various storage classes in C like static, auto, register and extern. We will also study the effect of storage classes on storage and visibility of variables.

A Storage class defines the scope, life-time and where to store a variable in C program. There are four storage classes defined in C programming language

  • static
  • auto
  • register
  • extern

Static Variable

A local static variable is visible only inside their own function but unlike local variables, they retain their values between function calls. We can declare static variable by adding static keyword before data type in variable declaration statement.

static data_type variable_name;

For Example:

static int sum;
  • Static keyword has different effect on local and global variables.
  • For local static variables, compiler allocates a permanent storage in heap like global variable, so that they can retain their values between function calls. Unlike global variables, local static variables are visible only within their function of declaration.
  • For global static variables, compiler creates a global variable which is only visible within the file of declaration.
  • Variables declared static are initialized to zero(or for pointers, NULL) by default.

In the following program, we declared a local and a static variable inside getVal function. Output of this programs shows that static variable retains it’s value between successive function call whereas local variable vanishes when control exits function block.

Storage Classes in C Programming

#include <stdio.h>
 
int printVal(){
    /* Declaring a static variable */    
    static int staticVariable = 0; 
    /* Declaring a local variable */
    int localVariable = 0;
     
    /*Incrementing both variables */
    staticVariable++;
    localVariable++;
     
    printf("StaticVariable = %d, LocalVariable = %d\n", staticVariable, localVariable);
}
 
int main(){
   printVal();
   printVal();
   printVal();
   printVal();
    
   return 0;
}

Output

StaticVariable = 1, LocalVariable = 1
StaticVariable = 2, LocalVariable = 1
StaticVariable = 3, LocalVariable = 1
StaticVariable = 4, LocalVariable = 1

Automatic variable

A variable which is declared inside a function or block is automatic variable by default. We can declare automatic variables using auto keyword, but it is rarely used because by default every variable is automatic variable.

Storage Classes in C Programming 1

#include <stdio.h>
 
int main(){
    /* Automatic variable by default */
    int a = 5;
    /* Declaration of automatic variables using auto keyword */
    auto int b = 10;
 
    printf("Sum = %d", a+b);
 
    return 0;
}

Output

Sum = 15

Register Variable

Declaring a variable with register keyword is a hint to the compiler to store this variable in a register of the computer’s CPU instead of storing it in memory. Storing any variable in CPU register, will reduce the time of performing any operation on register variable. We can declare register variables using register keyword.

  • The scope of register variables are same as automatic variables, visible only within their function.
  • You a only declare local variables and formal parameters of a function as register variables, global register variables are not allowed.
  • Declaring a variable as register is a request to the compiler to store this variable in CPU register, compiler may or may not store this variable in CPU register(there is no guarantee).
  • Frequently accessed variables like loop counters are good candidates for register variable.

Register Variable

#include <stdio.h>
 
int main(){
    /* Declaration of register variables using register keyword */
    register int counter;
    int sum=0;
    /* Variable counter is used frequently within for loop */
    for(counter = 1; counter <= 500; counter++){
        sum+= counter;
    }
    printf("Sum = %d", sum);
    
    return 0;
}

Output

Sum = 125250

External Variable

External variables in C are variables which can be used across multiple files. We you can declare an external variable by preceding a variable name with extern specifier. The extern specifier only tells the compiler about the name and data type of variable without allocating any storage for it. However, if you initialize that variable, then it also allocates storage for the extern variable.

  • Variables declared extern are initialized to zero by default.
  • The scope of the extern variable is global.
  • The value of the external variable exists till program termination.