This is a C-assignment. use void countDownUp(unsigned int k) to write a recursion to count until a certain number down and then immediately back up. For example, if k = 3, the output should be 3 2 1 0 1 2 3. I already wrote a countDown function
void countDown(unsigned int k)
{
printf("%d ", k);
if (k > 0)
countDown(k-1);
}
and also a countUp function. I used this function in my void countDownUp(unsigned int k)function like this:
void countDownUp(unsigned int k)
{
countDown(k);
static int n=0;
if(n < k){
printf("%d ", n+1);
n++;
countDownUp(k);
}
}
The output now is 3 2 1 0 1 3 2 1 0 2 3 2 1 0 3 3 2 1 0I know it doesn't work, but i have no idea how can i adjust it to the right output. Can someone give me some advices? Thank you very much!
There is no need to use a static variable. The function can be written simpler.
#include <stdio.h>
void countDownUp( unsigned int n )
{
printf( "%u ", n );
if ( n )
{
countDownUp( n - 1 );
printf( "%u ", n );
}
}
int main(void)
{
countDownUp( 3 );
return 0;
}
the program output is
3 2 1 0 1 2 3
As for your function implementation
void countDownUp(unsigned int k)
{
countDown(k);
static int n=0;
if(n < k){
printf("%d ", n+1);
n++;
countDownUp(k);
}
}
then the call within the function
countDownUp(k);
anew calls countDown(k); with the same value of k that was passed to the current call of the function countDownUp because within the function the value of k is not changing..
Also you need to specify the conversion specifier %u instead of %d because the variable k has the type unsigned int.
Q: What does CountDownUp() do in the general case?
A: It prints n twice, with the result of CountDownUp(n - 1) in between.
void CountDownUp(int n) {
printf("%d ", n);
CountDownUp(n - 1);
printf("%d ", n);
}
Q: What's the stop condition?
A: When CountDownUp is called with 0.
Q: What do we do then?
A: Print just once and stop recursion.
void CountDownUp(int n) {
printf("%d ", n);
if (n == 0) return;
CountDownUp(n - 1);
printf("%d ", n);
}
Voila!
Related
I wanna create all possible 5 digit numbers that can be created from the numbers (0-7).
The code below achieves this, but is there any way to make this depend on user input?
The number of loops equals the number of digits I want and each individual loop must be:
for(1st number;condition<=last number;1st number++)
So, for five digits, I have:
for(i=0;i<8;i++){
for(j=0;j<8;j++){
for(k=0;k<8;k++){
for(m=0;m<8;m++){
for(n=0;n<8;n++){
printf("%d %d %d %d %d\n",i,j,k,m,n);
}
}
}
}
}
Keep iterators in an array and increment them manually.
#include <assert.h>
#include <stdio.h>
#include <string.h>
void callback(unsigned n, int i[n]) {
assert(n == 5);
printf("%d %d %d %d %d\n", i[0], i[1], i[2], i[3], i[4]);
}
void iterate(unsigned n, unsigned max, void (*callback)(unsigned n, int i[n])) {
// VLA, use *alloc in real code
int i[n];
memset(i, 0, sizeof(i));
while (1) {
for (int j = 0; j < n; ++j) {
// increment first number, from the back
++i[n - j - 1];
// if it didn't reach max, we end incrementing
if (i[n - j - 1] < max) {
break;
}
// if i[0] reached max, return
if (j == n - 1) {
return;
}
// if the number reaches max, it has to be zeroed
i[n - j - 1] = 0;
}
// call the callback
callback(n, i);
}
}
int main() {
// iterate with 5 numbers to max 8
iterate(5, 8, callback);
}
The beginning and ending of what the code prints:
0 0 0 0 0
0 0 0 0 1
...
...
7 7 7 7 6
7 7 7 7 7
If you want variable numbers of loops, you generally need to use recursion.
Say if you want n digits, with the ith digit be in the range of a[i],b[i], then you will do the following:
/* whatever */
int n;
int *a,*b,*number;
void recursion(int whichdigit){
if (whichdigit==n){
/* Say you managed to output number */
return;
}
for (int i=a[whichdigit];i<=b[whichdigit];i++){
number[whichdigit]=i;
recursion(whichdigit+1);
}
return;
}
int main(){
/* Say somehow you managed to obtain n */
a=malloc(n*sizeof(int));
b=malloc(n*sizeof(int));
number=malloc(n*sizeof(int))
if (!a||!b||!number){
/* unable to allocate memory */
}
/* Say somehow you managed to read a[i],b[i] for all i in 0..n-1 */
recursion(0);
return 0;
}
Warning: if you tries to have too many digits, you will likely get a segmentation fault or stack overflow error.
I'm currently working on code that reads in a sequence of integers in the form of m1, n1, m2, n2, until I input a zero, and it prints the sum of m * n. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int m, n, i, sum = 0;
bool plus = true;
scanf("%d", &m);
scanf("%d", &n);
for(i = m; i <= n; i++)
{
sum = sum + (m * n);
if(!plus)
{
putchar('+');
}
printf("%d*%d", m, n);
plus = false;
}
printf("=%d\n", sum);
return 0;
}
If I type in 1, 1, 0, it prints out 1 * 1 = 1, but if I were to type in, 1, 2, 3, 4, 0, it prints out 1*2+1*2=4. I'm just confused on how I get it to calculate 1*2 and 3*4.
you never read the 3rd and 4th arguments as the scanf calls are outside the loop. If you put them and the plus initializtion inside the loop, and correct the loop initilization and termination conditions your code should work (If I am not missing anything else).
I'm currently working on code that reads in a sequence of integers in
the form of m1, n1, m2, n2, until I input a zero
It seems the approach you are using in whole is wrong. You should not enter the variables m and n. At least I do not see where 0 is entered and checked in your code.
What you are doing is calculating
sum = sum + (m * n);
n - m + 1 times in the loop. Because m and n correspondingly were entered like 1 and 2 you got 4 (1 * 2 + 1 * 2).
I can suggest the following approach.
#include <stdio.h>
int main(void)
{
printf( "Enter a sequence of integers (0 - exit): " );
long long int sum = 0;
int value, prev_value;
unsigned int i;
i = 0;
while ( scanf( "%d", &value ) == 1 && value != 0 )
{
if ( i % 2 )
{
if ( i != 1 ) printf( " + " );
printf( " %d * %d ", prev_value, value );
sum += ( long long int )prev_value * value;
}
else
{
prev_value = value;
}
++i;
}
if ( i % 2 )
{
if ( i != 1 ) printf( " + " );
printf( "%d", prev_value );
sum += prev_value;
}
printf( " = %lld\n", sum );
return 0;
}
The program output might look like
Enter a sequence of integers (0 - exit): 1 2 3 4 0
1 * 2 + 3 * 4 = 14
You don't want a for loop like that, as you want to loop an indefinite amount. My recommendation is to use while (true), and break from the loop when you reach the termination condition (or when scanf() fails to read both inputs):
#include <stdio.h>
#include <stdbool.h>
int main()
{
int sum = 0;
char const *plus = "";
while (true)
{
int m, n;
if (scanf("%d%d", &m, &n) != 2)
break;
if (m == 0 || n == 0)
break;
sum += m * n;
printf("%s%d*%d", plus, m, n);
plus = "+";
}
printf("=%d\n", sum);
}
A couple of other improvements in there: I've reduced the scope of m and n to be inside the loop, and I've changed plus to refer to the actual string to insert, rather than indirecting through a boolean.
Arguably, you might want to separate the scanf() back into the two calls you had, so that the terminating 0 need not be paired:
if (scanf("%d", &m) != 1 || m == 0)
break;
if (scanf("%d", &n) != 1 || n == 0)
break;
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sum, m, n;
if (!scanf("%d", &m))
return 0;
while (m)
{
if (!scanf("%d", &n))
return 0;
sum += m * n;
if (!scanf("%d", &m))
return 0;
}
printf("%d", sum);
}
Try this. I wrote it quickly, but it should work. Code also should check if number of arguments is correct (situation when user input is X 0 or X X X 0 etc.). Issues spotted in your code:
User input outside the loop
No scanf() returns check
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;
}