Thread: User input array size!!

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    7

    User input array size!!

    Hi, i have an assignment to do that is: Write a program that asks the users to enter a value for array size “n” and fill up the array with n integers. Then reverse the array and print it on the screen.

    I am not asking for the whole thing to be done for me, but I need help with getting the user to enter the array size. I have this so far

    Code:
    #include <stdio.h>
    int main(void)
    {
        int n;
        printf("Enter size of array\n");
        scanf_s("%d", &n);
    
    
        float array[n];
    
    
        for (int i = 0; i < n; i++) {
            scanf_s("%f", &array[n]);
        }
    
    
        printf("%f", array[n]);
        getchar();
        getchar();
    }

  2. #2
    Registered User
    Join Date
    Feb 2012
    Posts
    347
    You got correctly the data inside the array. Now you can write reverse function by using temporary array and then print the array.

  3. #3
    Registered User
    Join Date
    Apr 2017
    Posts
    7
    This code does not work. It says "n" must have a constant value

  4. #4
    Registered User
    Join Date
    Feb 2012
    Posts
    347
    That is because you have to have fixed array size
    Code:
    float array[100];
    Also the declaration should come at the beginning of function.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You need to write
    float *array = malloc( n * sizeof(*array) ); // synthesise float array[n];

    Don't forget to include stdlib.h

    Also, if you get warnings about casting void*, then stop using a C++ compiler to compile C code, by renaming your source files.


    > scanf_s("%f", &array[n]);
    Also, use i (your loop variable), not n (your array length).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Let The User Specify Array Size
    By c_lover in forum C++ Programming
    Replies: 7
    Last Post: 10-13-2014, 08:04 AM
  2. Replies: 2
    Last Post: 03-05-2012, 10:35 AM
  3. Array size base on user input
    By icoigo in forum C Programming
    Replies: 2
    Last Post: 10-27-2010, 12:28 PM
  4. Size of Array, user inputted..
    By otchster in forum C++ Programming
    Replies: 19
    Last Post: 06-25-2007, 12:50 PM
  5. User input for array size.
    By coolmoniker in forum C++ Programming
    Replies: 27
    Last Post: 08-24-2006, 11:34 PM

Tags for this Thread