PDA

View Full Version : Printing from array function



mmvanbesouw
06-22-2008, 11:19 PM
This program to reverse numbers in an array works, but I would like to make it cleaner by printing the array function rather than using a temp to switch the order. For example, using (int i = size - 1, numPrinted = 0; i >= 0; i--) in the function, then just printing the results where the reverse function is to be. I can't figure this out and I can't find the answer in any book. Any suggestions?

Thank you!

#include <stdio.h>
// Function Declarations
void reverse (int size, int rev );

int main (void)
{
// Local Declarations
int size;
int i;

// Statements
printf("How many numbers do you want to enter? ");
scanf("%d", &size);
int ary[size];
for (i = 0; i < size; i++)
{
printf("Enter number %d: ", i + 1);
scanf("%d", &ary[i]);
}
printf("The numbers you entered, in order are:\n");
for(i = 0; i < size; i++)
printf("%d\n", ary[i]);
reverse(size, ary);
printf("The numbers you entered, in reverse order are:\n");
for(i = 0; i < size; i++)
printf("%d\n", ary[i]);
return 0;
} // main

/* ***************************** reverse ***********************************
This function takes the numbers entered in the main function in the arry
and reverses them.
*/
void reverse (int size, int rev[size])
{
// Local Definitions
int i;
int temp;
int numPrinted;

// Statements
for(numPrinted = size - 1, i = 0; i < numPrinted; i++, numPrinted--)
{
temp = rev[i];
rev[i] = rev[numPrinted];
rev[numPrinted] = temp;
}
return;
}

oracleguy
06-23-2008, 12:01 AM
You can't do this:


printf("How many numbers do you want to enter? ");
scanf("&#37;d", &size);
int ary[size];

You either need to specify a constant for the array size in your program and then use size to control how much of it you use or dynamically allocate the array using malloc.