4

For example, in Python, if we take a list as an array it directly prints the whole array for a single line of code. Is there any way, achieving the same thing in the C language?

Dharman
  • 30,962
  • 25
  • 85
  • 135
shubhajit22
  • 125
  • 1
  • 6
  • not really. just use a for loop and printf – dangee1705 Feb 21 '21 at 16:06
  • 2
    Yes, if you use some recursive terminal tail-call for "loop"ing and if your compiler (e.g. [GCC](http://gcc.gnu.org/)...) is good enough to optimize it – Basile Starynkevitch Feb 21 '21 at 16:12
  • it trivially is, if you count e.g. `puts("hello")` (or the same with an explicitly declared `char []`)... – ilkkachu Feb 21 '21 at 16:15
  • @BasileStarynkevitch, ... But if your compiler is good enough to optimize it, it's optimizing it _back into a loop_ (unless the length is short and constant and it just gets unrolled). – Charles Duffy Feb 21 '21 at 17:41
  • Yes. The question is what is a loop: something syntactical (in C: with `for`, `while`, `do` ....) or something semantic (any iteration with a constant-height call stack). – Basile Starynkevitch Feb 21 '21 at 17:53

5 Answers5

16

Short answer

No

Short answer to almost ALL questions on the form "Can you do X as easy in C as Python?"

No

Long answer

It depends on what you mean. Internally, Python also work with loops. It's just hidden from you, and the same goes for all programming languages. If you want to process an array, you will in general need a loop at some level.

So if your question is if there are some predefined functions for printing arrays, the answer is no, provided that the array isn't a string. But it's not difficult to write a custom print function for this. Here is one example that prints it fairly pretty:

void print_int_array(int *arr, size_t size) {
    if (size == 0) {
        printf("[]");
    } else {     
        putchar('[');
        for (int i = 0; i < size - 1; i++)
            printf("%d, ", arr[i]);
        printf("%d]", arr[size - 1]);
    }
}

It's also possible to use recursion, but recursion is basically just a loop in disguise. Here is a recursive version of the above:

void print_int_array_rec(int *arr, size_t size) {
    if (size == 0) {
        putchar(']');
    } else {
        printf("%d", *arr);
        if (size == 1) 
             printf(", ");
        print_int_array_rec(arr + 1, size - 1);
    } 
}

void print_int_array(int *arr, size_t size) {
    putchar('[');
    
    print_int_array_rec(arr, size);
}

But as I said, it's basically just a loop in disguise. At least in this simple case. All loops are typically converted to something like this in assembly:

loop_start:
    // Code

    if(<condition>) goto loop_start

Or with a nested loop:

    loop_start:          <----------------------|
        // Code                                 |
    loop2_start:                <-----------|   |
        // Code                             |   |
        if(<condition>) goto loop2_start ---|   |
        // Code                                 |
        if(<condition>) goto loop_start  -------|

With recursion, these jumps can become more complicated. If you're using complicated recursion the jumps can stop being properly nested. It could cause something like this:

    loop_start:            <--------------|
        // Code                           |
    loop2_start:              <-----------+--|
        // Code                           |  |
        if(<condition>) goto loop_start --|  |
        // Code                              |
        if(<condition>) goto loop2_start ----|

Notice that I switched place on the gotos, so this "loop" is not properly nested. There is no inner and outer loop. This is what is called spaghetti code and the reason goto is frowned upon, because it makes the code very hard to follow. But it does not matter when it's assembly written by the compiler.

So does this snippet count as a loop, although a complicated one? TBH, I'm not sure. But what I DO know is that recursion and regular iteration are equally expressive which means that there is nothing you can compute recursively which you can not compute iteratively and vice versa. Read here for more information.

Some things become MUCH easier to write in a recursive style. For instance, the Ackermann function: How to rewrite Ackermann function in non-recursive style?

klutt
  • 30,332
  • 17
  • 55
  • 95
6

you can use recursion - no loops.

void printarray1(int *array, size_t size, size_t pos)
{
    if(pos < size) {printarray1(array, size, pos + 1); printf("%d%s", array[size - pos - 1], pos ? " ": "");}
}

void printarray(int *array, size_t size)
{
    printf("[");printarray1(array, size, 0);printf("]");
}

int main(void)
{
    int array[] = {1,2,3,4,5,6,7,8,9,10};

    printarray(array, sizeof(array)/sizeof(array[0]));
}

https://godbolt.org/z/Y79xTG

0___________
  • 60,014
  • 4
  • 34
  • 74
4

Ya, we can. If the array size is fixed, for example if the array's size is 6. Then you can print the values like printf(a[0]) to printf(a[5]). If you give the ''n'' value(here n is size of array) as input to user, then you don't know what value will the user give. So in that case you need loop to print the values in array.

Harshan
  • 41
  • 3
  • 1
    I cannot decide if I like this answer or not, because it's obviously not what OP meant. But still, good catch, and good eye for details. Have an upvote! :) – klutt Feb 21 '21 at 16:26
  • Well, actually, your loop-less solution would also work for a variable number of `n`. You only have to add an `if` statement in front of every `printf` statement. However, a loop would of course be the simpler solution. – Andreas Wenzel Feb 21 '21 at 16:32
  • @AndreasWenzel how does it work with if statements? like multiple/nested if statements? – Harshan Feb 25 '22 at 14:40
  • @Harshan: Let's say that the size of the array is `6`, as in your answer. If you know that `n` is `6` and you don't want a loop, then you can simply have 6 `printf` statements, as suggested in your answer. However, if `n` is entered by the user, it can be any value between `0` and `6`. In that case, the first `printf` statement will have to be in an `if ( n >= 1 )` statement, the second `printf` statement will have to be in an `if ( n >= 2 )` statement, etc. These `if` statements don't have to be nested, but they can be nested, so that no unnecessary checks are performed. – Andreas Wenzel Feb 25 '22 at 20:10
  • @AndreasWenzel yeah agree with u it's not necessary to be a nested if statement – Harshan Jul 01 '23 at 18:15
0

if its an array of chars, this way:

char a[] = "abcdefghi";
printf("%.3s", a); // prints -> abc

And if you want to print a variable amount of chars:

char a[] = "abcdefghi";
char fmt[128];
int n = 3;
sprintf(fmt, "%%.%ds", n);
printf(fmt, a); // prints -> abc

Usefull for arrays of chars that do not end in \0

-2

Yes its possible to print an array without loop you have to just use goto statemenet to make a loop and if condition to check

    my:

   if(i<n)
   {
    scanf("%d",&arr[i]);
    i++;
    goto my;
}
else{
    printf(" ");
}
j=0;
to:
    
if(j<n)
{
    printf("%d ",arr[j]);
    j++;
    goto to;
}
else{
    printf(" ");
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 20 '22 at 07:23