Want to use variable as size of array in turbo C++

I have been trying to use variable as size of an array(e.g.float data[x]) but can't do it. I have searched for others answers and can't seem to understand those. Please explain me in simplest way on how to use variable as size of array in turbo C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//Program to print largest element in an array(using a function)
#include<iostream.h>
#include<conio.h>
float largest(float abc[],int n)
{
 float large=0;
 for(int k=0;k<n;k++)
 {
  if(large<abc[k])
  {
   large=abc[k];
  }
 }
 return large;
}
int main()
{
 clrscr();
 cout<<"In this program you can enter any amount of elements you";
 cout<<" want and it will give the largest element as an output.\n";
 int noe;//from here to---------------------------
 cout<<"Enter the amount of elements you want to enter :";
 cin>>noe;
 float data[5];
 if(noe>5)
 {
  data[noe];
 }// here--------------------
 for(int i=0;i<noe;i++)
 {
  cout<<"Enter element no."<<(i+1)<<" : ";
  cin>>data[i];
 }
 cout<<"Largest element in the array is : "<<largest(data,noe);
 getch();
 return 0;
}
Last edited on
You need to allocate your array dynamically with new.
http://www.cplusplus.com/doc/tutorial/dynamic/

An even better and easier solution is to use a modern compiler and use std::vector.
Or forget C++ and learn C# or Java, even the oldest versions have container classes.
Topic archived. No new replies allowed.