Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why this function that print array in reverse doesn't work

I’m trying to make a function that print array in reverse, but it doesn’t work for me.

this is what I wrote (on online C compiler site):

#include <stdio.h>

void print_reversed(int* a)
{
    
    if (a[0]==0) {
        break;
    }
    print_reversed(&a[1]);
    printf("%d", a[0]);
}    
   

int main()
{
    int array [7] = {1, 2, 3, 4, 5, 6, 0};
    print_reversed(&array[0]);
    return 0;
}

0 indicate the end of the array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know there is a problem with the break statement but I don’t know how to solve it.

I know there are other solutions but I need to solve it in that method.

(I’m learning the basic so maybe it stupid question).

thanks a lot!

>Solution :

You are getting this error or similar:

<source>: In function 'print_reversed':
<source>:7:9: error: break statement not within loop or switch
    7 |         break;

As it says, break only works in a loop or a switch statement.

To return from a function, you want return.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading