简体   繁体   中英

How to Add Space in Output

Size of array <=1000 and reverse a array in C programming & problem is in printing.

For example output is:

7654321

I want:

7 6 5 4 3 2 1

The first line take input about the number of elements in the array. The second prints the reverse of the array.

#include <stdio.h>

int main()
{
    int k, i;
    scanf("%d",&k); //no of integers in array
    int a[1000];    //size given in question 
    for(i=0;i<=1000;i++)//accepting input
        scanf("%d",&a[i]);
    for(i=k-1;i>=0;i--)//for reversing string 
        printf("%d",a[i]);//my problem
    //code
    return 0;
}

Apart from your question the program is invalid.

The valid range of indices for the array declared in the program is [0, 1000) . However in this loop

for(i=0;i<=1000;i++)//accepting input
    scanf("%d",&a[i]);

you are trying to access the element with the index equal to 1000 though the array does not have such an element.

If your compiler supports variable length arrays then you could declare an array with the number of elements entered by the user.

In this case the program can look like

#include <stdio.h>

int main( void )
{
    size_t n;

    printf( "Enter the size of an array (0 - exit): " );

    if ( scanf( "%zu", &n ) == 1 && n != 0 )
    {
        int a[n];

        for ( size_t i = 0; i < n; i++ ) scanf( "%d", &a[i] );

        putchar( '\n' );

        for ( size_t i = n; i != 0; i-- ) printf( "%d ", a[i-1] );

        putchar( '\n' );
    }
}

The program output might look like

Enter the size of an array (0 - exit): 10

9 8 7 6 5 4 3 2 1 0 

Pay attention to the call of printf

printf( "%d ", a[i-1] )
         ^^^  

It can be substituted to the following two function calls

for ( size_t i = n; i != 0; i-- ) 
{
    printf( "%d", a[i-1] );
    putchar( ' ' );
}        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM