For example: for n = 5 the result should be: 123454321.
I've managed to do so with 2 functions which will get called one after the other: the first for printing 1 to n, and the second for printing n-1 to 1:
void oneToN(int num)
{
if (num == 1)
printf("%d",num);
else
{
oneToN(num-1);
printf("%d",num);
}
}
void NToOne(int num)
{
if(num >= 2)
{
printf("%d", num - 1);
NToOne(num - 1);
}
}
I was wondering if it's possible with only one recursive function
Yes, it is possible. Here is a general plan on how to deal with recursive problems:
Look for the trivial case when you do not need a recursive invocation
Imagine that you have a function working, and all you need to do is coming up with just one additional step of the function
Here, you would discover a simple pattern: if you have a function that prints 2345432, all you need to do is to print 1s around it. Hence, you need to supply two numbers - the from and the to. When the numbers are the same, you print one copy, and you are done. Otherwise, you print the from, do the recursive call, and print the from again. Done!
123454321 is 1 + 2345432 + 1
2345432 is 2 + 34543 + 2
34543 is 3 + 454 + 3
etc
See the pattern?
The function should print the current number twice, with a recursive call to handle the higher numbers in between.
void f(int n, int i) {
if (i == n) {
printf("%d", i);
} else {
printf("%d", i);
f(n, i + 1);
printf("%d", i);
}
}
This can be simplified by factoring out the leading (or trailing) printf.
void f(int n, int i) {
printf("%d", i);
if (i < n) {
f(n, i + 1);
printf("%d", i);
}
}
I would still use a second (non-recursive) function in practice.
void _f(int n, int i) {
printf("%d", i);
if (i < n) {
_f(n, i + 1);
printf("%d", i);
}
}
void f(int n) {
if (n > 0) {
_f(n, 1);
}
printf("\n");
}
Calling such a function with NToOne(1, 4) should be enough.
#include <stdio.h>
void
NToOne(int num, int max)
{
printf("%d", num);
if(num < max)
NToOne(num + 1, max);
else if (num == max)
printf("%d", num+1);
printf("%d", num);
}
void
print_1_to_n_to_1(int n)
{
NToOne(1, n-1);
}
void
main(void)
{
print_1_to_n_to_1(5);
}
Here's how I do this by using single recursive function.
#include<iostream>
using namespace std;
//Recursive Function
void func(int n,int i){
if(i<=n){
cout<<i;
func(n,++i);
}
if(i<=n)
cout<<i-1;
}
int main(){
int n;
cin>>n;
func(n,1);
return 0;
}
We can easily get that pattern with only one recursive function called 'work'
(https://i.stack.imgur.com/yUzJN.jpg)
Related
I want to generate numbers 1 to 4 in a random fashion using C programming.
I have made provision to print a[0] directly in a while loop and for any further element the program checks whether the new number from a[1] to a[3] is same as any of the previous elements. A function has been created for the same. int checkarray(int *x, int y).
The function checks current element with previous elements one by one by reducing the passed address. If it matches the value it exits the loop by assigning value zero to the condition variable (int apply).
return apply;
In the main program it matches with the int check if check==1, the number is printed or else the loop is repeated.
Problem faced: The number of random numbers generated is varying between 2 and 4.
e.g
2 4
2 4 3
1 3 3 4
etc
Also repetition is there sometimes.
#include <stdio.h>
#include <conio.h>
int checkarray(int *x, int y);
void main() {
int a[4], i = 0, check;
srand(time(0));
while (i < 4) {
a[i] = rand() % 4 + 1;
if (i == 0) {
printf("%d ", a[i]);
i++;
continue;
} else {
check = checkarray(&a[i], i);
}
if (check == 1) {
printf("\n%d ", a[i]);
} else {
continue;
}
i++;
}
getch();
}
int checkarray(int *x, int y) {
int arrcnt = y, apply = 1, r = 1;
while (arrcnt > 0) {
if (*x == *(x - 2 * r)) {
apply = 0;
exit(0);
} else {
arrcnt--;
r++;
continue;
}
}
return apply;
}
Let's look at the checkarray function, which is supposed to check if a number is already present in the array.
It is called this way:
check = checkarray(&a[i], i);
Where a is an array of 4 integers and i is the actual index, so it tries to scan the array backwards looking for any occurrences of a[i]
int checkarray(int *x,int y)
{
int arrcnt=y,apply=1,r=1;
while(arrcnt>0)
{
if(*x==*(x-2*r))
// ^^^ Why? This will cause an out of bounds access.
{
apply = 0;
exit(0); // <-- This ends the program. It should be a 'break;'
}
else
{
arrcnt--;
r++;
continue;
}
}
return apply;
}
Without changing the interface (which is error prone, in my opinion) it could be rewritten as
int check_array(int *x, int y)
{
while ( y )
{
if ( *x == *(x - y) )
return 0;
--y;
}
return 1;
}
Testable here.
There are many other issues which should be addressed, though, so please, take a look to these Q&A too.
Does "n * (rand() / RAND_MAX)" make a skewed random number distribution?
Why do people say there is modulo bias when using a random number generator?
Fisher Yates shuffling algorithm in C
int main() vs void main() in C
Why can't I find <conio.h> on Linux?
Your approach is tedious but can be made to work:
there is no need to special case the first number, just make checkarray() return not found for an empty array.
you should pass different arguments to checkarray(): a pointer to the array, the number of entries to check and the value to search.
you should not use exit(0) to return 0 from checkarray(): it causes the program to terminate immediately.
Here is a modified version:
#include <stdio.h>
#include <conio.h>
int checkarray(int *array, int len, int value) {
int i;
for (i = 0; i < len; i++) {
if (array[i] == value)
return 0;
}
return 1;
}
int main() {
int a[4], i = 0, value;
srand(time(0));
while (i < 4) {
value = rand() % 4 + 1;
if (checkarray(a, i, value)) {
printf("%d ", value);
a[i++] = value;
}
}
printf("\n");
getch();
return 0;
}
I was wondering how to make a function consider a given parameter as a static variable. For example, i tried, without success, to generate hailstone numbers:
#include<stdio.h>
int hailstone(int);
int n; /* n is an extern variable*/
int main(){
hailstone(n);
return 0;
}
int hailstone(int n){
static int m = n; /*not possible because n is not constant*/
if(m % 2 == 0 && m != 1)
hailstone(m /= 2);
else if(m != 1)
hailstone((m *= 3) + 1);
else
exit(0); /*Is the use of exit() correct, in this case?*/
return 0;
}
I would like to use a static variable to elaborate n. Otherwise, each recursive call would operate on the whole parameter n, thus going on endless, never reaching the case base.
Few questions:
Does this idea represent a feasible approach to the problem?
Does this idea represent a reasonable/effective approach to the problem?
Is exit(0) used correctly, in a similar case?
You don't need a static variable for this. Just pass in the new value to operate on and use that. Also, the value 1 is your base case, so check for that to stop the recursion, and print the value of n so you can actually see what's going on.
void hailstone(int n){
printf("n=%d\n", n);
if(n % 2 == 0 && n > 1) {
hailstone(n/2);
} else if(n > 1) {
hailstone((n*3) + 1);
}
}
Given that this function could go on for quite a few iterations, a recursive solution could end up causing a stack overflow. Better to go with an iterative solution:
void hailstone(int n){
while (n > 1) {
printf("n=%d\n", n);
if(n % 2 == 0) {
n = n/2;
} else {
n = (n*3) + 1;
}
}
}
Here's the recursive algorithm for hailstorm, there's no need for static
#include <assert.h>
#include <stdio.h>
void hailstone(unsigned int n)
{
assert(n>0);
printf("%u\n", n);
if ( n == 1 )
return;
if( n & 1 ) {
hailstone(3*n + 1);
}
else {
hailstone(n >> 1);
}
}
int main() {
hailstone(5);
}
I am learning how to apply recursion to arrays.
For example, I usually read arrays itiratively, this way:
void read_array(int *a, int n){
int i;
for(i = 0; i < n; ++i)
scanf("%d", &a[i]);
return;
}
I would like to read an array recursively. I wrote the following function:
void read_array(int *a, int n){
int i = n - 1;
if (n < 0)
return;
else{
if(scanf("%d", &a[n - 1 - i]) == 1){
read_array(a, n - 1);
return;
}
}
}
It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.
Your calculation of the array index is wrong. This line:
if(scanf("%d", &a[n - 1 - i]) == 1){
assumes the initial value of n, but at the same time, you decrease n with every recursion step. That being said, it shouldn't crash but just repeatedly write the first element of a, because with i = n - 1, n - 1 - i is always zero.
The idiomatic way to write such a recursion would be to recurse on i:
void read_array(int *a, int n, int i)
{
if (i < n)
{
if(scanf("%d", &a[i]) == 1)
{
read_array(a, n, i+1);
}
}
}
and call it with the initial value for i, e.g. read_array(a, 10, 0) for reading a 10-element array.
In practice, recursion in C is to be avoided.*
* Functional languages can typically optimize recursion, C just uses the call stack with a lot of overhead.
In this example, the theoretical purpose of recursion for writing a pure function is somewhat defeated with a function returning void. If this is just about learning the principle, the functions actually should return something. You could for example create a functional "list builder":
#include <stdio.h>
#include <stdlib.h>
// place the side effect in a separate function
int getValue(void)
{
// could have `scanf()` here:
return rand();
}
typedef struct List
{
int a[10];
size_t length;
} List;
// non-functional helper to get around limitations of C:
// (if it could initialize result directly with the new values, it would
// be functional)
List listAppend(List list, int val)
{
List result = list;
result.a[result.length++] = val;
return result;
}
// recursive function without side effects:
List buildList(List list, int (*value)())
{
if (list.length >= 10) return list;
return buildList(listAppend(list, value()), value);
}
int main(void)
{
List myList = buildList((List){0}, &getValue);
for (size_t i = 0; i < myList.length; ++i)
{
printf("myList.a[%zu] is %d\n", i, myList.a[i]);
}
}
There is a bug in the function.
As the variable i is initialized the following way
int i = n - 1;
then the second argument in this call
scanf("%d", &a[n - 1 - i])
is evaluated like
scanf("%d", &a[n - 1 - (n - 1)])
that is it is always equal to zero
scanf("%d", &a[0])
As the recursive function is called with the same value of the pointer a then all entered values are assigned to a[0]. All other elements of the array are still uninitialized.
Though this does not serve as a reason for the abnormal execution of the function.
It is possible that there is used a big array and the stack is too small to call the function recursively.
In any case the function can be defined more simply and correctly the following way
size_t read_array( int *a, size_t n )
{
return n && scanf( "%d", a ) == 1 ? 1 + read_array( a + 1, n - 1 ) : 0;
}
Take into account as the input can be interrupted by the user. In this case the function returns the number of initialized elements of the array.
Here is a demonstrative program.
#include <stdio.h>
size_t read_array( int *a, size_t n )
{
return n && scanf( "%d", a ) == 1 ? 1 + read_array( a + 1, n - 1 ) : 0;
}
#define N 10
int main(void)
{
int a[N];
size_t n = read_array( a, N );
for ( size_t i = 0; i < n; i++ ) printf( "%d ", a[i] );
putchar( '\n' );
return 0;
}
If to enter sequence of numbers
0 1 2 3 4 5 6 7 8 9
then the output will be
0 1 2 3 4 5 6 7 8 9
Example:
int read_array_aux(int *i, int *n) {
if (i == n) {
return 0;
}
if (scanf("%d", i) != 1) {
return -1;
}
return read_array_aux(i + 1, n);
}
int read_array_aux2(int *a, size_t i, size_t n) {
if (i == n) {
return 0;
}
if (scanf("%d", a + i) != 1) {
return -1;
}
return read_array_aux2(a, i + 1, n);
}
int read_array(int *a, size_t n) {
return read_array_aux(a, a + n);
// return read_array_aux2(a, 0, n);
}
First, condition n<0 is wrong. Probably this is the cause of segfault.
Also, why even bother about calculating the index? When processing any kind of list recursively it's worth to grasp the concept of head (first element of list) and tail (everything except head) of the list. So, filling an array recursively would be defined as (in pseudo code):
void read_array() {
read_head();
read_tail();
}
What is head? It's the first element of current array. What's the tail? The array starting from next element. So, read_tail is equivalent of read_array, but with the beginning moved forward by one element.
And, finally, to gather everything into one place:
void read_array(int *a, int n) {
if(n<=0) {
return;
} else {
if(scanf("%d", a) == 1) {
read_array(a+1,n-1);
}
}
}
As other answers have mentioned, your handling of n is leading to problems. You can return 0 from the base case of sz == 0, otherwise return the result of the next recursive call, or -1 if scanf() fails. At each recursive call, increment a and decrement sz. The value returned in the calling function should be checked for input errors: 0 on success, -1 on failure.
Note that this is a tail recursion, which should be optimized by most good compilers.
#include <stdio.h>
int read_array(int *a, size_t sz);
int main(void)
{
int arr[5];
puts("Enter array elements:");
if (read_array(arr, 5) != 0) {
fprintf(stderr, "Input error\n");
} else {
for (size_t i = 0; i < 5; i++) {
printf("%8d", arr[i]);
}
putchar('\n');
}
return 0;
}
int read_array(int *a, size_t sz)
{
if (sz == 0 ) {
return 0;
}
if (scanf("%d", a) == 1){
return read_array(a + 1, sz - 1);
} else {
return -1;
}
}
Sample interaction:
Enter array elements:
1 2 3 4 5
1 2 3 4 5
Enter array elements:
1 2 3 x 5
Input error
I'm trying to implement a code that recursively calls itself and prints the given digits in ascending order, i.e. if the number is 5, then the function will print 1 2 3 4 5. I cannot use loops in any way!
void print_ascending(int n)
{
int i = 1;
if(i < n)
{
printf("%d", i);
i++;
print_ascending(n);
}
}
Of course, the problem with this code is it will re-initialize the variable i to 1 every single time and infinitely loop to print 1.
There are also no outside global variables or outside functions allowed!
Try incrementing value of argument, when you call recursive function each time.
void print_ascending(int limit, int current_value)
{
if(current_value < limt)
{
printf("%d ", current_value);
print_ascending(limit, current_value + 1);
}
}
Initially call the function as
print_ascending(5, 1)
Alternatively,
void print_ascending(int n)
{
if(n > 0)
{
print_ascending( n - 1);
printf("%d ", n);
}
}
The function can be defined simply the following way
void print_ascending( unsigned int n )
{
if ( n > 1 ) print_ascending( n - 1 );
printf( "%u ", n );
}
I used type unsigned int instead of int because otherwise you have to consider the case when n can be a negative number.
Gurus,
I want to know how to write a recursive function that prints
1
12
123
1234
...
......
For eg: display(4) should print
1
12
123
1234
Code
#include <stdio.h>
void print(int n)
{
if(n != 0)
{
print(n-1);
printf("\n");
print(n-1);
printf("%d",n);
}
}
int main()
{
print(3);
}
Output
1
12
1
123
Issues
I wanted to write a pure recursive (without any loop) function but unable to filter unwanted prints.
Hope someone will help me out!!!
Update
Thanks all for the answers.From all the comments which were given it seems like we can write one with only recursion and a loop is required.
To define a recursive function, you have to do three things:
Define what the function does. In this case it is printing numbers from 1 up to n.
Define what the recursive call is. What happens the next time around? The easiest way is to think from the bottom up; in this case, on each earlier line, it is printing numbers up to one less than the previous. Therefore, every time you call the function again, you want to call it with one less than the previous number.
Define your stop condition. When should I stop recursing? In this case, once you hit the number 1, this will be your last iteration. This means, we want to call the recursive function until this stop condition is reached - or in other words, while n is greater than 1.
Therefore, we end up with the following algorithm:
function display(n):
if(n > 1):
display(n-1);
print 1..n;
EDIT: OK, I improved my answer with the guidelines of #lc.
void print_recursive(unsigned int num) {
if (num > 1) {
print_recursive(num - 1);
}
for (unsigned int i = 0; i < num; i++) {
printf("%d ", (i + 1));
}
printf("\n");
}
This question is quite old, yet none of the answers answer the actual question, viz. solving the problem in C using recursion only, without explicit loops.
Here is a simple solution obtained by fixing the misunderstanding present in the original code (confusion between two possible functions of "print"). There are no explicit loops.
#include <stdio.h>
void countto(int n)
{
if(n != 0)
{
countto(n-1);
printf("%d",n);
}
}
void triang(int n)
{
if(n != 0)
{
triang(n-1);
printf("\n");
countto(n);
}
}
int main()
{
triang(4);
}
We keep calling PrintIt() with the argument-1 recursively until x < 1. Each call will then return in reverse order when x < 1. At each return we print a line starting at 1 to x.
#include "stdio.h"
void PrintIt( int x )
{
int i;
if( x > 1 )
{
PrintIt( x - 1 );
printf("\n");
}
for( i = 1; i < x+1; i++)
{
printf("%d", i);
}
return;
}
int main(int argc, char *argv[])
{
PrintIt( 4 );
return 0;
}
The recursive function used here is func(int).
Initially the value is passed from the main() program.
The recursion occurs till we reach the exit condition , which is val=0 in this case.
Once we reach that level , we move the penultimate frame a print "1". The same pattern is followed to attain the sequence "1 2". . . "1 2 3 " . . . "1 2 3 4"
int func(int val){
int temp,i;
if( val == 0 )
{
val++;
return val;
}
else
{
val--;
temp=func( val );
for (i=1;i<=temp;i++)
{
printf("%d",i);
}
printf("\n");
temp++;
return temp;
}
}
int main(){
int value=4, result;
result=func(value);
}
Just for fun, here's a purely recursive solution. It's in python, which is practically pseudocode anyway. (Non-pythonic newlines are for clarity).
def loop(max, row=1, col=1):
if col <= row:
print col,
loop(max, row, col+1)
elif row < max:
print "\n",
loop(max, row+1, 1)
else:
print "\n",
#include<stdio.h>
void print_num(int x);
int n;
void main(){
printf("Enter number of lines: ");
scanf("%d",&n);
print_num(1);
}
void print_num(int x){
int i;
for(i=1;i<=x;i++){
printf("%d",i);
}
if(x<n){
printf("\n");
x++;
print_num(x);
}
}
This is simple, right?
void display(int k)
{
if (k < 1) { return; }
display(k-1);
for (int i = 1; i <= k; i++)
{
cout << i;
}
cout << endl;
}
int main()
{
int a = 4;
display(a);
return 0;
}