one dim array - smallest element & index

The question is as follows:
Write a C++ Program that ask the user to enter array size, then declare an integer array with the same size that the user entered.
For the declared array ask the users to enter the numbers inside the array then, find the index of the smallest element in the array.
Finally, your program should print the value of the smallest index.

I have tried as follows:

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
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    int s;              // s = size number
    int index=0;
    int array [s];
    
    cout<<" Please enter the size number of your array: ";
    cin>>s;
    
    for (int i=1;i<=s;i++)
    cin>>array[i];
    
    for (int i=1;i<=s;i++)
    if (array[i]<array[index])
    index=i;
    
    cout<<" The minimum value in your array is :"<<endl;
    cout<<array[index];
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


But where is the false if u could help me ?
1
2
3
	int s;              // s = size number
	int index = 0;
	int array[s];

this is illegal. Your s variable has to be const; to make this legal, and of course your s variable should have a value.


If you want to crate the array at runtime you need to use a dynamic array.
1
2
	int *arr = new int[s];
	delete[] arr;


The algorithm header file has a function that gets the min element of an array.
http://www.cplusplus.com/reference/algorithm/min_element/

anything with the word system in it is considered bad programming
http://www.cplusplus.com/forum/articles/11153/
Last edited on
Topic archived. No new replies allowed.