Author name: Vikram Chiluka

Program to Find the Sum of an Upper Triangular Matrix

Python Program to Find the Sum of an Upper Triangular Matrix

In the previous article, we have discussed Python Program to Find the Sum of all Elements in a 2D Array

Given a matrix and the task is to find the sum of an upper triangular matrix of the given matrix in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Upper Triangular Matrix:

An upper triangular matrix is a square matrix in which all of the entries below the major diagonal are zero.

Examples:

Example1:

Input:

Given Matrix :
6 2 1
1 5 0
2 8 3

Output:

The sum of Upper Triangular matrix of the given matrix is :
11

Example2:

Input:

Given Matrix :
4 3
9 8

Output:

The sum of Upper Triangular matrix of the given matrix is :
9

Program to Find the Sum of an Upper Triangular Matrix in Python

Below are the ways to find the sum of an upper triangular matrix of the given matrix in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say uppr_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is greater than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, add the gvnmatrix[n][m] to the above-initialized uppr_sum and store it in the same variable uppr_sum.
  • Print the variable uppr_sum to get the sum of an upper triangular matrix of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[6, 2, 1], [1, 5, 0], [2, 8, 3]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
print("The sum of Upper Triangular matrix of the given matrix is :")
# Take a variable say uppr_sum and initialize its value to 0.
uppr_sum = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is greater than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n > m:
          # If the statement is true, add the gvnmatrix[n][m] to the above-initialized
          # uppr_sum and store it in the same variable uppr_sum.
            uppr_sum += mtrx[n][m]
# Print the variable uppr_sum to get the sum of an upper triangular matrix of the
# given matrix.
print(uppr_sum)

Output:

The sum of Upper Triangular matrix of the given matrix is :
11

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say uppr_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is greater than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, add the gvnmatrix[n][m] to the above-initialized uppr_sum and store it in the same variable uppr_sum.
  • Print the variable uppr_sum to get the sum of an upper triangular matrix of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
# Take a variable say uppr_sum and initialize its value to 0.
uppr_sum = 0
print("The sum of Upper Triangular matrix of the given matrix is :")
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is greater than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n > m:
          # If the statement is true, add the gvnmatrix[n][m] to the above-initialized
          # uppr_sum and store it in the same variable uppr_sum.
            uppr_sum += mtrx[n][m]
# Print the variable uppr_sum to get the sum of an upper triangular matrix of the
# given matrix.
print(uppr_sum)

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 2
Enter {2} elements of row {1} separated by spaces = 4 3
Enter {2} elements of row {2} separated by spaces = 9 8
The sum of Upper Triangular matrix of the given matrix is :
9

Dive into numerous Python Programming Language Examples for practice and get the best out of the tutorial and learn python one step at a time.

Python Program to Find the Sum of an Upper Triangular Matrix Read More »

Program to Find the Sum of all Elements in a 2D ArrayMatrix

Python Program to Find the Sum of all Elements in a 2D Array/Matrix

In the previous article, we have discussed Python Program to Display an Upper Triangular Matrix

Given a matrix and the task is to find the sum of all elements in a 2-dimensional array of the given matrix in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given Matix : 
1 6 4 
8 1 3 
1 6 2

Output:

The sum of all elements in 2 dimensional array for a given matrix is :
32

Example2:

Input:

Given Matix : 
0 8
3 7

Output:

The sum of all elements in 2 dimensional array for a given matrix is :
18

Program to Find the Sum of all Elements in a 2D Array in Python

Below are the ways to find the sum of all elements in a 2-dimensional array of the given matrix in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Add the gvnmatrix[n][m] to the above-initialized rslt_sum and store it in the same variable rslt_sum.
  • Print the variable rslt_sum to get the sum of all elements in a 2-dimensional array for a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[1, 6, 4], [8, 1, 3], [1, 6, 2]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
print("The sum of all elements in 2 dimensional array for a given matrix is :")
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Add the gvnmatrix[n][m] to the above-initialized
        # rslt_sum and store it in the same variable rslt_sum.
        rslt_sum += mtrx[n][m]
# Print the variable rslt_sum to get the sum of all elements in a 2 dimensional array for
# a given matrix
print(rslt_sum)

Output:

The sum of all elements in 2 dimensional array for a given matrix is :
32

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Add the gvnmatrix[n][m] to the above-initialized rslt_sum and store it in the same variable rslt_sum.
  • Print the variable rslt_sum to get the sum of all elements in a 2-dimensional array for a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
print("The sum of all elements in 2 dimensional array for a given matrix is :")
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Add the gvnmatrix[n][m] to the above-initialized
        # rslt_sum and store it in the same variable rslt_sum.
        rslt_sum += mtrx[n][m]
# Print the variable rslt_sum to get the sum of all elements in a 2 dimensional array for
# a given matrix
print(rslt_sum)

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 2
Enter {2} elements of row {1} separated by spaces = 0 8
Enter {2} elements of row {2} separated by spaces = 3 7
The sum of all elements in 2 dimensional array for a given matrix is :
18

If you are new to the Python Programming Language then practice using our Python Programming Examples for Beginners as our expert team has designed them from scratch.

Python Program to Find the Sum of all Elements in a 2D Array/Matrix Read More »

Program to Display an Upper Triangular Matrix

Python Program to Display an Upper Triangular Matrix

In the previous article, we have discussed Python Program to Display a Lower Triangular Matrix

Given a matrix and the task is to display an upper triangular matrix of the given matrix in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Upper Triangular Matrix:

An upper triangular matrix is a square matrix in which all of the entries below the major diagonal are zero.

Examples:

Example1:

Input:

Given Matrix :
5 3 2
6 1 5
4 8 2

Output:

The Upper Triangular matrix of the given matrix is : 
5 3 2 
0 1 5 
0 0 2

Example2:

Input:

Given Matrix :
1 2 3
6 5 4
7 8 9

Output:

The Upper Triangular matrix of the given matrix is :
1 2 3 
0 5 4 
0 0 9

Program to Display an Upper Triangular Matrix in Python

Below are the ways to display an upper triangular matrix of the given matrix in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is greater than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print 0.
  • Else Print the element of the matrix by printing gvnmatrix[n][m] value.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[5, 3, 2], [6, 1, 5], [4, 8, 2]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
print("The Upper Triangular matrix of the given matrix is :")
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is greater than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n > m:
          # If the statement is true, then print 0.
            print("0 ", end="")
        else:
          # Else Print the element of the matrix by printing gvnmatrix[n][m] value.
            print(mtrx[n][m], end=" ")
    print()

Output:

The Upper Triangular matrix of the given matrix is :
5 3 2 
0 1 5 
0 0 2

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is greater than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print 0.
  • Else Print the element of the matrix by printing gvnmatrix[n][m] value.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
print("The Upper Triangular matrix of the given matrix is :")
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is greater than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n > m:
          # If the statement is true, then print 0.
            print("0 ", end="")
        else:
          # Else Print the element of the matrix by printing gvnmatrix[n][m] value.
            print(mtrx[n][m], end=" ")
    print()

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 3
Enter {3} elements of row {2} separated by spaces = 6 5 4
Enter {3} elements of row {3} separated by spaces = 7 8 9
The Upper Triangular matrix of the given matrix is :
1 2 3 
0 5 4 
0 0 9

Remediate your knowledge gap by attempting the Python Code Examples regularly and understand the areas of need and work on them.

Python Program to Display an Upper Triangular Matrix Read More »

Program to Display a Lower Triangular Matrix

Python Program to Display a Lower Triangular Matrix

In the previous article, we have discussed Python Program to Find the Sum of all Diagonal Elements of a Matrix

Given a matrix and the task is to display the lower triangular matrix of the given matrix in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Lower Triangular Matrix:

A lower triangular matrix is one that has all of its upper triangular elements equal to zero. In other words, all non-zero elements are on the main diagonal or in the lower triangle.

Examples:

Example1:

Input:

Given Matrix :
5 3 2
6 1 5
4 8 2

Output:

The Lower Triangular matrix of the given matrix is :
5 0 0 
6 1 0 
4 8 2

Example2:

Input:

Given Matrix :
1 2 3
6 5 4
7 8 9

Output:

The Lower Triangular matrix of the given matrix is :
1 0 0 
6 5 0 
7 8 9

Program to Display a Lower Triangular Matrix in Python

Below are the ways to display the lower triangular matrix of the given matrix in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is less than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print 0.
  • Else Print the element of the matrix by printing gvnmatrix[n][m] value.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[5, 3, 2], [6, 1, 5], [4, 8, 2]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
print("The Lower Triangular matrix of the given matrix is :")
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is less than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n < m:
          # If the statement is true, then print 0.
            print("0 ", end="")
        else:
          # Else Print the element of the matrix by printing gvnmatrix[n][m] value.
            print(mtrx[n][m], end=" ")
    print()

Output:

The Lower Triangular matrix of the given matrix is :
5 0 0 
6 1 0 
4 8 2

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is less than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print 0.
  • Else Print the element of the matrix by printing gvnmatrix[n][m] value.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
print("The Lower Triangular matrix of the given matrix is :")
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is less than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n < m:
          # If the statement is true, then print 0.
            print("0 ", end="")
        else:
          # Else Print the element of the matrix by printing gvnmatrix[n][m] value.
            print(mtrx[n][m], end=" ")
    print()

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 3 
Enter {3} elements of row {2} separated by spaces = 6 5 4
Enter {3} elements of row {3} separated by spaces = 7 8 9
The Lower Triangular matrix of the given matrix is :
1 0 0 
6 5 0 
7 8 9

Explore more Example Python Programs with output and explanation and practice them for your interviews, assignments and stand out from the rest of the crowd.

Python Program to Display a Lower Triangular Matrix Read More »

Program to Find the Sum of all Diagonal Elements of a Matrix

Python Program to Find the Sum of all Diagonal Elements of a Matrix

In the previous article, we have discussed Python Program to Check Whether a Matrix is Diagonal or Not

Given a matrix and the task is to find the sum of all diagonal elements of a given matrix in python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Diagonal Matrix:

The entries outside the main diagonal of a diagonal matrix are all 0; the word usually refers to square matrices.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given Matrix : 
3 0 0
0 1 0
0 0 2

Output:

The Sum of all Diagonal elements of a given Matix =  6

Example2:

Input:

Given Matrix : 
1 2 3 
6 5 4 
7 8 9

Output:

The Sum of all Diagonal elements of a given Matix = 15

Program to Find the Sum of all Diagonal Elements of a Matrix in Python

Below are the ways to find the sum of all diagonal elements of a given matrix in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say diagnl_sum and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is equal to m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then add the gvnmatrix[n][m] to the above-initialized diagnl_sum and store it in the same variable diagnl_sum.
  • Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[3, 0, 0], [0, 1, 0], [0, 0, 2]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
# Take a variable say diagnl_sum and initialize its value to zero.
diagnl_sum = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is equal to m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n == m:
          # If the statement is true, then add the gvnmatrix[n][m] to the above-initialized
          # diagnl_sum and store it in the same variable diagnl_sum.
            diagnl_sum += mtrx[n][m]
# Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
print("The Sum of all Diagonal elements of a given Matix = ", diagnl_sum)

Output:

The Sum of all Diagonal elements of a given Matix =  6

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say diagnl_sum and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is equal to m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then add the gvnmatrix[n][m] to the above-initialized diagnl_sum and store it in the same variable diagnl_sum.
  • Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
# Take a variable say diagnl_sum and initialize its value to zero.
diagnl_sum = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is equal to m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n == m:
          # If the statement is true, then add the gvnmatrix[n][m] to the above-initialized
          # diagnl_sum and store it in the same variable diagnl_sum.
            diagnl_sum += mtrx[n][m]
# Print the value of diagnl_sum to get the sum of all diagonal elements of a given matrix.
print("The Sum of all Diagonal elements of a given Matix = ", diagnl_sum)

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 3
Enter {3} elements of row {2} separated by spaces = 6 5 4
Enter {3} elements of row {3} separated by spaces = 7 8 9
The Sum of all Diagonal elements of a given Matix = 15

If you are learning Python then the Python Programming Example is for you and gives you a thorough description of concepts for beginners, experienced programmers.

Python Program to Find the Sum of all Diagonal Elements of a Matrix Read More »

Program to Check Whether a Matrix is Diagonal or Not

Python Program to Check Whether a Matrix is Diagonal or Not

In the previous article, we have discussed Python Program to Find Square of a Matrix

Given a matrix and the task is to check if the given matrix is diagonal or not in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Diagonal Matrix:

The entries outside the main diagonal of a diagonal matrix are all 0; the word usually refers to square matrices.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given Matrix : 
3 0 0
0 1 0
0 0 2

Output:

The Matrix given is a diagonal Matrix.

Example2:

Input:

Given Matrix : 
1 2 3 
6 5 4 
7 8 9

Output:

The Matrix given is not a diagonal Matrix.

Program to Check Whether a Matrix is Diagonal or Not in Python

Below are the ways to check if the given matrix is diagonal or not in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say tempo and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement and come out of the loop.
  • Check if the value of tempo is equal to 1 using the if conditional statement.
  • If the statement is true, then print “The Matrix given is not a diagonal Matrix.”
  • Else print “The Matrix given is a diagonal Matrix.”
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[3, 0, 0], [0, 1, 0], [0, 0, 2]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
# Take a variable and initialize its value to zero.
tempo = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the
        # if conditional statement where n is the iterator value of the parent For loop and m
        # is the iterator value of the inner For loop.
        if n != m and mtrx[n][m] != 0:
           # If the statement is true, then make the value of tempo as 1.
            tempo = 1
       # Break the statement and come out of the loop.
            break
# Check if the value of tempo is equal to 1 using the if conditional statement.
if tempo == 1:
  # If the statement is true, then print "The Matrix given is not a diagonal Matrix."
    print("The Matrix given is not a diagonal Matrix.")
else:
  # Else print "The Matrix given is a diagonal Matrix."
    print("The Matrix given is a diagonal Matrix.")

Output:

The Matrix given is a diagonal Matrix.

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say tempo and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement and come out of the loop.
  • Check if the value of tempo is equal to 1 using the if conditional statement.
  • If the statement is true, then print “The Matrix given is not a diagonal Matrix.”
  • Else print “The Matrix given is a diagonal Matrix.”
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
# Take a variable say tempo and initialize its value to zero.
tempo = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the
        # if conditional statement where n is the iterator value of the parent For loop and m
        # is the iterator value of the inner For loop.
        if n != m and mtrx[n][m] != 0:
           # If the statement is true, then make the value of tempo as 1.
            tempo = 1
       # Break the statement and come out of the loop.
            break
# Check if the value of tempo is equal to 1 using the if conditional statement.
if tempo == 1:
  # If the statement is true, then print "The Matrix given is not a diagonal Matrix."
    print("The Matrix given is not a diagonal Matrix.")
else:
  # Else print "The Matrix given is a diagonal Matrix."
    print("The Matrix given is a diagonal Matrix.")

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 3
Enter {3} elements of row {2} separated by spaces = 6 5 4
Enter {3} elements of row {3} separated by spaces = 7 8 9
The Matrix given is not a diagonal Matrix.

Grab the opportunity and utilize the Python Program Code Examples over here to prepare basic and advanced topics too with ease and clear all your doubts.

Python Program to Check Whether a Matrix is Diagonal or Not Read More »

Program to Find Square of a Matrix

Python Program to Find Square of a Matrix

In the previous article, we have discussed Python Program to Print Triangular Number series 1 3 6 10 15 …N

Given a matrix and the task is to find the square of each element in the given matrix in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given Matrix :
5  3  2
6  1  5
4  8  2
7  5  8

Output:

The Square of all elements of the given matrix is :
25 9 4 
36 1 25 
16 64 4 
49 25 64

Example2:

Input:

Given Matrix :
1  2  3
6  5  4
7  8  0

Output:

The Square of all elements of the given matrix is :
1 4 9 
36 25 16 
49 64 0

Program to Find Square of a Matrix in Python

Below are the ways to find the square of each element in the given matrix in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Print the square of the given element of the matrix by printing gvnmatrix[n][m]*gvnmatrix[n][m] value where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[5, 3, 2], [6, 1, 5], [4, 8, 2], [7, 5, 8]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
print("The Square of all elements of the given matrix is :")
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Print the square of the given element of the matrix by printing gvnmatrix[n][m]*gvnmatrix[n][m]
      # value where n is the iterator value of the parent For loop and m is the iterator value
      # of the inner For loop.
        print(mtrx[n][m]*mtrx[n][m], end=' ')
    print()

Output:

The Square of all elements of the given matrix is :
25 9 4 
36 1 25 
16 64 4 
49 25 64

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • To print all the elements of the given matrix.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Print the square of the given element of the matrix by printing gvnmatrix[n][m]*gvnmatrix[n][m] value where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
print("The Square of all elements of the given matrix is :")
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Print the square of the given element of the matrix by printing gvnmatrix[n][m]*gvnmatrix[n][m]
      # value where n is the iterator value of the parent For loop and m is the iterator value
      # of the inner For loop.
        print(mtrx[n][m]*mtrx[n][m], end=' ')
    print()

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 3
Enter {3} elements of row {2} separated by spaces = 6 5 4
Enter {3} elements of row {3} separated by spaces = 7 8 0
The Square of all elements of the given matrix is :
1 4 9 
36 25 16 
49 64 0

Practice Python Program Examples to master coding skills and learn the fundamental concepts in the dynamic programming language Python.

Python Program to Find Square of a Matrix Read More »

Program to Find Sum of Series 1-2+3-4+5...+N

Python Program to Find Sum of Series 1-2+3-4+5…+N

In the previous article, we have discussed Python Program to Find Sum of Series 1+1/3+1/5+1/7+…..1/(N+2)

Given a number N and the task is to find the sum of the given series (1-2+3-4+5…+N) for the given number in Python.

Examples:

Example1:

Input:

Given Number = 20

Output:

The total sum of the series till the given number { 20 } =  -10

Example2:

Input:

Given Number = 7

Output:

The total sum of the series till the given number { 7 } =  4

Program to Find Sum of Series 1-2+3-4+5…+N in Python

Below are the ways to find the sum of the given series (1-2+3-4+5…+N) for the given number in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Take a variable say resltsum which gives the sum of the given series till N and initialize its value to 0.
  • Loop from 1 to the given number using the for loop.
  • Inside the loop, check if the value of iterator modulus 2 is equal to zero(even condition) or not using the if conditional statement.
  • If the statement is True, then subtract the iterator value from the above-declared resltsum.
  • Store it in the same variable resltsum.
  • Else if the statement is False, then add the iterator value to the above-declared resltsum.
  • Store it in the same variable resltsum.
  • Print the resltsum value which is the result of the series till the given Number N.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as static input and store it in a variable.
gvn_numb = 20
# Take a variable say resltsum which gives the sum of the given series till N and
# initialize its value to 0.
resltsum = 0
# Loop from 1 to the given number using the for loop.
for itr in range(1, gvn_numb+1):
    # Inside the loop, check if the value of iterator modulus 2 is equal to zero(even condition)
    # or not using the if conditional statement.
    if itr % 2 == 0:
      # If the statement is True, then subtract the iterator value from the above-declared
      # resltsum.
      # Store it in the same variable resltsum.
        resltsum -= itr
    else:
      # Else if the statement is False, then add the iterator value to the above-declared
      # resltsum.
      # Store it in the same variable resltsum.
        resltsum += itr
# Print the resltsum value which is the result of the series till the given Number N.
print(
    "The total sum of the series till the given number {", gvn_numb, "} = ", resltsum)

Output:

The total sum of the series till the given number { 20 } =  -10

Method #2: Using For loop (User Input)

Approach:

  • Give the number N as user input using the int(input()) function and store it in a variable.
  • Take a variable say resltsum which gives the sum of the given series till N and initialize its value to 0.
  • Loop from 1 to the given number using the for loop.
  • Inside the loop, check if the value of iterator modulus 2 is equal to zero(even condition) or not using the if conditional statement.
  • If the statement is True, then subtract the iterator value from the above-declared resltsum.
  • Store it in the same variable resltsum.
  • Else if the statement is False, then add the iterator value to the above-declared resltsum.
  • Store it in the same variable resltsum.
  • Print the resltsum value which is the result of the series till the given Number N.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as user input using the int(input()) function and 
# store it in a variable.
gvn_numb = int(input("Enter some Random Number = "))
# Take a variable say resltsum which gives the sum of the given series till N and
# initialize its value to 0.
resltsum = 0
# Loop from 1 to the given number using the for loop.
for itr in range(1, gvn_numb+1):
    # Inside the loop, check if the value of iterator modulus 2 is equal to zero(even condition)
    # or not using the if conditional statement.
    if itr % 2 == 0:
      # If the statement is True, then subtract the iterator value from the above-declared
      # resltsum.
      # Store it in the same variable resltsum.
        resltsum -= itr
    else:
      # Else if the statement is False, then add the iterator value to the above-declared
      # resltsum.
      # Store it in the same variable resltsum.
        resltsum += itr
# Print the resltsum value which is the result of the series till the given Number N.
print(
    "The total sum of the series till the given number {", gvn_numb, "} = ", resltsum)

Output:

Enter some Random Number = 7
The total sum of the series till the given number { 7 } = 4

Find a comprehensive collection of Examples of Python Programs ranging from simple ones to complex ones to guide you throughout your coding journey.

Python Program to Find Sum of Series 1-2+3-4+5…+N Read More »

Program to Print Triangular Number series 1 3 6 10 15 ...N

Python Program to Print Triangular Number series 1 3 6 10 15 …N

In the previous article, we have discussed Python Program to Find Sum of Series 1-2+3-4+5…+N

Given a number N and the task is to find the triangular number series (1 3 6 10 15 …N) until the given number.

int() function in Python:

The int() function is used to transform a value into an integer number.

Examples:

Example1:

Input:

Given Number = 8

Output:

The Triangular series until the given number{ 8 } is :
1 3 6 10 15 21 28 36

Example2:

Input:

Given Number = 15

Output:

The Triangular series until the given number{ 15 } is :
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120

Program to Print Triangular Number series 1 3 6 10 15 …N in Python

Below are the ways to find the triangular number series (1 3 6 10 15 …N) until the given number N :

Method #1: Using While Loop (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Take a variable say k and initialize its value with 1.
  • Loop until the value of k is less than or equal to the given number using the while loop.
  • Inside the loop, multiply the value of k with k+1 and divide the result by 2 and convert it into an integer using the int() function.
  • Store it in a variable say p.
  • Print the above result (p) separated by spaces to get the triangular series until the given number.
  • Increment the value of k by 1 and store it in the same variable k.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as static input and store it in a variable.
gvn_numb = 8
# Take a variable say k and initialize its value with 1.
k = 1
print("The Triangular series until the given number{", gvn_numb, "} is :")
# Loop until the value of k is less than or equal to the given number using the while loop.
while(k <= gvn_numb):
   # Inside the loop, multiply the value of k with k+1 and divide the result by 2 and
   # convert it into an integer using the int() function.
   # Store it in a variable say p.
    p = int((k*(k+1))/2)
   # Print the above result (p) separated by spaces to get the triangular series until
   # the given number.
    print(p, end=" ")
   # Increment the value of k by 1 and store it in the same variable k.
    k += 1

Output:

The Triangular series until the given number{ 8 } is :
1 3 6 10 15 21 28 36

Method #2: Using While loop (User Input)

Approach:

  • Give the number N as user input using the int(input()) function and store it in a variable.
  • Take a variable say k and initialize its value with 1.
  • Loop until the value of k is less than or equal to the given number using the while loop.
  • Inside the loop, multiply the value of k with k+1 and divide the result by 2 and convert it into an integer using the int() function.
  • Store it in a variable say p.
  • Print the above result (p) separated by spaces to get the triangular series until the given number.
  • Increment the value of k by 1 and store it in the same variable k.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as user input using the int(input()) function and
# store it in a variable.
gvn_numb = int(input("Enter some Random Number = "))
# Take a variable say k and initialize its value with 1.
k = 1
print("The Triangular series until the given number{", gvn_numb, "} is :")
# Loop until the value of k is less than or equal to the given number using the while loop.
while(k <= gvn_numb):
   # Inside the loop, multiply the value of k with k+1 and divide the result by 2 and
   # convert it into an integer using the int() function.
   # Store it in a variable say p.
    p = int((k*(k+1))/2)
   # Print the above result (p) separated by spaces to get the triangular series until
   # the given number.
    print(p, end=" ")
   # Increment the value of k by 1 and store it in the same variable k.
    k += 1

Output:

Enter some Random Number = 15
The Triangular series until the given number{ 15 } is :
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120

If you wanna write simple python programs as a part of your coding practice refer to numerous Simple Python Program Examples existing and learn the approach used.

Python Program to Print Triangular Number series 1 3 6 10 15 …N Read More »

Program to Find Sum of Series 1+13+15+17+.....1(N+2)

Python Program to Find Sum of Series 1+1/3+1/5+1/7+…..1/(N+2)

In the previous article, we have discussed Python Program to Find the Sum of Series 3+7+13+21…..+N

Given a number N and the task is to find the sum of the given series (1+1/3+1/5+1/7+…..1/(N+2)) for the given number in Python.

Examples:

Example1:

Input:

Given Number = 25

Output:

The total sum of the series till the given number { 25 } =  2.2643528386481675

Example2:

Input:

Given Number = 14

Output:

The total sum of the series till the given number { 14 } =  1.9551337551337549

Program to Find Sum of Series 1+1/3+1/5+1/7+…..1/(N+2) in Python

Below are the ways to find the sum of the given series (1+1/3+1/5+1/7+…..1/(N+2)) for the given number in Python:

Method #1: Using While Loop (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Take a variable say resltsum which gives the sum of the given series till N and initialize its value to 0.0 (to get the floating-point number).
  • Take another variable say k and initialize its value with 1.
  • Loop until the value of k is less than or equal to the given number using the while loop.
  • Inside the loop, Add 1 divided by k to the above-initialized resltsum and store it in the same variable resltsum.
  • Increment the value of k by 2 and store it in the same variable k.
  • Print the resltsum value which is the result of the series till the given Number N.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as static input and store it in a variable.
gvn_numb = 25
# Take a variable say resltsum which gives the sum of the given series till N and
# initialize its value to 0.0 (to get the floating-point number).
resltsum = 0.0
# Take another variable say k and initialize its value with 1.
k = 1
# Loop until the value of k is less than or equal to the given number using the while loop.
while(k <= gvn_numb):
  # Inside the loop, Add 1 divided by k to the above-initialized resltsum and
  # store it in the same variable resltsum.
    resltsum += 1/k
  # Increment the value of k by 2 and store it in the same variable k.
    k += 2
# Print the resltsum value which is the result of the series till the given Number N.
print(
    "The total sum of the series till the given number {", gvn_numb, "} = ", resltsum)

Output:

The total sum of the series till the given number { 25 } =  2.2643528386481675

Method #2: Using While loop (User Input)

Approach:

  • Give the number N as user input using the int(input()) function and store it in a variable.
  • Take a variable say resltsum which gives the sum of the given series till N and initialize its value to 0.0 (to get the floating-point number).
  • Take another variable say k and initialize its value with 1.
  • Loop until the value of k is less than or equal to the given number using the while loop.
  • Inside the loop, Add 1 divided by k to the above-initialized resltsum and store it in the same variable resltsum.
  • Increment the value of k by 2 and store it in the same variable k.
  • Print the resltsum value which is the result of the series till the given Number N.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as user input using the int(input()) function and 
# store it in a variable.
gvn_numb = int(input("Enter some Random Number = "))
# Take a variable say resltsum which gives the sum of the given series till N and
# initialize its value to 0.0 (to get the floating-point number).
resltsum = 0.0
# Take another variable say k and initialize its value with 1.
k = 1
# Loop until the value of k is less than or equal to the given number using the while loop.
while(k <= gvn_numb):
  # Inside the loop, Add 1 divided by k to the above-initialized resltsum and
  # store it in the same variable resltsum.
    resltsum += 1/k
  # Increment the value of k by 2 and store it in the same variable k.
    k += 2
# Print the resltsum value which is the result of the series till the given Number N.
print(
    "The total sum of the series till the given number {", gvn_numb, "} = ", resltsum)

Output:

Enter some Random Number = 14
The total sum of the series till the given number { 14 } = 1.9551337551337549

Find the best practical and ready-to-use Python Programming Examples that you can simply run on a variety of platforms and never stop learning.

Python Program to Find Sum of Series 1+1/3+1/5+1/7+…..1/(N+2) Read More »