c code recursive function to print numbers between two numbers
#include<stdio.h>
void printNumbers(int start, int end) {
if (start > end) {
return;
}
printf("%d ", start);
printNumbers(start + 1, end);
}
int main() {
int start, end;
printf("Enter the starting number: ");
scanf("%d", &start);
printf("Enter the ending number: ");
scanf("%d", &end);
printf("Numbers between %d and %d are: ", start, end);
printNumbers(start, end);
return 0;
}
The above code is a C program that uses a recursive function to print numbers between two given numbers. Here is a step-by-step explanation of how the code works:
The code starts with the inclusion of the standard input/output library
stdio.h
.The
printNumbers
function is defined, which takes two integer parameters:start
andend
. This function is responsible for printing the numbers betweenstart
andend
recursively.Inside the
printNumbers
function, there is a base case check. Ifstart
is greater thanend
, it means we have reached the end of the range, so the function returns without doing anything.If the base case check fails, the code proceeds to the next step, which is printing the current
start
value usingprintf
. The%d
format specifier is used to print an integer.After printing the current
start
value, theprintNumbers
function is called recursively withstart + 1
as the newstart
value. This will print the next number in the range.The
main
function is defined, which is the entry point of the program. It declares two integer variablesstart
andend
.The user is prompted to enter the starting number using
printf
andscanf
functions. The"%d"
format specifier is used to read an integer value from the user and store it in thestart
variable.Similarly, the user is prompted to enter the ending number, which is also stored in the
end
variable.After getting the input from the user, the program prints a message indicating the range of numbers being printed.
Finally, the
printNumbers
function is called with thestart
andend
values provided by the user, and the numbers between the given range are printed recursively.The
main
function returns 0, indicating successful execution of the program.