🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
Often in programming, we come across situations where we want to perform a task without using the typical approach. One such task might be printing numbers from 1 to n without using loops. This can be achieved using recursion in Python.
2. Program Overview
1. Define a recursive function to print numbers.
2. Take user input for the value of n.
3. Call the recursive function with n as an argument.
3. Code Program
# Python program to print numbers from 1 to n without using loops
def print_numbers(n):
"""Recursive function to print numbers from 1 to n."""
if n > 0:
print_numbers(n-1)
print(n)
# Taking user input
n = int(input("Enter the value of n: "))
# Calling the recursive function
print_numbers(n)
Output:
(For an input of 5) Enter the value of n: 5 1 2 3 4 5
4. Step By Step Explanation
1. We start by defining a recursive function print_numbers that takes a single argument n.
2. Inside this function, if n is greater than 0, we recursively call print_numbers with n-1 as the argument. This step ensures that the numbers are printed in ascending order.
3. After the recursive call, we print the current value of n.
4. Outside the function, we prompt the user to input a number (the value of n) and call our recursive function with this value.
5. As a result, numbers from 1 to n are printed in sequence. For instance, when the user enters 5, the numbers 1 through 5 are printed as showcased in the output.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment