Right now, I am learning how to use an Array. How the program should work is, I declare how many numbers I want to input, and then, put numbers in. At last, I can choose either find the maximum, sum, or product. The program seems right to me but it's not really working. The black box comes up and I can do all inputs until I get to pick from max, sum, or product. The program crashes. Can anyone find a mistake for me?

#include <iostream>
using namespace std;

void max(int n, //number of elements
		 int a[], //array of values
		 int&result)
	
	{
		int m=a[0];
		int max;
		for (int i=1; i<n; i++)
			if (a[i] > max) max = a[i];
		result = m;
	}


void sum(int n, //number of elements
		 int b[], //array of values
		 int&result)
		
	{
		int s=b[0];
		int sum;
		for (int i=0; i<n; i++)
			b[i]= b[i] + n;
		result = s;
	}


void product(int n, // number of elements
			int c[], // array of values
			int&result)
	{
		int p=c[1];
		int product;
		for (int i=0; i<n; i++)
			c[i] = c[i] * p;
		result = p;
	}

void main()
{
	char choice;
	int n;
	int result;
		cout << "Please input the number of values (<=10): ";
		cin >> n;
		int v[10];

	//reading the array
	for (int i=0; i<n; i++)
	{
		cout << "input a value: ";
		cin >> v[i];
	}

	cout << "What is your coice (m,s,p)?" ;
	cin >> choice;

	switch (choice)
	{
	case 'm': max (n,v,result);
				  break;
	case 'p': product (n,v,result);
				  break;
	case 's': sum (n,v,result);
				  break;
	
	default : cout << "Wrong choice" << endl;
	}
	cout << "result= " << result << endl;
	
	system("pause");
}

Edited 5 Years Ago by jdh1231: n/a

I used 4 , 4,3,2,1 an then either m,p,s none of them worked

Output as follows.

j@j-desktop:~/badCode$ ./a.out 
Please input the number of values (<=10): 4
input a value: 4
input a value: 3
input a value: 2
input a value: 1
What is your coice (m,s,p)?m
result= 4

I removed system("pause"); and changed void main() to int main(). No other changes.

Here is an error, though:
if (a > max) max = a;
The first time you come to this, what value does max have?

Edited 5 Years Ago by Moschops: n/a

This article has been dead for over six months. Start a new discussion instead.