Python

Program to Count Number of Digits in a Number using Recursion

Python Program to Count Number of Digits in a Number using Recursion

In the previous article, we have discussed Python Program to Find Sum of Odd Numbers Using Recursion in a List/Array

Given a number and the task is to count the number of digits present in a given number using recursion in python.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given Number = 567812

Output:

The Number of digits present in the above given Number { 567812 } =  6

Example2:

Input:

Given Number = 602

Output:

The Number of digits present in the above given Number { 602 } =  3

Program to Count Number of Digits in a Number using Recursion in Python

Below are the ways to count the number of digits present in a given number using recursion in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable say cnt_digits and initialize its value to 0.
  • Pass the given number as an argument to the countnumbr_digits function.
  • Create a recursive function to say countnumbr_digits which takes the given number as an argument and returns the count of the number of digits present in a given number.
  • Make the cnt_digits a global declaration.
  • Check if the given number is not equal to 0 using the if conditional statement.
  • If the statement is true, then increment the value of cnt_digits by 1 and store it in the same variable.
  • Pass the given number divided by 10 as an argument to the countnumbr_digits function(which removes the last digit of the number) {Recursive Logic}.
  • Return cnt_digits.
  • Print the count of the number of digits present in the above-given number.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say countnumbr_digits which takes the given number as
# an argument and returns the count of the number of digits present in a given number.


def countnumbr_digits(gvn_numb):
  # Make the cnt_digits a global declaration.
    global cnt_digits
    # Check if the given number is not equal to 0 using the if conditional statement.
    if (gvn_numb != 0):
      # If the statement is true, then increment the value of cnt_digits by 1 and store it
      # inthe same variable.
        cnt_digits += 1
      # Pass the given number divided by 10 as an argument to the countnumbr_digits function
      # (which removes the last digit of the number) {Recursive Logic}.
        countnumbr_digits(gvn_numb // 10)
    # Return cnt_digits.
    return cnt_digits


# Give the number as static input and store it in a variable.
gvn_numb = 567812
# Take a variable say cnt_digits and initialize its value to 0.
# Pass the given number as an argument to the countnumbr_digits function.
cnt_digits = 0
# Print the count of the number of digits present in the above-given number.
print("The Number of digits present in the above given Number {", gvn_numb, "} = ", countnumbr_digits(
    gvn_numb))

Output:

The Number of digits present in the above given Number { 567812 } =  6

Method #2: Using Recursion (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take a variable say cnt_digits and initialize its value to 0.
  • Pass the given number as an argument to the countnumbr_digits function.
  • Create a recursive function to say countnumbr_digits which takes the given number as an argument and returns the count of the number of digits present in a given number.
  • Make the cnt_digits a global declaration.
  • Check if the given number is not equal to 0 using the if conditional statement.
  • If the statement is true, then increment the value of cnt_digits by 1 and store it in the same variable.
  • Pass the given number divided by 10 as an argument to the countnumbr_digits function(which removes the last digit of the number) {Recursive Logic}.
  • Return cnt_digits.
  • Print the count of the number of digits present in the above-given number.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say countnumbr_digits which takes the given number as
# an argument and returns the count of the number of digits present in a given number.


def countnumbr_digits(gvn_numb):
  # Make the cnt_digits a global declaration.
    global cnt_digits
    # Check if the given number is not equal to 0 using the if conditional statement.
    if (gvn_numb != 0):
      # If the statement is true, then increment the value of cnt_digits by 1 and store it
      # inthe same variable.
        cnt_digits += 1
      # Pass the given number divided by 10 as an argument to the countnumbr_digits function
      # (which removes the last digit of the number) {Recursive Logic}.
        countnumbr_digits(gvn_numb // 10)
    # Return cnt_digits.
    return cnt_digits


# Give the number 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 cnt_digits and initialize its value to 0.
# Pass the given number as an argument to the countnumbr_digits function.
cnt_digits = 0
# Print the count of the number of digits present in the above-given number.
print("The Number of digits present in the above given Number {", gvn_numb, "} = ", countnumbr_digits(
    gvn_numb))

Output:

Enter some random number = 5341
The Number of digits present in the above given Number { 5341 } = 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 Count Number of Digits in a Number using Recursion Read More »

Program to Find Sum of Odd Numbers Using Recursion in a ListArray

Python Program to Find Sum of Odd Numbers Using Recursion in a List/Array

In the previous article, we have discussed Python Program to Check Armstrong Number using Recursion

Given a list and the task is to find the sum of odd numbers using recursion in a given list in python.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given List = [6, 12, 4, 2, 3, 9, 1, 5]

Output:

The Sum of Odd Elements in a given list [6, 12, 4, 2, 3, 9, 1, 5] = 18

Example2:

Input:

Given List = [4, 3, 1, 5, 11]

Output:

The Sum of Odd Elements in a given list [4, 3, 1, 5, 11] = 20

Program to Find Sum of Odd Numbers Using Recursion in a List/Array in Python

Below are the ways to find the sum of odd numbers using recursion in a given list in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given list and length of the given list as the arguments to the oddelemt_sum function.
  • Create a recursive function to say oddelemt_sum which takes the given list and length of the given list as the arguments and returns the sum of odd numbers in a given list using recursion.
  • Make the rslt_sum a global declaration.
  • Check if the length of the given list is greater than 0 using the if conditional statement.
  • If the statement is true, then subtract 1 from the length of the given list and store it in a variable k.
  • Check if the element present at the index k of the given list is odd using the modulus operator and if conditional statement.
  • If the statement is true, add the element present at the index k of the given list to the above-initialized rslt_sum.
  • Store it in the same variable.
  • Pass the given list and k value as the arguments to the oddelemt_sum function.{Recursive Logic}
  • Return rslt_sum.
  • Print the sum of odd numbers in the above-given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say oddelemt_sum which takes the given list and length
# of the given list as the arguments and returns the sum of odd numbers in a given list
# using recursion.


def oddelemt_sum(gven_lst, len_lst):
    # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the length of the given list is greater than 0 using the if conditional
    # statement.
    if(len_lst > 0):
        # If the statement is true, then subtract 1 from the length of the given list and
        # store it in a variable k.
        k = len_lst-1
   # Check if the element present at the index k of the given list is odd using modulus
   # operator and if conditional statement.
        if(gven_lst[k] % 2 != 0):
            # If the statement is true, add the element present at the index k of the
            # given list to the above-initialized rslt_sum.
            # Store it in the same variable.
            rslt_sum = rslt_sum+gven_lst[k]
           # Pass the given list and k value as the arguments to the oddelemt_sum function
           # {Recursive Logic}.
        oddelemt_sum(gven_lst, k)
       # Return rslt_sum.
    return rslt_sum


# Give the list as static input and store it in a variable.
gven_lst = [6, 12, 4, 2, 3, 9, 1, 5]
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Pass the given list and length of the given list as the arguments to the oddelemt_sum
# function.
# Print the sum of odd numbers in the above-given list.
print("The Sum of Odd Elements in a given list",
      gven_lst, "=", oddelemt_sum(gven_lst, len_lst))

Output:

The Sum of Odd Elements in a given list [6, 12, 4, 2, 3, 9, 1, 5] = 18

Method #2: Using Recursion (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given list and length of the given list as the arguments to the oddelemt_sum function.
  • Create a recursive function to say oddelemt_sum which takes the given list and length of the given list as the arguments and returns the sum of odd numbers in a given list using recursion.
  • Make the rslt_sum a global declaration.
  • Check if the length of the given list is greater than 0 using the if conditional statement.
  • If the statement is true, then subtract 1 from the length of the given list and store it in a variable k.
  • Check if the element present at the index k of the given list is odd using the modulus operator and if conditional statement.
  • If the statement is true, add the element present at the index k of the given list to the above-initialized rslt_sum.
  • Store it in the same variable.
  • Pass the given list and k value as the arguments to the oddelemt_sum function.{Recursive Logic}
  • Return rslt_sum.
  • Print the sum of odd numbers in the above-given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say oddelemt_sum which takes the given list and length
# of the given list as the arguments and returns the sum of odd numbers in a given list
# using recursion.


def oddelemt_sum(gven_lst, len_lst):
    # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the length of the given list is greater than 0 using the if conditional
    # statement.
    if(len_lst > 0):
        # If the statement is true, then subtract 1 from the length of the given list and
        # store it in a variable k.
        k = len_lst-1
   # Check if the element present at the index k of the given list is odd using modulus
   # operator and if conditional statement.
        if(gven_lst[k] % 2 != 0):
            # If the statement is true, add the element present at the index k of the
            # given list to the above-initialized rslt_sum.
            # Store it in the same variable.
            rslt_sum = rslt_sum+gven_lst[k]
           # Pass the given list and k value as the arguments to the oddelemt_sum function
           # {Recursive Logic}.
        oddelemt_sum(gven_lst, k)
       # Return rslt_sum.
    return rslt_sum


# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gven_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Pass the given list and length of the given list as the arguments to the oddelemt_sum
# function.
# Print the sum of odd numbers in the above-given list.
print("The Sum of Odd Elements in a given list",
      gven_lst, "=", oddelemt_sum(gven_lst, len_lst))

Output:

Enter some random List Elements separated by spaces = 4 3 1 5 11
The Sum of Odd Elements in a given list [4, 3, 1, 5, 11] = 20

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 Odd Numbers Using Recursion in a List/Array Read More »

Program to Check Armstrong Number using Recursion

Python Program to Check Armstrong Number using Recursion

In the previous article, we have discussed Python Program to Print Multiplication Table using Recursion

Given a number and the task is to check whether the given number is an Armstrong number or not using recursion.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given Number = 153

Output:

The above given Number is an Armstrong Number.

Example2:

Input:

Given Number = 100

Output:

The above given Number is Not an Armstrong Number.

Program to Check Armstrong Number using Recursion in Python

Below are the ways to check whether the given number is an Armstrong number or not using recursion:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given number as an argument to the chek_ArmstrngNumb function.
  • Create a recursive function to say chek_ArmstrngNumb which takes the given number as an argument and returns the rslt_sum.
  • Make the rslt_sum a global declaration.
  • Check if the given number is not equal to 0 using the if conditional statement.
  • If the statement is true, get the last digit of the given number using the modulus operator and store it in another variable k.
  • Calculate the value of k raised to power 3 using the pow() function and add it to the rslt_sum.
  • Store it in the same variable rslt_sum.
  • Pass the given number divided by 10 as an argument to the chek_ArmstrngNumb function(which removes the last digit of the number) {Recursive Logic}.
  • Return rslt_sum.
  • Check if the chek_ArmstrngNumb which takes the given number as an argument is equal to the given number using the if conditional statement.
  • If the statement is true, then print “The above-given number is an Armstrong Number”.
  • Else print “The above-given number is not an Armstrong Number”.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say chek_ArmstrngNumb which takes the given number as
# an argument and returns the rslt_sum.


def chek_ArmstrngNumb(gven_numb):
  # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the given number is not equal to 0 using the if conditional statement.
    if (gven_numb != 0):
        # If the statement is true, get the last digit of the given number using the modulus
        # operator and store it in another variable k.
        k = gven_numb % 10
     # Calculate the value of k raised to power 3 using the pow() function and add it to the
     # rslt_sum. 
     # Store it in the same variable rslt_sum.
        rslt_sum += pow(k, 3)
    # Pass the given number divided by 10 as an argument to the chek_ArmstrngNumb function
    # (which removes the last digit of the number) {Recursive Logic}.

        chek_ArmstrngNumb(gven_numb//10)
     # Return rslt_sum.
    return rslt_sum


# Give the number as static input and store it in a variable.
gven_numb = 153
# Take a variable say rslt_sum and initialize its value to 0.
# Pass the given number as an argument to the chek_ArmstrngNumb function.
rslt_sum = 0
# Check if the chek_ArmstrngNumb which takes the given number as an argument is equal
# to the given number using the if conditional statement.
if (chek_ArmstrngNumb(gven_numb) == gven_numb):
  # If the statement is true, then print "The above given number is an Armstrong Number".
    print("The above given Number is an Armstrong Number.")
else:
  # Else print "The above given number is not an Armstrong Number".
    print("The above given Number is Not an Armstrong Number.")

Output:

The above given Number is an Armstrong Number.

Method #2: Using Recursion (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given number as an argument to the chek_ArmstrngNumb function.
  • Create a recursive function to say chek_ArmstrngNumb which takes the given number as an argument and returns the rslt_sum.
  • Make the rslt_sum a global declaration.
  • Check if the given number is not equal to 0 using the if conditional statement.
  • If the statement is true, get the last digit of the given number using the modulus operator and store it in another variable k.
  • Calculate the value of k raised to power 3 using the pow() function and add it to the rslt_sum.
  • Store it in the same variable rslt_sum.
  • Pass the given number divided by 10 as an argument to the chek_ArmstrngNumb function(which removes the last digit of the number) {Recursive Logic}.
  • Return rslt_sum.
  • Check if the chek_ArmstrngNumb which takes the given number as an argument is equal to the given number using the if conditional statement.
  • If the statement is true, then print “The above-given number is an Armstrong Number”.
  • Else print “The above-given number is not an Armstrong Number”.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say chek_ArmstrngNumb which takes the given number as
# an argument and returns the rslt_sum.


def chek_ArmstrngNumb(gven_numb):
  # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the given number is not equal to 0 using the if conditional statement.
    if (gven_numb != 0):
        # If the statement is true, get the last digit of the given number using the modulus
        # operator and store it in another variable k.
        k = gven_numb % 10
     # Calculate the value of k raised to power 3 using the pow() function and add it to the
     # rslt_sum. 
     # Store it in the same variable rslt_sum.
        rslt_sum += pow(k, 3)
    # Pass the given number divided by 10 as an argument to the chek_ArmstrngNumb function
    # (which removes the last digit of the number) {Recursive Logic}.

        chek_ArmstrngNumb(gven_numb//10)
     # Return rslt_sum.
    return rslt_sum


# Give the number as user input using the int(input()) function and
# store it in a variable.
gven_numb = int(input("Enter some random number = "))
# Take a variable say rslt_sum and initialize its value to 0.
# Pass the given number as an argument to the chek_ArmstrngNumb function.
rslt_sum = 0
# Check if the chek_ArmstrngNumb which takes the given number as an argument is equal
# to the given number using the if conditional statement.
if (chek_ArmstrngNumb(gven_numb) == gven_numb):
  # If the statement is true, then print "The above given number is an Armstrong Number".
    print("The above given Number is an Armstrong Number.")
else:
  # Else print "The above given number is not an Armstrong Number".
    print("The above given Number is Not an Armstrong Number.")

Output:

Enter some random number = 100
The above given Number is Not an Armstrong Number.

Access the big list of Python Programming Code Examples with actual logical code asked in Programming and Coding Interviews for Python and stand out from the crowd.

Python Program to Check Armstrong Number using Recursion Read More »

Program to Print Multiplication Table using Recursion

Python Program to Print Multiplication Table using Recursion

In the previous article, we have discussed Python Program to Find Sum of Even Numbers Using Recursion in a List/Array

Given a number and the task is to print the multiplication table of that number using recursion in python.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given Number = 5

Output:

The Multiplication Table of the above given number  5 :
5  X  1  =  5
5  X  2  =  10
5  X  3  =  15
5  X  4  =  20
5  X  5  =  25
5  X  6  =  30
5  X  7  =  35
5  X  8  =  40
5  X  9  =  45
5  X  10  =  50

Example2:

Input:

Given Number = 2

Output:

The Multiplication Table of the above given number  2 :
2  X  1  =  2
2  X  2  =  4
2  X  3  =  6
2  X  4  =  8
2  X  5  =  10
2  X  6  =  12
2  X  7  =  14
2  X  8  =  16
2  X  9  =  18
2  X  10  =  20

Program to Print Multiplication Table using Recursion in Python

Below are the ways to print the multiplication table of the given number using recursion in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the given number and 1 as the arguments to the Mult_table_num function.
  • Create a recursive function to say Mult_table_num which takes the given number and k as the arguments and returns the multiplication table of the given number using recursion.
  • Print the given number multiplied by k.
  • Check if the k value is less than 10 using the if conditional statement.
  • If the statement is true, then pass the given number and k+1 value as the arguments to the Mult_table_num function.{Recursive Logic}
  • Print the multiplication table of the given number using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say Mult_table_num which takes the given number and k
# as the arguments and returns the multiplication table of the given number
# using recursion.


def Mult_table_num(gven_numb, k):
  # Print the given number multiplied by k.
    print(gven_numb, " X ", k, " = ", gven_numb * k)
    # Check if the k value is less than 10 using the if conditional statement.
    if (k < 10):
      # If the statement is true, then pass the given number and k+1 value as the arguments
      # to the Mult_table_num function.{Recursive Logic}
        Mult_table_num(gven_numb, k + 1)


# Give the number as static input and store it in a variable.
gven_numb = 5
# Print the multiplication table of the given number using recursion.
print("The Multiplication Table of the above given number ", gven_numb, ":")
# Pass the given number and 1 as the arguments to the Mult_table_num function.
Mult_table_num(gven_numb, 1)

Output:

The Multiplication Table of the above given number  5 :
5  X  1  =  5
5  X  2  =  10
5  X  3  =  15
5  X  4  =  20
5  X  5  =  25
5  X  6  =  30
5  X  7  =  35
5  X  8  =  40
5  X  9  =  45
5  X  10  =  50

Method #2: Using Recursion (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number and 1 as the arguments to the Mult_table_num function.
  • Create a recursive function to say Mult_table_num which takes the given number and k as the arguments and returns the multiplication table of the given number using recursion.
  • Print the given number multiplied by k.
  • Check if the k value is less than 10 using the if conditional statement.
  • If the statement is true, then pass the given number and k+1 value as the arguments to the Mult_table_num function.{Recursive Logic}
  • Print the multiplication table of the given number using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say Mult_table_num which takes the given number and k
# as the arguments and returns the multiplication table of the given number
# using recursion.


def Mult_table_num(gven_numb, k):
  # Print the given number multiplied by k.
    print(gven_numb, " X ", k, " = ", gven_numb * k)
    # Check if the k value is less than 10 using the if conditional statement.
    if (k < 10):
      # If the statement is true, then pass the given number and k+1 value as the arguments
      # to the Mult_table_num function.{Recursive Logic}
        Mult_table_num(gven_numb, k + 1)


# Give the number as user input using the int(input()) function and
# store it in a variable.
gven_numb = int(input("Enter some Random Number = "))
# Print the multiplication table of the given number using recursion.
print("The Multiplication Table of the above given number ", gven_numb, ":")
# Pass the given number and 1 as the arguments to the Mult_table_num function.
Mult_table_num(gven_numb, 1)

Output:

Enter some Random Number = 10
The Multiplication Table of the above given number 10 :
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100

The best way to learn Python for Beginners is to practice as much as they can taking help of the Sample Python Programs For Beginners. Using them you can develop code on your own and master coding skills.

Python Program to Print Multiplication Table using Recursion Read More »

Program to Find Sum of Even Numbers Using Recursion in a ListArray

Python Program to Find Sum of Even Numbers Using Recursion in a List/Array

In the previous article, we have discussed Python Program to Find Maximum and Minimum Elements in List/Array Using Recursion

Given a list and the task is to find the sum of even numbers using recursion in a given list in python.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given List = [1, 6, 3, 7, 8, 4]

Output:

The Sum of Even Elements in a given list [1, 6, 3, 7, 8, 4] = 18

Example2:

Input:

Given List = [14, 10, 2, 5, 8, 1, 4]

Output:

The Sum of Even Elements in a given list [14, 10, 2, 5, 8, 1, 4] = 38

Program to Find Sum of Even Numbers Using Recursion in a List/Array in Python

Below are the ways to find the sum of even numbers using recursion in a given list in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given list and length of the given list as the arguments to the evenelemt_sum function.
  • Create a recursive function to say evenelemt_sum which takes the given list and length of the given list as the arguments and returns the sum of even numbers in a given list using recursion.
  • Make the rslt_sum a global declaration.
  • Check if the length of the given list is greater than 0 using the if conditional statement.
  • If the statement is true, then subtract 1 from the length of the given list and store it in a variable k.
  • Check if the element present at the index k of the given list is even using modulus operator and if conditional statement.
  • If the statement is true, add the element present at the index k of the given list to the above-initialized rslt_sum.
  • Store it in the same variable.
  • Pass the given list and k value as the arguments to the evenelemt_sum function.{Recursive Logic}
  • Return rslt_sum.
  • Print the sum of even numbers in the above-given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say evenelemt_sum which takes the given list and length
# of the given list as the arguments and returns the sum of even numbers in a given list
# using recursion.


def evenelemt_sum(gven_lst, len_lst):
    # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the length of the given list is greater than 0 using the if conditional
    # statement.
    if(len_lst > 0):
        # If the statement is true, then subtract 1 from the length of the given list and
        # store it in a variable k.
        k = len_lst-1
   # Check if the element present at the index k of the given list is even using modulus
   # operator and if conditional statement.
        if(gven_lst[k] % 2 == 0):
            # If the statement is true, add the element present at the index k of the
            # given list to the above-initialized rslt_sum.
            # Store it in the same variable.
            rslt_sum = rslt_sum+gven_lst[k]
           # Pass the given list and k value as the arguments to the evenelemt_sum function
           # {Recursive Logic}.
        evenelemt_sum(gven_lst, k)
       # Return rslt_sum.
    return rslt_sum


# Give the list as static input and store it in a variable.
gven_lst = [1, 6, 3, 7, 8, 4]
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Pass the given list and length of the given list as the arguments to the evenelemt_sum
# function.
# Print the sum of even numbers in the above-given list.
print("The Sum of Even Elements in a given list",
      gven_lst, "=", evenelemt_sum(gven_lst, len_lst))

Output:

The Sum of Even Elements in a given list [1, 6, 3, 7, 8, 4] = 18

Method #2: Using Recursion (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Pass the given list and length of the given list as the arguments to the evenelemt_sum function.
  • Create a recursive function to say evenelemt_sum which takes the given list and length of the given list as the arguments and returns the sum of even numbers in a given list using recursion.
  • Make the rslt_sum a global declaration.
  • Check if the length of the given list is greater than 0 using the if conditional statement.
  • If the statement is true, then subtract 1 from the length of the given list and store it in a variable k.
  • Check if the element present at the index k of the given list is even using modulus operator and if conditional statement.
  • If the statement is true, add the element present at the index k of the given list to the above-initialized rslt_sum.
  • Store it in the same variable.
  • Pass the given list and k value as the arguments to the evenelemt_sum function.{Recursive Logic}
  • Return rslt_sum.
  • Print the sum of even numbers in the above-given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say evenelemt_sum which takes the given list and length
# of the given list as the arguments and returns the sum of even numbers in a given list
# using recursion.


def evenelemt_sum(gven_lst, len_lst):
    # Make the rslt_sum a global declaration.
    global rslt_sum
    # Check if the length of the given list is greater than 0 using the if conditional
    # statement.
    if(len_lst > 0):
        # If the statement is true, then subtract 1 from the length of the given list and
        # store it in a variable k.
        k = len_lst-1
   # Check if the element present at the index k of the given list is even using modulus
   # operator and if conditional statement.
        if(gven_lst[k] % 2 == 0):
            # If the statement is true, add the element present at the index k of the
            # given list to the above-initialized rslt_sum.
            # Store it in the same variable.
            rslt_sum = rslt_sum+gven_lst[k]
           # Pass the given list and k value as the arguments to the evenelemt_sum function
           # {Recursive Logic}.
        evenelemt_sum(gven_lst, k)
       # Return rslt_sum.
    return rslt_sum


# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gven_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Pass the given list and length of the given list as the arguments to the evenelemt_sum
# function.
# Print the sum of even numbers in the above-given list.
print("The Sum of Even Elements in a given list",
      gven_lst, "=", evenelemt_sum(gven_lst, len_lst))

Output:

Enter some random List Elements separated by spaces = 14 10 2 5 8 1 4
The Sum of Even Elements in a given list [14, 10, 2, 5, 8, 1, 4] = 38

Enhance your coding skills with our list of Python Basic Programs provided and become a pro in the general-purpose programming language Python in no time.

Python Program to Find Sum of Even Numbers Using Recursion in a List/Array Read More »

Program to Find Maximum and Minimum Elements in ListArray Using Recursion

Python Program to Find Maximum and Minimum Elements in List/Array Using Recursion

In the previous article, we have discussed Python Program For Division Two Numbers Operator Without Using Division(/) Operator

Given a list and the task is to find the maximum and minimum elements in a given List using recursion in python

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given List = [1, 6, 3, 7, 8, 4]

Output:

The Maximum element in a given list [1, 6, 3, 7, 8, 4] = 8
The Minimum element in a given list [1, 6, 3, 7, 8, 4] = 1

Example2:

Input:

Given List = [20, 30, 40, 10, 50]

Output:

The Maximum element in a given list [20, 30, 40, 10, 50] = 50
The Minimum element in a given list [20, 30, 40, 10, 50] = 10

Program to Find Maximum and Minimum Elements in List/Array Using Recursion in Python

Below are the ways to find the maximum and minimum elements in a given List using recursion in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Pass the given list and length of the given list as the arguments to the max_elemnt, min_elemnt functions.
  • Create a recursive function to say max_elemnt which takes the given list and length of the given list as the arguments and returns the maximum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return maximum of (gven_lst[len_lst – 1], max_elemnt(gven_lst, len_lst – 1) {Recursive logic}.
  • Create a recursive function to say min_elemnt which takes the given list and length of the given list as the arguments and returns the minimum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1) {Recursive logic}.
  • Print the maximum element of the given list.
  • Print the minimum element of the given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say max_elemnt which takes the given list and
# length of the given list as the arguments and returns the maximum element in a
# given list using recursion.


def max_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
     # Return maximum of (gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1)
     # {Recursive logic}.
    return max(gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1))

# Create a recursive function to say min_elemnt which takes the given list and
# length of the given list as the arguments and returns the minimum element in a
# given list using recursion.


def min_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
    # Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1)
    # {Recursive logic}.
    return min(gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1))


# Give the list as static input and store it in a variable.
gven_lst = [1, 6, 3, 7, 8, 4]
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Pass the given list and length of the given list as the arguments to the max_elemnt,
# min_elemnt functions.
# Print the maximum element of the given list.
print("The Maximum element in a given list",
      gven_lst, "=", max_elemnt(gven_lst, len_lst))
# Print the minimum element of the given list.
print("The Minimum element in a given list",
      gven_lst, "=", min_elemnt(gven_lst, len_lst))

Output:

The Maximum element in a given list [1, 6, 3, 7, 8, 4] = 8
The Minimum element in a given list [1, 6, 3, 7, 8, 4] = 1

Method #2: Using Recursion (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list and store it in another variable.
  • Pass the given list and length of the given list as the arguments to the max_elemnt, min_elemnt functions.
  • Create a recursive function to say max_elemnt which takes the given list and length of the given list as the arguments and returns the maximum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return maximum of (gven_lst[len_lst – 1], max_elemnt(gven_lst, len_lst – 1) {Recursive logic}.
  • Create a recursive function to say min_elemnt which takes the given list and length of the given list as the arguments and returns the minimum element in a given list using recursion.
  • Check if the length of the given list is 1 using the if conditional statement.
  • If the statement is true, then return the first element of the list.
  • Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1) {Recursive logic}.
  • Print the maximum element of the given list.
  • Print the minimum element of the given list.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say max_elemnt which takes the given list and
# length of the given list as the arguments and returns the maximum element in a
# given list using recursion.


def max_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
     # Return maximum of (gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1)
     # {Recursive logic}.
    return max(gven_lst[len_lst - 1], max_elemnt(gven_lst, len_lst - 1))

# Create a recursive function to say min_elemnt which takes the given list and
# length of the given list as the arguments and returns the minimum element in a
# given list using recursion.


def min_elemnt(gven_lst, len_lst):
  # Check if the length of the given list is 1 using the if conditional statement.
    if len_lst == 1:
      # If the statement is true, then return the first element of the list.
        return gven_lst[0]
    # Return minimum of (gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1)
    # {Recursive logic}.
    return min(gven_lst[len_lst-1], min_elemnt(gven_lst, len_lst-1))



# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gven_lst = list(map(int, input( 'Enter some random List Elements separated by spaces = ').split()))
# Calculate the length of the given list and store it in another variable.
len_lst = len(gven_lst)
# Pass the given list and length of the given list as the arguments to the max_elemnt,
# min_elemnt functions.
# Print the maximum element of the given list.
print("The Maximum element in a given list",
      gven_lst, "=", max_elemnt(gven_lst, len_lst))
# Print the minimum element of the given list.
print("The Minimum element in a given list",
      gven_lst, "=", min_elemnt(gven_lst, len_lst))

Output:

Enter some random List Elements separated by spaces = 20 30 40 50 10
The Maximum element in a given list [20, 30, 40, 50, 10] = 50
The Minimum element in a given list [20, 30, 40, 50, 10] = 10

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 Maximum and Minimum Elements in List/Array Using Recursion Read More »

Program For Division Two Numbers Operator Without Using Division() Operator

Python Program For Division Two Numbers Operator Without Using Division(/) Operator

In the previous article, we have discussed Python Program to Subtract Two Numbers Without Using Minus(-) Operator

Given two numbers and the task is to find the division of given two numbers without using Division(/)  Operator in python.

Examples:

Example1:

Input:

Given First Number = 400
Given Second Number = 200

Output:

The Division of above given two numbers{ 400 / 200 } =2

Example2:

Input:

Given First Number = 75
Given Second Number = 15

Output:

The Division of above given two numbers{ 75 / 15 } =5

Program For Division Two Numbers Operator Without Using Division(/) Operator in Python

Below are the ways to find the division of given two numbers without using the division(/) operator in python:

Method #1: Using While Loop (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Take a variable say rslt_divsn and initialize its value to 0.
  • Loop until the given first number is greater than or equal to the given second number using the while loop.
  • Inside the loop, subtract the second number from the given first number and store the result in the first number.
  • Increment the value of the above-initialized variable rslt_divsn by 1 and store it in the same variable.
  • Print rslt_divsn to get the division of given two numbers without using the division(/) operator.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
fst_numb = 400
# Give the second number as static input and store it in another variable.
scnd_numb = 200
# Take a variable say rslt_divsn and initialize its value to 0.
rslt_divsn = 0
print("The Division of above given two numbers{",
      fst_numb, "/", scnd_numb, "} =", end="")
# Loop until the given first number is greater than or equal to the given second
# number using the while loop.
while fst_numb >= scnd_numb:
    # Inside the loop, subtract the second number from the given first number and store
    # the result in the first number.
    fst_numb = fst_numb-scnd_numb
    # Increment the value of the above-initialized variable rslt_divsn by 1 and store it in
    # the same variable.
    rslt_divsn += 1
# Print rslt_divsn to get the division of given two numbers without using the division(/)
# operator.
print(rslt_divsn)

Output:

The Division of above given two numbers{ 400 / 200 } =2

Method #2: Using While loop (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Take a variable say rslt_divsn and initialize its value to 0.
  • Loop until the given first number is greater than or equal to the given second number using the while loop.
  • Inside the loop, subtract the second number from the given first number and store the result in the first number.
  • Increment the value of the above-initialized variable rslt_divsn by 1 and store it in the same variable.
  • Print rslt_divsn to get the division of given two numbers without using the division(/) operator.
  • The Exit of the Program.

Note: If you want to get the result in float format give float in place if int.

Below is the implementation:

# Give the first number as user input using the int(input()) function and
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and
# store it in another variable.
scnd_numb = int(input("Enter some random number = "))
# Take a variable say rslt_divsn and initialize its value to 0.
rslt_divsn = 0
print("The Division of above given two numbers{",
      fst_numb, "/", scnd_numb, "} =", end="")
# Loop until the given first number is greater than or equal to the given second
# number using the while loop.
while fst_numb >= scnd_numb:
    # Inside the loop, subtract the second number from the given first number and store
    # the result in the first number.
    fst_numb = fst_numb-scnd_numb
    # Increment the value of the above-initialized variable rslt_divsn by 1 and store it in
    # the same variable.
    rslt_divsn += 1
# Print rslt_divsn to get the division of given two numbers without using the division(/)
# operator.
print(rslt_divsn)

Output:

Enter some random number = 450
Enter some random number = 15
The Division of above given two numbers{ 450 / 15 } =30

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 For Division Two Numbers Operator Without Using Division(/) Operator Read More »

Program to Subtract Two Numbers Without Using Minus(-) Operator

Python Program to Subtract Two Numbers Without Using Minus(-) Operator

In the previous article, we have discussed Python Program to Multiply Two Numbers Without Using Multiplication(*) Operator

Given two numbers and the task is to subtract the given two numbers without using the minus(*) Operator in python.

Two’s Complement:

The negative of a binary integer, which is obtained by changing all ones to zeros and then adding one to the result.

Examples:

Example1:

Input:

Given First Number = 1500
Given Second Number = 700

Output:

The Subtraction of above given two numbers{ 1500 - 700 } = 800

Example2:

Input:

Given First Number = 400
Given Second Number = 200

Output:

The Subtraction of above given two numbers{ 400 - 200 } = 200

Program to Subtract Two Numbers Without Using Minus(-) Operator in Python

Below are the ways to subtract the given two numbers without using the minus(*) Operator in python:

Method #1: Using 2’s Complement Method (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Calculate the two’s complement of the given second number using the complement (~) operator.
  • Store it in another variable.
  • Add the above result to the given first number and store it in another variable.
  • Print the subtraction of the given two numbers without using the minus(*) Operator.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
fst_numb = 1500
# Give the second number as static input and store it in another variable.
scnd_numb = 700
# Calculate the two's complement of the given second number using the complement (~)
# operator.
# Store it in another variable.
twos_complemnt = (~scnd_numb+1)
# Add the above result to the given first number and store it in another variable.
rslt_subtctn = fst_numb+twos_complemnt
# Print the subtraction of the given two numbers without using the minus(*) Operator.
print("The Subtraction of above given two numbers{",
      fst_numb, "-", scnd_numb, "} =", rslt_subtctn)

Output:

The Subtraction of above given two numbers{ 1500 - 700 } = 800

Method #2: Using 2’s Complement Method (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Calculate the two’s complement of the given second number using the complement (~) operator.
  • Store it in another variable.
  • Add the above result to the given first number and store it in another variable.
  • Print the subtraction of the given two numbers without using the minus(*) Operator.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as user input using the int(input()) function and
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and
# store it in another variable.
scnd_numb = int(input("Enter some random number = "))
# Calculate the two's complement of the given second number using the complement (~)
# operator.
# Store it in another variable.
twos_complemnt = (~scnd_numb+1)
# Add the above result to the given first number and store it in another variable.
rslt_subtctn = fst_numb+twos_complemnt
# Print the subtraction of the given two numbers without using the minus(*) Operator.
print("The Subtraction of above given two numbers{",
      fst_numb, "-", scnd_numb, "} =", rslt_subtctn)

Output:

Enter some random number = 600
Enter some random number = 100
The Subtraction of above given two numbers{ 600 - 100 } = 500

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

Python Program to Subtract Two Numbers Without Using Minus(-) Operator Read More »

Program to Multiply Two Numbers Without Using Multiplication() Operator

Python Program to Multiply Two Numbers Without Using Multiplication(*) Operator

In the previous article, we have discussed Python Program to Swap Two Numbers using Bitwise Operators

Given two numbers and the task is to multiply the given two numbers without using multiplication(*) Operator

Examples:

Example1:

Input:

Given First Number = 3
Given Second Number = 6

Output:

The multiplication of given two numbers{ 3 * 6 } =  18

Example2:

Input:

Given First Number =  15
Given Second Number = 4

Output:

The multiplication of given two numbers{ 15 * 4 } =  60

Program to Multiply Two Numbers Without Using Multiplication(*) Operator in Python

Below are the ways to multiply the given two numbers without using multiplication(*) Operator in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Loop from 1 to the given first number using the for loop.
  • Inside the loop, add the given second number to the above-initialized variable rslt_sum and store it in the same variable rslt_sum.
  • Print the variable rslt_sum to get the multiplication of given two numbers without using the multiplication(*) Operator.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
fst_numb = 3
# Give the second number as static input and store it in another variable.
scnd_numb = 6
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Loop from 1 to the given first number using the for loop.
for itr in range(1, fst_numb+1):
    # Inside the loop, add the given second number to the above-initialized variable
    # rslt_sum and store it in the same variable rslt_sum.
    rslt_sum = rslt_sum+scnd_numb
# Print the variable rslt_sum to get the multiplication of given two numbers without
# using the multiplication(*) Operator.
print("The multiplication of given two numbers{",
      fst_numb, "*", scnd_numb, "} = ", rslt_sum)

Output:

The multiplication of given two numbers{ 3 * 6 } =  18

Method #2: Using For loop (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Take a variable say rslt_sum and initialize its value to 0.
  • Loop from 1 to the given first number using the for loop.
  • Inside the loop, add the given second number to the above-initialized variable rslt_sum and store it in the same variable rslt_sum.
  • Print the variable rslt_sum to get the multiplication of given two numbers without using the multiplication(*) Operator.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as user input using the int(input()) function and
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and
# store it in another variable.
scnd_numb = int(input("Enter some random number = "))
# Take a variable say rslt_sum and initialize its value to 0.
rslt_sum = 0
# Loop from 1 to the given first number using the for loop.
for itr in range(1, fst_numb+1):
    # Inside the loop, add the given second number to the above-initialized variable
    # rslt_sum and store it in the same variable rslt_sum.
    rslt_sum = rslt_sum+scnd_numb
# Print the variable rslt_sum to get the multiplication of given two numbers without
# using the multiplication(*) Operator.
print("The multiplication of given two numbers{",
      fst_numb, "*", scnd_numb, "} = ", rslt_sum)

Output:

Enter some random number = 15
Enter some random number = 4
The multiplication of given two numbers{ 15 * 4 } = 60

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 Multiply Two Numbers Without Using Multiplication(*) Operator Read More »

Program to Swap Two Numbers using Bitwise Operators

Python Program to Swap Two Numbers using Bitwise Operators

In the previous article, we have discussed Python Program to Check Even or Odd Using Bitwise Operator

Given two numbers and the task is to swap the given two numbers using Bitwise Operators.

Bitwise XOR operation:

Sets each bit to 1 if only one of two bits is 1

Examples:

Example1:

Input:

Given First Number= 35
Given Second Number = 20

Output:

The Result After Swapping  given two Numbers is:
First Number =  20
Second Number =  35

Example2:

Input:

Given First Number= 54
Given Second Number = 10

Output:

The Result After Swapping given two Numbers is:
First Number = 10 
Second Number = 54

Program to Swap Two Numbers using Bitwise Operators in Python

Below are the ways to swap the given two numbers using Bitwise Operators in Python:

Method #1: Using Bitwise XOR Operator (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Apply bitwise ^ operator on the first and second numbers and store it in the first number.
  • Again apply the bitwise ^ operator on the first and second numbers and store it in the second number.
  • Apply bitwise ^ operator on the first and second numbers and store it in the first number.
  • Print the given numbers after swapping.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
fst_numb = 54
# Give the second number as static input and store it in another variable.
scnd_numb = 10
# Apply bitwise ^ operator on the first and second numbers and store it in the
# first number.
fst_numb = fst_numb ^ scnd_numb
# Again apply the bitwise ^ operator on the first and second numbers and store it in the
# second number.
scnd_numb = fst_numb ^ scnd_numb
# Apply bitwise ^ operator on the first and second numbers and store it in the
# first number.
fst_numb = fst_numb ^ scnd_numb
# Print the given numbers after swapping.
print("The Result After Swapping  given two Numbers is:")
print("First Number = ", fst_numb)
print("Second Number = ", scnd_numb)

Output:

The Result After Swapping  given two Numbers is:
First Number =  10
Second Number =  54

Method #2: Using Bitwise XOR Operator (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Apply bitwise ^ operator on the first and second numbers and store it in the first number.
  • Again apply the bitwise ^ operator on the first and second numbers and store it in the second number.
  • Apply bitwise ^ operator on the first and second numbers and store it in the first number.
  • Print the given numbers after swapping.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as user input using the int(input()) function and
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and
# store it in another variable.
scnd_numb = int(input("Enter some random number = "))
# Apply bitwise ^ operator on the first and second numbers and store it in the
# first number.
fst_numb = fst_numb ^ scnd_numb
# Again apply the bitwise ^ operator on the first and second numbers and store it in the
# second number.
scnd_numb = fst_numb ^ scnd_numb
# Apply bitwise ^ operator on the first and second numbers and store it in the
# first number.
fst_numb = fst_numb ^ scnd_numb
# Print the given numbers after swapping.
print("The Result After Swapping  given two Numbers is:")
print("First Number = ", fst_numb)
print("Second Number = ", scnd_numb)

Output:

Enter some random number = 45
Enter some random number = 65
The Result After Swapping given two Numbers is:
First Number = 65
Second Number = 45

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 Swap Two Numbers using Bitwise Operators Read More »