Suraj Kumar M
Suraj Kumar M

Reputation: 31

For Loop Executing only once in cpp

Hey am trying to run this code but the for loop executes only once. Removing the line cout< fixes the problem but I need the ans to be precise to 15 decimal places. here's the code

int n,i;
cin>>n;
double a[n];
for(i=0;i<n;i++){

    cin>>a[i];
    a[i]=(a[i]/100);
    cout<<fixed<<setprecision(15)<<a[i];
}
for(i=0;i<n;i++) {
    cout<<a[i];
}

Upvotes: 0

Views: 59

Answers (1)

R Sahu
R Sahu

Reputation: 206567

First things first

Use of variable length arrays (VLAs) is not standard C++. It is supported by some compilers as an extension. If you are allowed to use std::vector, use

std::vector<double> a(n);

If you are not allowed to use std::vector, use

double* a = new double[n];

and make sure to use

delete [] a;

before the end of the funtion.

Suggestion to help you diagnose the problem

Add appropriate prompts before entering data and messages to indicate what was read.

for(i=0;i<n;i++)
{
    cout << "Enter number for a[" << i << "]: ";
    cin>>a[i];
    a[i]=(a[i]/100);

    // Make sure to add endl at the very end.
    cout<< "Value of a[" << i << "]: " << fixed << setprecision(15) << a[i] << endl;
}

Upvotes: 2

Related Questions