Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jun 2008
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Printing from array function

    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;
    }

  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Location
    USA
    Posts
    9,074
    Thanks
    1
    Thanked 328 Times in 324 Posts
    You can't do this:

    Code:
    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.
    OracleGuy


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •