I'm trying to print my array but i'm not getting my desired result

Viewed 67

I'm fairly new to programming and was trying to create a program which creates a one dimensional array with random numbers from a certain range and then prints it out. I managed to make a function to create the array but I'm having trouble actually printing out the array I made. I have a general idea of what the problem might be but no clue as to how to fix the code.

Here is the code in question:

#include <iostream>

using namespace std;

int *create(int n)
{
    int *arr = new int [n];
    
    for (int i = 0; i > n; i++)
    {
        arr[i] = rand() % 100;
    }
}

int main ()
{
    int n = 12;
    int *arr = create(n);
    
    cout << "this is the array: ";
    
    for (int i = 0; i > n; i++)
    {
        cout << arr[i] << " ";
    };
    
    delete[] arr;
    
    return 0;
}
4 Answers

There are two errors in your code:

  1. You are not returning your array from create()
  2. Your loop condition is incorrect.

Fixed code:

#include <iostream>

using namespace std;

int *create(int n)
{
    int *arr = new int [n];
    
    for (int i = 0; i < n; i++)
    {
        arr[i] = rand() % 100;
    }
    return arr;
}

int main ()
{
    int n = 12;
    int *arr = create(n);
    
    cout << "this is the array: ";
    
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    };
    
    delete[] arr;
    
    return 0;
}

I dont see how you code compiles.

  1. You are not returning anything from function.
  2. both your loop conditions should be <n

This way is works but your design is very poor, unless you are just learning handling pointers.

#include <iostream>

using namespace std;

int* create(int n)
{
    int* arr = new int[n];

    for (int i = 0; i < n; i++)
    {
        arr[i] = rand() % 100;
    }
    return arr;
}

int main()
{
    int n = 12;
    int* arr = create(n);

    cout << "this is the array: ";

    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    };

    delete[] arr;

    return 0;
}

The only missing part in your code - you are not returning your arr variable from your create function.

int *create(int n)
{
    int *arr = new int [n];
    
    for (int i = 0; i > n; i++)
    {
        arr[i] = rand() % 100;
    }
    return arr;
}

This way it will work:)

You made a mistake in the loop. you used '>' instead of '<' line 22 should be.

for (int i = 0; i < n; i++)

The loop stopped before the first iterations because i=0 was smaller than n=12.

Related