[英]How to Add Space in Output
Size of array <=1000 and reverse a array in C programming & problem is in printing.数组大小 <=1000 并在 C 编程中反转数组 & 问题正在打印中。
For example output is:例如输出是:
7654321
7654321
I want:我想要:
7 6 5 4 3 2 1
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)
.程序中声明的数组的有效索引范围是
[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.您试图访问索引等于 1000 的元素,尽管数组没有这样的元素。
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
的调用
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( ' ' );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.