need help :)

This code works properly when user enter max 2 variables... When put more - crash.... please for help :)

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
int sum = 0;
int n = 0;

cout << "Enter a number of variables : ";
cin >> n;

int *p = new int[n]; // Allocate n integers
for (int i = 0; i < n; i++)
{
cout << "Enter a number #" << i << ": ";
cin >> p[i];
sum += p[i];
}
cout << "All your numbers: ";
cout << endl;

cout << "The sum is: " << sum << endl;
cout << "Average is: " << (double) sum / n << endl;
for (int i = 0; i < n;)
{
int smallest = p[i];
for (int j = i + 1; j < n; ++j)
{
if (p[j] < p[i])
{
smallest = p[j];
cout << "The smallest number of your enter is: " << p[j];
break;
}
if (p[j] > p[i])
{
cout << "The smallest number of your enter is: " << p[i];
break;
}
}
++i;
}


cout << endl;

delete [] p; // Release n integers.
system("PAUSE");
return 0;
}
Last edited on
The logic for printing the smallest number is wrong, but I'm not seeing a crash. As long as your user inputs are integers, this should run.
you are right.. it's not a crash, it does not return proper value..... what I did wrong?
Last edited on
You only need one loop
1
2
3
4
5
6
7
int smallest = p[0];
for (int i = 1; i < n; i++)
{
    if (p[i] < smallest )
        smallest = p[i];
}
cout << "The smallest number of your enter is: " << smallest;
Last edited on
Thx :)
Topic archived. No new replies allowed.