Author name: Vikram Chiluka

Program to Find the Fibonacci Series Using Recursion

Python Program to Find the Fibonacci Series Using Recursion

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Fibonacci Sequence:

The Fibonacci Sequence is a series of integers named after the Italian mathematician Fibonacci. It is merely a string of numbers that begins with 0 and 1 and is then followed by the addition of the two numbers before it.

Recursion:

If you’re familiar with Python functions, you’ll know that it’s typical for one function to call another. It is also feasible for a function in Python to call itself! A recursive function calls itself, and the process of using a recursive function is known as recursion.

Although it may appear strange for a function to call itself, many sorts of programming challenges are better stated recursively.

Given a number, the task is to find the Fibonacci sequence till the given number using recursion.

Examples:

Example1:

Input:

given number = 23

Output:

The Fibonacci Sequence till the given number 23  = 
Number =  0
Number =  1
Number =  1
Number =  2
Number =  3
Number =  5
Number =  8
Number =  13
Number =  21
Number =  34
Number =  55
Number =  89
Number =  144
Number =  233
Number =  377
Number =  610
Number =  987
Number =  1597
Number =  2584
Number =  4181
Number =  6765
Number =  10946
Number =  17711

Example2:

Input:

given number =13

Output:

Enter some random number = 13
The Fibonacci Sequence till the given number 13 = 
Number = 0
Number = 1
Number = 1
Number = 2
Number = 3
Number = 5
Number = 8
Number = 13
Number = 21
Number = 34
Number = 55
Number = 89
Number = 144

Program to Find the Fibonacci Series Using Recursion

Below are the ways to find the Fibonacci Series using the recursive approach in Python:

1)Using Recursion(Static Input)

Approach:

  • The user must give the number as static input and store it in a variable.
  • Pass the given number as a parameter to the Fibonacci recursive function.
  • The base condition is defined as a value that is less than or equal to 1.
  • Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called recursively with the parameter as the number minus 2.
  • Use a for loop to return the Fibonacci sequence and return the result and print the result.
  • The exit of the program.

Below is the implementation:

# function which finds the fibonacci sequence recursively
def fibonacciRecursion(numb):
  # The base condition is defined as a value that is less than or equal to 1.
    if(numb <= 1):
        return numb
    else:
      # Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called
      # recursively with the parameter as the number minus 2.
        return(fibonacciRecursion(numb-1) + fibonacciRecursion(numb-2))


# The user must give the number as static input and store it in a variable.
numb = 23
print("The Fibonacci Sequence till the given number", numb, ' = ')
# Looping from 1 to given number using for loop
for n in range(numb):
  # passing the iterter value as argument to the recursive function fibonacciRecursion
    print('Number = ', fibonacciRecursion(n))

Output:

The Fibonacci Sequence till the given number 23  = 
Number =  0
Number =  1
Number =  1
Number =  2
Number =  3
Number =  5
Number =  8
Number =  13
Number =  21
Number =  34
Number =  55
Number =  89
Number =  144
Number =  233
Number =  377
Number =  610
Number =  987
Number =  1597
Number =  2584
Number =  4181
Number =  6765
Number =  10946
Number =  17711

In this way, we can print the Fibonacci sequence of the given number using recursion.

2)Using Recursion(User Input)

Approach:

  • The user must give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number as a parameter to the Fibonacci recursive function.
  • The base condition is defined as a value that is less than or equal to 1.
  • Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called recursively with the parameter as the number minus 2.
  • Use a for loop to return the Fibonacci sequence and return the result and print the result.
  • The exit of the program.

Below is the implementation of the above approach:

# function which finds the fibonacci sequence recursively
def fibonacciRecursion(numb):
  # The base condition is defined as a value that is less than or equal to 1.
    if(numb <= 1):
        return numb
    else:
      # Otherwise, call the function recursively with the argument as the number minus 1 plus the function that was called
      # recursively with the parameter as the number minus 2.
        return(fibonacciRecursion(numb-1) + fibonacciRecursion(numb-2))


# The user must give the number as user input using the
# int(input()) function and store it in a variable.
numb = int(input('Enter some random number = '))
print("The Fibonacci Sequence till the given number", numb, ' = ')
# Looping from 1 to given number using for loop
for n in range(numb):
  # passing the iterter value as argument to the recursive function fibonacciRecursion
    print('Number = ',fibonacciRecursion(n))

Output:

Enter some random number = 13
The Fibonacci Sequence till the given number 13 = 
Number = 0
Number = 1
Number = 1
Number = 2
Number = 3
Number = 5
Number = 8
Number = 13
Number = 21
Number = 34
Number = 55
Number = 89
Number = 144

Explanation:

  • The number of terms must be entered by the user and saved in a variable.
  • A recursive function takes the number as a parameter.
  • The number must be less than or equal to one as a starting point.
  • Otherwise, the function is run recursively with the number minus 1 as an input, which is added to the function that is called recursively with the number minus 2.
  • The result is returned, and the Fibonacci sequence is printed using a for statement.
  • In this way, we can print the Fibonacci sequence of the given number using recursion.

Related Programs:

Python Program to Find the Fibonacci Series Using Recursion Read More »

Program to Find the Power of a Number Using Recursion

Python Program to Find the Power of a Number Using Recursion

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Power of a number :

A number’s power (or exponent) aa represents the number of times xx must be multiplied by itself. It is written as a tiny number above and to the right of the base number.

Recursion:

If you’re familiar with Python functions, you’ll know that it’s typical for one function to call another. It is also feasible for a function in Python to call itself! A recursive function calls itself, and the process of using a recursive function is known as recursion.

Although it may appear strange for a function to call itself, many sorts of programming challenges are better stated recursively.

Given a number N and the power of P. The aim is to develop a Python program that uses recursion to find the power of a number with the given base.

Examples:

Example1:

Input:

Enter some random base =8 
Enter some random exponent value = 3

Output:

8 ^ 3 = 512

Example2:

Input:

Enter some random base =17
Enter some random exponent value = 3

Output:

17 ^ 3 = 4913

Program to Find the Power of a Number Using Recursion in Python

Below are the ways to find the power of a number using the recursive approach in Python.

1)Using Recursion(Static Input)

Approach:

  • Give the exponent as static input and store it in a variable.
  • Give the base as static input and store it in another variable.
  • To find the power of a number, pass the given exponent and base as arguments to the recursive function.
  • Give the base condition in the instance where the exponent argument is 1.
  • If the exponent is not equal to 1, return the base multiplied by the function with the parameter’s base and exponent minus 1.
  • Until the exponent value is 1, the function calls itself.
  • The power of the specified base number should be printed using the print() function.
  • Exit of Program

Below is the implementation:

# function which calculates the power of the number recursively
def powerRecursion(given_base, given_exp):
  # Give the base condition in the instance where the exponent argument is 1.
    if(given_exp == 1):
        return(given_base)
    # If the exponent is not equal to 1, return the base multiplied by the function
    # with the parameter's base and exponent minus 1.
    if(given_exp != 1):
      # Until the exponent value is 1, the function calls itself.
        return(given_base*powerRecursion(given_base, given_exp-1))


# Give the base as static input and store it in variable.
given_base = 4
# Enter some random exponent as static input and store it in a variable
given_exp = 11
# passing the given base an exponent as arguments to the recursive function powerRecursion
print(given_base, "^", given_exp, ' = ', powerRecursion(given_base, given_exp))

Output:

4 ^ 11  =  4194304

2)Using Recursion(User Input)

Approach:

  • Give the base as user input using the int(input()) function and store it in a variable.
  • Give some exponent as user input using the int(input()) function and store it in a variable
  • To find the power of a number, pass the given exponent and base as arguments to the recursive function.
  • Give the base condition in the instance where the exponent argument is 1.
  • If the exponent is not equal to 1, return the base multiplied by the function with the parameter’s base and exponent minus 1.
  • Until the exponent value is 1, the function calls itself.
  • The power of the specified base number should be printed using the print() function.
  • Exit of Program

Below is the implementation:

# function which calculates the power of the number recursively
def powerRecursion(given_base, given_exp):
  # Give the base condition in the instance where the exponent argument is 1.
    if(given_exp == 1):
        return(given_base)
    # If the exponent is not equal to 1, return the base multiplied by the function
    # with the parameter's base and exponent minus 1.
    if(given_exp != 1):
      # Until the exponent value is 1, the function calls itself.
        return(given_base*powerRecursion(given_base, given_exp-1))


# Give the base as user input using int(input()) function and store it in a variable.
given_base = int(input("Enter some random base ="))
# Give some exponent as user input using int(input()) function and store it in a variable
given_exp = int(input("Enter some random exponent value = "))
# passing the given base an exponent as arguments to the recursive function powerRecursion
print(given_base, "^", given_exp,' = ',powerRecursion(given_base, given_exp))

Output:

Enter some random base =8
Enter some random exponent value = 3
8 ^ 3 = 512

Explanation:

  • The base and exponential values must be entered by the user.
  • To find the power of a number, the numbers are supplied as arguments to a recursive function.
  • The base condition is that the base number is returned if the exponential power is equal to 1.
  • If the exponential power is not equal to one, the base number multiplied by the power function is called
  • recursively, with the parameters being the base and power minus one.
  • The power calculated will be printed.

Related Programs:

Python Program to Find the Power of a Number Using Recursion Read More »

Program to Find the Sum of the Digits of the Number Recursively

Python Program to Find the Sum of the Digits of the Number Recursively

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

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.

Given a number the task is to calculate the sum of the digits of the given number using recursive approach in Python.

Examples:

Example1:

Input:

Enter some random number = 18627677851

Output:

The total sum of digits off the given number 18627677851 = 58

Example2:

Input:

Enter some random number = 7816833887102099

Output:

The total sum of digits off the given number 7816833887102099 = 80

Program to Find the Sum of the Digits of the Number Recursively

Below are the ways to calculate the sum of the digits of the given number using recursive approach in Python.

1)Using Recursion(Static Input)

Approach:

  • Create a recursive function that accepts a number as an argument.
  • Take a number from the static input and pass it to a recursive function as an argument.
  • Put the base condition in the function that says if the number is zero, return the created list.
  • Otherwise, take each digit and add it to the list.
  • Outside of the function, find the sum of the digits in the list.
  • Print the total sum
  • Exit of program.

Below is the implementation:

# take a empty list
numbList = []
# function which returns count of all the digits of
# the given number using recursive approach.


def sumDigitsRecursion(numb):
    # Put the base condition in the function that says
    # if the number is zero, return the created list.
    if(numb == 0):
        return numbList
    # getting the last digit of the given number using modulus operator
    numdigit = numb % 10
    # appending this digit to numberslist using digit function
    numbList.append(numdigit)
    # passing numb/10 recursively
    sumDigitsRecursion(numb//10)


# give the number as static input
numb = 18627677851
# passing the number to sumDigitsRecursion function to
# calculate the sum of digits recursively
sumDigitsRecursion(numb)
# calculating the sum of list using sum() function.
print('The total sum of digits off the given number', numb, '=', sum(numbList))

Output:

The total sum of digits off the given number 18627677851 = 58

2)Using Recursion(User Input)

Approach:

  • Create a recursive function that accepts a number as an argument.
  • Take a number from the user input by using int(input()) function and pass it to a recursive function as an argument.
  • Put the base condition in the function that says if the number is zero, return the created list.
  • Otherwise, take each digit and add it to the list.
  • Outside of the function, find the sum of the digits in the list.
  • Print the total sum
  • Exit of program.

Below is the implementation:

# take a empty list
numbList = []
# function which returns count of all the digits of
# the given number using recursive approach.


def sumDigitsRecursion(numb):
    # Put the base condition in the function that says
    # if the number is zero, return the created list.
    if(numb == 0):
        return numbList
    # getting the last digit of the given number using modulus operator
    numdigit = numb % 10
    # appending this digit to numberslist using digit function
    numbList.append(numdigit)
    # passing numb/10 recursively
    sumDigitsRecursion(numb//10)


#scan some random number using int(input()) function
numb = int(input('Enter some random number = '))
# passing the number to sumDigitsRecursion function to
# calculate the sum of digits recursively
sumDigitsRecursion(numb)
# calculating the sum of list using sum() function.
print('The total sum of digits off the given number', numb, '=', sum(numbList))

Output:

Enter some random number = 7816833887102099
The total sum of digits off the given number 7816833887102099 = 80

Explanation:

  • A recursive function with a number as an argument is defined.
  • A user-given number is taken and sent as an argument to a recursive function.
  • The base condition of the function is that if the number is zero, the created list is returned.
  • Otherwise, each digit is acquired through the use of a modulus operator and appended to the list.
  • The function is then invoked with the user’s number, and the total of the digits in the list is calculated.
  • The total sum is printed.

Related Programs:

Python Program to Find the Sum of the Digits of the Number Recursively Read More »

Python Program to Reverse a String Using Recursion

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

Recursion in Python:

Python also supports function recursion, which means that a specified function can call itself.

Recursion is a mathematical and programming concept that is widely used. It signifies that a function calls itself. This has the advantage of allowing you to loop through data to obtain a result.

The developer must exercise extreme caution when using recursion since it is quite easy to write a function that never terminates or consumes excessive amounts of memory or computing power. However, when performed correctly, recursion may be a tremendously efficient and mathematically elegant way to programming.

Examples:

Example1:

Input:

given string = btechgeeks

Output:

The modified given string{after reversing} = skeeghcetb

Example2:

Input:

The original given string = aplustopper

Output:

The modified given string{after reversing} = reppotsulpa

Program to Reverse a String Using Recursion in Python

Below are the ways to reverse a given string using recursion in Python.

1)Using Recursion(Static Input)

Approach:

  • Give the string from the user as static input and store it in a variable.
  • We can also use recursion to reverse a string. The process through which a function calls itself in Python is known as recursion.
  • Calculate the length of the given string using the len() function.
  • To begin, we declared the reverseRecursion() function and gave given_string as an input if                len(given_string ) == 1 is used to check the length of the string, which is the fundamental condition of recursion. If the length of the string is 1, the string is returned, otherwise, the function is called recursively.
  • The slice operator will slice the string and concatenate it to the end of the slice string if it anticipates the first character.
  • Finally, it will return the reverse order and print the reversed string.
  • The exit of the program.

Below is the implementation:

# function which accepts the given string as an argument and
# reverse the given string using recursion and return the reversed string


def reverseRecursion(given_string):
   # Calculate the length of the given string using the len() function.
    stringLen = len(given_string)
    # if len(str1) == 1 is used to check the length of the string, which is the fundamental condition of recursion. If                  the length of the string is 1,
    # the string is returned, otherwise, the function is called recursively.
    if stringLen == 1:
        return given_string
    else:
      # The slice operator will slice the string and concatenate it to the end of the
      # slice string if it anticipates the first character.
        return reverseRecursion(given_string[1:]) + given_string[0]


# Give the string from the user as static input and store it in a variable.
givenstring = 'btechgeeks'
# printing the original given string
print('The original given string =', givenstring)
# passing the given string as an argument to the recursive function
# 'reverseRecursion' which reverses the given string.

print('The modified given string{after reversing} = ',
      reverseRecursion(givenstring))

Output:

The original given string = btechgeeks
The modified given string{after reversing} =  skeeghcetb

2)Using Recursion(User Input)

Approach:

  • Scan the given string from the user as user input using the int(input()) function.
  • We can also use recursion to reverse a string. The process through which a function calls itself in Python is known as recursion.
  • Calculate the length of the given string using the len() function.
  • To begin, we declared the reverseRecursion() function and gave given_string as an input if              len(given_string ) == 1 is used to check the length of the string, which is the fundamental condition of recursion. If the length of the string is 1, the string is returned, otherwise, the function is called recursively.
  • The slice operator will slice the string and concatenate it to the end of the slice string if it anticipates the first character.
  • Finally, it will return the reverse order and print the reversed string.
  • The exit of the program.

Below is the implementation:

# function which accepts the given string as an argument and
# reverse the given string using recursion and return the reversed string


def reverseRecursion(given_string):
   # Calculate the length of the given string using the len() function.
    stringLen = len(given_string)
    # if len(str1) == 1 is used to check the length of the string, which is the fundamental condition of recursion. If the length of the string is 1,
    # the string is returned, otherwise, the function is called recursively.
    if stringLen == 1:
        return given_string
    else:
      # The slice operator will slice the string and concatenate it to the end of the
      # slice string if it anticipates the first character.
        return reverseRecursion(given_string[1:]) + given_string[0]


# Scan the given string from the user as user input using the int(input()) function.able.
givenstring = input('Enter some random string = ')
# printing the original given string
print('The original given string =', givenstring)
# passing the given string as an argument to the recursive function
# 'reverseRecursion' which reverses the given string.

print('The modified given string{after reversing} = ',
      reverseRecursion(givenstring))

Output:

Enter some random string = aplustopper
The original given string = aplustopper
The modified given string{after reversing} = reppotsulpa

Related Programs:

Python Program to Reverse a String Using Recursion Read More »

Program to Determine How Many Times a Given Letter Occurs in a String Recursively

Python Program to Determine How Many Times a Given Letter Occurs in a String Recursively

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

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.

Given a string and a character the task is to count the occurrence of the given letter in the string using recursive approach in Python.

Examples:

Example1:

Input:

Enter some random string= btechgeeks
Enter some random character= e

Output:

Priting the count of e in the given string btechgeeks = 3

Example2:

Input:

Enter some random string= symphony 
Enter some random character= y

Output:

Printing the count of y in the given string symphony = 2

Program to Determine How Many Times a Given Letter Occurs in a String Recursively

Below are the ways to count the occurrence of the given letter in the string using recursive approach in Python.

Method #1:Using Recursion(Static Input)

Approach:

  • Give the string and character as static input.
  • Pass the string and the characters to a recursive function as arguments.
  • Pass the fundamental constraint that the string is not empty.
  • If the initial character of the string is the same as the character taken from the user, increment the count.
  • The string is progressed in either direction, and the number of times the letter appears in the string is printed.
  • Exit of program.

Below is the implementation:

# function which returns count of the given character in the string recursively.


def checkCountRecursively(given_string, character):
  # Pass the fundamental constraint that the string is not empty.
    if not given_string:
        return 0
    # If the initial character of the string is the same as the character
    # taken from the user, increment the count.
    elif given_string[0] == character:
        return 1+checkCountRecursively(given_string[1:], character)
    # The string is progressed in either direction, and the number of times
    # the letter appears in the string is printed.
    else:
        return checkCountRecursively(given_string[1:], character)


# given string as static input
given_string = 'btechgeeks'
# given character as static input
given_character = 'e'
# passing the given character and given string to checkCountRecursively function
print('Priting the count of', given_character, 'in the given string',
      given_string, '=', checkCountRecursively(given_string, given_character))

Output:

Priting the count of e in the given string btechgeeks = 3

Method #2:Using Recursion(User Input)

Approach:

  • Scan the string and character as user input using input() function.
  • Pass the string and the characters to a recursive function as arguments.
  • Pass the fundamental constraint that the string is not empty.
  • If the initial character of the string is the same as the character taken from the user, increment the count.
  • The string is progressed in either direction, and the number of times the letter appears in the string is printed.
  • Exit of program.

Below is the implementation:

# function which returns count of the given character in the string recursively.


def checkCountRecursively(given_string, character):
  # Pass the fundamental constraint that the string is not empty.
    if not given_string:
        return 0
    # If the initial character of the string is the same as the character
    # taken from the user, increment the count.
    elif given_string[0] == character:
        return 1+checkCountRecursively(given_string[1:], character)
    # The string is progressed in either direction, and the number of times
    # the letter appears in the string is printed.
    else:
        return checkCountRecursively(given_string[1:], character)


# Scan some random string as user input using input() function.
given_string = input('Enter some random string= ')
# Scan some random character as user input using input() function.
given_character = input('Enter some random character= ')
# passing the given character and given string to checkCountRecursively function
print('Printing the count of', given_character, 'in the given string',
      given_string, '=', checkCountRecursively(given_string, given_character))

Output:

Enter some random string= symphony
Enter some random character= y
Printing the count of y in the given string symphony = 2

Explanation:

  • A string and a character must be entered by the user and stored in distinct variables.
  • The recursive function is given the string and the character as arguments.
  • The basic criterion is that the string is not empty.
  • The count is increased if the first character of the string matches the character taken from the user.
  • The string is updated by passing it back to the method recursively.
  • The number of times the letter appears in the string is displayed.

Related Programs:

Python Program to Determine How Many Times a Given Letter Occurs in a String Recursively Read More »

Program to Determine Whether a Given Number is Even or Odd Recursively

Python Program to Determine Whether a Given Number is Even or Odd Recursively

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

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.

Given a number the task is to check whether the given number is even number or odd number using recursive approach in Python.

Examples:

Example1:

Input:

Enter some random number = 215

Output:

The given number 215 is odd

Example2:

Input:

Enter some random number = 628

Output:

The given number 628 is even

Program to Determine Whether a Given Number is Even or Odd Recursively

Below are the ways to check whether the given number is even or odd recursively :

1)Using Recursion(Static Input)

Approach:

  • Give the number as static input.
  • Pass the number to a recursive function as an argument.
  • Define the base condition as an integer less than two.
  • Otherwise, use the number -2 to invoke the function recursively.
  • Then return the result and determine whether the number is even or odd.
  • The final result should be printed.
  • Exit of program.

Below is the implementation:

# function which returns true if the given number
# is evennum or oddnum using recursoive approach


def checkPrimeRecursion(numb):
  # Defining the base condition as an integer less than two.
    if (numb < 2):
      # Then return the result and determine whether the number is even or odd.
        return (numb % 2 == 0)
    # Otherwise, use the number -2 to invoke the function recursively.
    return (checkPrimeRecursion(numb - 2))


# Give the number as static input.
numb = 729
# passing the given number to checkPrimeRecursion
# if the returned value is true then it is even number
if(checkPrimeRecursion(numb)):
    print("The given number", numb, "is even")
# if the returned value is false then it is odd number
else:
    print("The given number", numb, "is odd")

Output:

The given number 729 is odd

Explanation:

  • User must give the number as static input and store it in  a variable.
  • A recursive function is given the number as an argument.
  • The basic requirement is that the number be less than two.
  • Otherwise, the function is called recursively with a number less than two.
  • The outcome is returned, and an if statement is used to determine whether the integer is odd or even.
  • The final result is printed.

2)Using Recursion(User Input)

Approach:

  • Enter some random number as user input using int(input()) function.
  • Pass the number to a recursive function as an argument.
  • Define the base condition as an integer less than two.
  • Otherwise, use the number -2 to invoke the function recursively.
  • Then return the result and determine whether the number is even or odd.
  • The final result should be printed.
  • Exit of program.

Below is the implementation:

# function which returns true if the given number
# is evennum or oddnum using recursoive approach


def checkPrimeRecursion(numb):
  # Defining the base condition as an integer less than two.
    if (numb < 2):
      # Then return the result and determine whether the number is even or odd.
        return (numb % 2 == 0)
    # Otherwise, use the number -2 to invoke the function recursively.
    return (checkPrimeRecursion(numb - 2))


# Give the number as static input.
numb = int(input('Enter some random number = '))
# passing the given number to checkPrimeRecursion
# if the returned value is true then it is even number
if(checkPrimeRecursion(numb)):
    print("The given number", numb, "is even")
# if the returned value is false then it is odd number
else:
    print("The given number", numb, "is odd")

Output:

Enter some random number = 215
The given number 215 is odd

Related Programs:

Python Program to Determine Whether a Given Number is Even or Odd Recursively Read More »

Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

Python Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

If we examine closely at this problem, we can see that the concept of “loop” is to track some counter value, such as “i=0″ till I = higher”. So, if we aren’t permitted to use loops, how can we track something in Python?
One option is to use ‘recursion,’ however we must be careful with the terminating condition. Here’s a solution that uses recursion to output numbers.

Examples:

Example1:

Input:

Enter some upper limit range = 11

Output:

The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Example2:

Input:

Enter some upper limit range = 28

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Program to Print Numbers in a Range (1,upper) Without Using any Loops/Recursive Approach

Below are the ways to print all the numbers in the range from 1 to upper without using any loops or by using recursive approach.

Method #1:Using Recursive function(Static Input)

Approach:

  • Give the upper limit range using static input.
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = 28
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Method #2:Using Recursive function(User Input)

Approach:

  • Scan the upper limit range using int(input()).
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = int(input('Enter some upper limit range = '))
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

Enter some upper limit range = 11
The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Explanation:

  • The user must enter the range’s top limit.
  • This value is supplied to the recursive function as an argument.
  • The recursive function’s basic case is that number should always be bigger than zero.
  • If the number is greater than zero, the function is called again with the argument set to the number minus one.
  • The number has been printed.
  • The recursion will continue until the number is less than zero.

Python Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion Read More »

Program to Check Whether a String is a Palindrome or not Using Recursion

Python Program to Check Whether a String is a Palindrome or not Using Recursion

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Recursion in Python:

When a function calls itself and loops until it reaches the intended end state, this is referred to as recursion. It is based on the mathematics idea of recursive definitions, which define elements in a set in terms of other members in the set.

Each recursive implementation contains a base case in which the desired state is reached, and a recursive case in which the desired state is not reached and the function enters another recursive phase.

On each step, the behavior in the recursive situation before the recursive function call, the internal self-call, is repeated. Recursive structures are beneficial when a larger problem (the base case) can be solved by solving repeated subproblems (the recursive case) that incrementally advance the program to the base case.
It behaves similarly to for and while loops, with the exception that recursion moves closer to the desired condition, whereas for loops run a defined number of times and while loops run until the condition is no longer met.

In other words, recursion is declarative because you specify the desired state, whereas for/while loops are iterative because you provide the number of repeats.

Strings in Python:

A string is typically a piece of text (sequence of characters). To represent a string in Python, we use ” (double quotes) or ‘ (single quotes).

Examples:

Example1:

Input:

given string = "btechgeeksskeeghcetb"

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

Example2:

Input:

given string = "aplussulpa"

Output:

The given string [ aplussulpa ] is a palindrome

Program to Check Whether a String is a Palindrome or not Using Recursion

Below are the ways to Check Whether a String is a Palindrome or not using the recursive approach in Python:

1)Using Recursion (Static Input)

Approach:

  • Give some string as static input and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some string as static input and store it in a variable.
given_str = 'btechgeeksskeeghcetb'
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

2)Using Recursion (User Input)

Approach:

  • Give some random string as user input using the input() function and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some random string as user input using the input()
# function and store it in a variable.
given_str = input('Enter some random string = ')
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

Enter some random string = aplussulpa
The given string [ aplussulpa ] is a palindrome

Explanation:

  • A string must be entered by the user.
  • A recursive function gets the string as an argument.
  • If the length of the string is less than one, the function returns True.
  • If the end letter is the same as the initial letter, the function is repeated recursively with the argument as the sliced list with the first and last characters removed, otherwise, false is returned.
  • The if statement is used to determine whether the returned value is True or False, and the result is printed.

Related Programs:

Python Program to Check Whether a String is a Palindrome or not Using Recursion Read More »

Python Program to Find Magnitude of a Complex Number

Python Program to Find Magnitude of a Complex Number

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

Using a simple snippet, we can calculate the Magnitude of a Complex Number in Python.
Let us begin by learning the fundamentals of complex numbers in Python.
First, let’s look at how to initialize or declare a complex number in Python.

Complex Number:
By setting a variable to a + bi, we can generate a complex number. In this case, a and b are real numbers.

4+11i

In the above example, the real part(a) is 4 and the imaginary part(b) is 11.
The complex([real][,imaginary]) method can also be used to generate a complex number. Its parameters are the real and imaginary parts, respectively.
If a parameter is not specified, the complex number’s corresponding portion is set to the default value. The default setting is 0.

Example:

cmplxnumber = complex(9,2)

In this application, we will utilize the abs() function to determine the magnitude of a complex number. The method abs() only accepts one argument.
The following is an example of an argument:
1. The Float Number
2. Complex Number
3. Integer
If the number is an integer or a floating-point, abs(number) returns

1. Modulus of the number.
2. The magnitude of the number if it is complex.

Examples:

Example1:

Input:

Given real part = 12
Given imaginary part = 16

Output:

The magnitude of the complex number (12+16j) = 20.0

Example2:

Input:

Given real part = 11
Given imaginary part = 47

Output:

The magnitude of the complex number (11+47j) = 48.27007354458868

Python Program to Find Magnitude of a Complex Number

Below are the ways to find the magnitude of a complex number in Python.

Method #1: Using abs Function (Static Input)

Approach:

  • Give the real part and imaginary part of the complex number as static input and store it in two variables.
  • Using a complex() function convert those two variables into a complex number.
  • Calculate the magnitude of the complex number using the abs() function.
  • Print the magnitude of the complex number.
  • The Exit of the program.

Below is the implementation:

# Give the real part and imaginary part of the complex number
# as static input and store it in two variables.
realnumb = 12
imaginarynumb = 16
# Using a complex() function convert those two variables into a complex number.
complexnumb = complex(realnumb, imaginarynumb)
# Calculate the magnitude of the complex number using the abs() function.
magcomplex = abs(complexnumb)
# Print the magnitude of the complex number.
print('The magnitude of the complex number', complexnumb, '=', magcomplex)

Output:

The magnitude of the complex number (12+16j) = 20.0

Method #2: Using abs Function (User Input)

Approach:

  • Give the real part and imaginary part of the complex number as user input using map(), int(), split().
  • Store it in two variables.
  • Using a complex() function convert those two variables into a complex number.
  • Calculate the magnitude of the complex number using the abs() function.
  • Print the magnitude of the complex number.
  • The Exit of the program.

Below is the implementation:

# Give the real part and imaginary part of the complex number as user input
# using map(), int(), split().
# Store it in two variables.
realnumb, imaginarynumb = map(int, input(
    'Enter real part and complex part of the complex number = ').split())
# Using a complex() function convert those two variables into a complex number.
complexnumb = complex(realnumb, imaginarynumb)
# Calculate the magnitude of the complex number using the abs() function.
magcomplex = abs(complexnumb)
# Print the magnitude of the complex number.
print('The magnitude of the complex number', complexnumb, '=', magcomplex)

Output:

Enter real part and complex part of the complex number = 11 47
The magnitude of the complex number (11+47j) = 48.27007354458868

Related Programs:

Python Program to Find Magnitude of a Complex Number Read More »

Program to Check a number is Narcissistic Number or Not

Python Program to Check a number is Narcissistic Number or Not

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Given a number, the task is to check whether the given number is a Narcissistic Number or Not in Python.

Narcissistic Number:

Narcissistic numbers are a type of number that can be generated by adding the sum of its own digits raised to the power of the number of digits.

Example:

370

Number of digits=3

3*(Number of digits)+7*(Number of digits)+0*(Number of digits)

3^(3)+7^(3)+0^3=370

So it is a Narcissistic Number.

Examples:

Example1:

Input:

Given Number =370

Output:

The given Number { 370 } is a Narcissistic Number

Example2:

Input:

Given Number =371

Output:

The given Number { 371 } is a Narcissistic Number

Program to Check a number is Narcissistic Number or Not in Python

Below are the ways to check whether the given number is a Narcissistic Number or Not in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert this number into list of digits using list(),map(),int(),str() functions.
  • Store it in a variable.
  • Calculate the length of the list using the len() function and store it in a variable say listleng.
  • Take a variable tempo and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Calculate the iterator value^listleng where ^ represents the power operator and store it in a variable.
  • Increment the tempo by the above variable.
  • After the end of For loop check if the tempo value is equal to the given number using the If conditional Statement.
  • If it is true then print the given number as a Narcissistic Number.
  • Else it is not a Narcissistic Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
givennmb = 370
# Convert this number into list of digits using list(),map(),int(),str() functions.
# Store it in a variable.
numbedigis = list(map(int, str(givennmb)))
# Calculate the length of the list using the len() function
# and store it in a variable say listleng.
listleng = len(numbedigis)
# Take a variable tempo and initialize its value to 0.
tempo = 0
# Loop in this digits list using For loop.
for numbrdigit in numbedigis:
        # Calculate the iterator value^listleng where ^ represents
    # the power operator and store it in a variable.
    powevalu = numbrdigit**listleng
    # Increment the tempo by the above variable.
    tempo = tempo+powevalu
# After the end of For loop check if the tempo value is equal
# to the given number using the If conditional Statement.
if(tempo == givennmb):
        # If it is true then print the given number as a Narcissistic Number.
    print('The given Number {', givennmb, '} is a Narcissistic Number')
else:
        # Else it is not a Narcissistic Number.
    print('The given Number {', givennmb, '} is not a Narcissistic Number')

Output:

The given Number { 370 } is a Narcissistic Number

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Convert this number into list of digits using list(),map(),int(),str() functions.
  • Store it in a variable.
  • Calculate the length of the list using the len() function and store it in a variable say listleng.
  • Take a variable tempo and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Calculate the iterator value^listleng where ^ represents the power operator and store it in a variable.
  • Increment the tempo by the above variable.
  • After the end of For loop check if the tempo value is equal to the given number using the If conditional Statement.
  • If it is true then print the given number as a Narcissistic Number.
  • Else it is not a Narcissistic Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
givennmb = int(input('Enter some random number = '))
# Convert this number into list of digits using list(),map(),int(),str() functions.
# Store it in a variable.
numbedigis = list(map(int, str(givennmb)))
# Calculate the length of the list using the len() function
# and store it in a variable say listleng.
listleng = len(numbedigis)
# Take a variable tempo and initialize its value to 0.
tempo = 0
# Loop in this digits list using For loop.
for numbrdigit in numbedigis:
        # Calculate the iterator value^listleng where ^ represents
    # the power operator and store it in a variable.
    powevalu = numbrdigit**listleng
    # Increment the tempo by the above variable.
    tempo = tempo+powevalu
# After the end of For loop check if the tempo value is equal
# to the given number using the If conditional Statement.
if(tempo == givennmb):
        # If it is true then print the given number as a Narcissistic Number.
    print('The given Number {', givennmb, '} is a Narcissistic Number')
else:
        # Else it is not a Narcissistic Number.
    print('The given Number {', givennmb, '} is not a Narcissistic Number')

Output:

Enter some random number = 371
The given Number { 371 } is a Narcissistic Number

Related Programs:

Python Program to Check a number is Narcissistic Number or Not Read More »