Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- [invert_array.c]
- Author : Alessandro Suglia ( alessandro.suglia@gmail.com )
- Date : 10/17/2011 15:37
- Simple program which shows how to manage a structured
- data type like the array. It asks to the user the size of
- the array, asks to fill it with n values, and then prints
- them to the video, firstly in the inserting order and,
- afterthat, inverted.
- */
- /* <------------- Header declaration -------------------- > */
- #include <stdio.h>
- #include <stdlib.h>
- /* <-------------- Useful Macros and define --------------> */
- #define LEN(x) sizeof(x)/sizeof(int)
- #define PRINT_ARRAY(x, n) for ( i = 0; i < n; i++ ) printf("%d)\t%d\n", i+1, x[i])
- /* < ------------- Functions' prototype declaration ------> */
- void get_array( int [], int );
- void invert_array( int [], int );
- void swap( int *, int * );
- /* <--------------- main() function ----------------------> */
- int main()
- {
- int *num;
- int n = 0;
- int i = 0;
- printf("::::::: INVERT ARRAY :::::::::::\n\n");
- printf("What's the array's size?\n");
- scanf("%d", &n);
- if ( n < 0 ) /* Check the size of the array inserted by the user, if it's negative, exit*/
- {
- perror("Nothing to be done with an array with negative size!!\n");
- exit(-1);
- }
- else /* Else, allocates memory for the defined array num */
- {
- num = (int*)malloc( n * sizeof(int));
- if ( !(num) ) /* Check for some errors in the dynamic allocation */
- {
- perror("MALLOC ERROR : FATAL!!\n");
- exit(-1);
- }
- get_array( num, n );
- printf("Value inserted in the array : \n");
- PRINT_ARRAY( num, n );
- printf("\n\n");
- printf("Inverted array values : \n");
- invert_array( num, n );
- PRINT_ARRAY( num, n );
- }
- /* Some sort of stuff that I MUST do in order to make the code portable also with linux */
- #ifdef _WIN32
- system("PAUSE");
- #endif
- return EXIT_SUCCESS;
- }
- /* It receives the array and its length and then grants to the user to fill it */
- void get_array( int a[], int len )
- {
- int i;
- printf("Insert %d values : \n", len);
- for ( i = 0; i < len; i++ )
- scanf("%d", &a[i]);
- }
- /* A kinda of function used to swap the value */
- void swap( int *a, int *b )
- {
- int temp = *a;
- *a = *b;
- *b = temp;
- }
- /* Inverts the order of the array's elements */
- void invert_array( int a[], int len )
- {
- int m = len/2;
- int i;
- for ( i = 0; i < m; i++ )
- swap(&a[i], &a[len-1-i]);
- }
Add Comment
Please, Sign In to add comment