#include<iostream>

using namespace std;

int main()
{

    int len1;
    cout<<"please enter the length of arrayn 1";
    cin>>len1;
    cout<<"creating array now";   
    int *arr1= new int[len1];
    cout<<"please enter the elements now";
    for(int i=0;i<len1;i++)
    {
        cin>>arr1[i];
        cout<<endl;
    }
    return 0;
    cout<<arr1;
    delete [] arr1;
}

In the above code, the program stops execution after the first cin.(i know that the variable needs to be initialized first)
Q1) why do we need to initialize the variable first?? Should it not take some garbage value or NULL?

Recommended Answers

All 4 Replies

You don't need to initialise the variable len1. You set a value before you use it, so that's fine.

I see that your main function returns on line 19, so line 20 and line 21 will never be executed. This seems silly.

Your code compiles and runs fine. The only output after line 13 is a series of endls

Works just fine for me.

even with the return statement moved to the end of the function, the line
cout << arr1;
will not display the array contents. You need to walk through the array, displaying each element's value one at a time.

It is left as an exercise for the OP to explain what is actually displayed with his original output statement.

Declare a pointer in declaration and then use it. e.g

#include<iostream>
using namespace std;
int main()
{
    int len1,*arr1;
    cout<<"please enter the length of arrayn 1";
    cin>>len1;
    cout<<"creating array now";   
    arr1= new int[len1];
    cout<<"please enter the elements now";
    for(int i=0;i<len1;i++)
    {
        cin>>arr1[i];
        cout<<endl;
    }
    return 0;
    cout<<arr1;
    delete [] arr1;
}

Now check this code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.