I'm writing a program that asks the user how many numbers they would like to input, then proceeds to ask the user to enter the said amount of numbers. At the end, the program computes the sum, average, largest number and smallest number. I've got the entire program figured out, but I've been sitting here for hours trying to figure out how to compute the smallest number and it's driving me crazy. Can someone please tell me how to do this? I feel like i've tried everything. (Probably not, though, seeing as I'm new to C++ lol) Here's what I have for code.

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
	int UserInput, number, i;
	int sum = 0; 
	float average = 0;
	int largest = 0;
	int smallest = 0;
		cout << "How many numbers do you wish to enter? ";
		cin >> UserInput;
		
		for (i = 0; i < UserInput; i++)
		{
			cout << "Enter a number: ";
			cin >> number;
			sum = sum + number;
			average = float(sum)/UserInput;
			if (number > largest)
				largest = number;
			if (number > smallest && number < largest)
				smallest = number;
			
		}
		
		cout << "The sum is: " << sum << endl;
		cout << "The average is: " << average << endl;
		cout << "The largest is: " << largest << endl;
		cout << "The smallest is: " << smallest << endl;

	getch();
	return 0;
}

You have made mistakes in the code to do the largest AND smallest.
First off, consider the test case of a user inputting ONE number only.
Let us say that number is 10.

Then your code will report that correctly for the largest BUT report 0 for the smallest. The problem here is that you have assumed that the largest and smallest number cannot occur together. Same problem exists if you enter 3,5,10.

Second issue is that you start with the smallest number equal to zero. That is obviously a mistake. There are (easy) two ways round that (a) set smallest to be the biggest possible integer, (b) use a flag.

Let me show your how to to the latter.

// Note that i is acting both as the loop variable and the flag
for(int i=0;i<UserInput;i++)
  {
     if (!i || smallest>number)
       smallest=number;
  }

Yes it adds an extra test. That is sometimes a problem.

u have already declared the smallest=0 so if the user enter all the number greater than 0 u will get 0 as your output
so assign smallest as the first number given by user
and change the condition if by
if(number<=smallest)
{
smallest=number
}
reply me if it works

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