Sunday, 15 May 2011

c - Printing Integer array in reverse -


This is a very easy problem for printing integer arrays in reverse order. However whenever I try to print, it ends displaying the value of the garbage. Below is my program.

  #include & lt; Stdio.h & gt; # Include & lt; Conio.h & gt; Int main () {int temp = {'\ 0'}; Integer number [9]; Int i; Int j = 8; Printf ("Enter number 8 \ n"); (I = 0; i & lt; 8; i ++) for {scanf_s ("% d", and number [i], 1); } For (i = 0; i and lt; = j; i ++, j--) {temp = num [i]; Number [i] = number [ja]; Num [j] = temp; } Printf ("\ nNo numbers in reverse \ n"); For (i = 0; i & lt; = 8; i ++) {printf ("% d \ n", number [i]); } _getch (); Return 0; }  

Ask input numbers from 1 to 8 only, it prints the number in reverse, but value before the print is garbage value. I know that I can use to face the situation and if I make the statement, but there is no way to deal with this problem?

There are several logical discrepancies in your program,

You have an array of 9 elements Defined

  int num [9];  

but only for 8 elements

 for  (i = 0; i <8; i ++) {scanf_s ("% D ", and num [ii], 1); }  

Thus the last element of the array with the Essex 8 has not been initiated. However, in the loop, which swaps elements of the array, you can use this unpublished element

  int j = 8; // ... for (i = 0; i & lt; = j; i ++, j--) {temp = num [i]; Number [i] = number [ja]; Num [j] = temp; }  

You do not need to swap its elements in order to output the array to the reverse order.

A program that outputs the array in a reverse order without swapping its elements, it can see the following methods

  #include  

to enter a sequence of numbers

  1 2 3 4 5 6 7 8 9  

Then output will appear

  9 8 7 6 5 4 3 2 1  

If you want to swap elements of the array then the program may look like this

  #include & lt; Stdio.h & gt; # Include & lt; Conio.h & gt; #define N 9 int main (zero) {int num [N]; Int n; Int i; Printf ("Enter% d number \ n", N); N = 0; While (n & lt; n & amp; scf ("% d", and [n]) == 1) N ++; For (i = 0; i & lt; n / 2; i ++) {int tmp = num [i]; Number [i] = number [n - i - 1]; Number [n - ii] 1 = tmp; } Printf ("\ nNo numbers in reverse \ n"); For (i = 0; i & lt; n; i ++) printf ("% d", number [i]); Printf ("\ n"); _getch (); Return 0; }  

If input is similar to above then the output will be

  9 8 7 6 5 4 3 2 1  

No comments:

Post a Comment