Understanding the Steps to Store Elements in Reversely Stored

Asked 2 years ago, Updated 2 years ago, 32 views

I created it as follows, but the terminal stopped with the following conditions:

/*
  ex1402.c
*/

# include <stdio.h>

void reverseIntArray(inta[], int size)
{
  inti,t;
  for(i=0;i<size/2;i=i+1){
    /* Replace a[i] and a[size-1-i]*/
    t = a[i];
    a[i] = a[size-1-i];
    a[size-1-i] = t;
  }
}


void readIntArray(inta[], int size)
{
  inti;
  for(i=0;i<size;i=i+1){
    printf("%dth?", i=i+1);
    scanf("%d", & a[i]);
  }
}

void printIntArray(inta[], int size)
{
  inti;
  for(i=0;i<size;i=i+1){
    printf("%d", a[i]);
  }
  printf("\n");
}

int main (void)
{
  int data [100], size;

  printf("n=? ");
  scanf("%d", & size);

  readIntArray(data,size);
  printIntArray(data,size);
  reverseIntArray(data,size);
  printIntArray(data,size);

  return 0;
} 

terminals:

$ccex1402.c
$ ./a.out
n = ?10
Number one? 1

There was no error on the terminal, so I didn't even know where it was wrong.
What should I do?

By the way, it seems that the execution example should be like this.

$./a.out
n = ?10
Number 0? 1
1st? 2nd.
2nd? 3rd.
Third? Four.
4th? 5th?
Number five? Number six.
6th? 7th.
Seventh? Eight.
8th? 9th.
Number nine? Number ten.
1 2 3 4 5 6 7 8 9 10
10  9 8 7 6 5 4 3 2 1

c

2022-09-30 14:20

2 Answers

scanf("%d", & a[i]);

The cause is the scanf() format string, and if you set "%d" to "%d", you will be able to proceed.

If you specify "%d", you may want to leave a space after the number, but one of the many traps in scanf() does not finish typing spaces in the format string until you enter non-blank characters after spaces like 1a will not consume the last


2022-09-30 14:20

for(i=0; i printf("%dth?", i=i+1);

When the last semicolon is present, this for statement loops only this.
If you want to repeat scanf("%d", & a[i]);, delete the semicolon at the end of the for statement.
If possible, surround it with {}.

for(i=0; i printf("%dth?", i=i+1){
    scanf("%d", & a[i]);
}

Like this.


2022-09-30 14:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.