Errors while Programming

This program contains error as mentioned below:
//program to find mean of N numbers.
#include<iostream>
using namespace std;
double x[];
int n;
int main()
{
double mean(double a[], int b);   //function declaration
cout<<“Enter number of elements: “;
cin>>n;
cout<<“Enter elements: “;
for(int i=0;i<n;i++)
{
cin>>x[i];
}
double m = mean(x,n);    //function call
cout<<” Mean of “<<n<<” numbers =”<<m<<“n”;
}
double mean(double a[], int b)   //function defination
{
double sum=0;
double mn;
for(int i=0;i<=b;i++)
{
sum = sum + a[i];
}
mn=sum/b;
return(mn);
}
 
error: storage size of ‘x’ isn’t known
I declare an array as: double x[] ;  but didn’t give its size.
I define its size as double x[10], then it works fine.
[ but as I enter n=5, it cause loss of extra memory allocated as x is declared of size 10, therefor here pointer array is required. }
……………………………………………………………………………………………………………………………………………….
same code is improved as
 
//program to find mean of N numbers.
#include<iostream>
using namespace std;

int n;

double *x;  //declare pointer

int main()
{
double mean(double a[], int b);   //function declaration
cout<<“Enter number of elements: “;
cin>>n;
x = new double[n];   // new pointer array
cout<<“Enter elements: “;
for(int i=0;i<n;i++)
{
cin>>x[i];
}
double Mean = mean(x,n);   //function call
cout<<“Mean of “<<n<<” numbers =”<<Mean<<“\n”;
delete[]x;
}

double mean(double a[], int b)   //function defination
{
double sum=0;
double mn;
for(int i=0;i<=b;i++)
{
sum = sum + a[i];
}
mn=sum/b;
return(mn);
}
Advertisements

About Jasleen Kaur

Hi, I am Jasleen kaur, a Computer Science Student.
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s