I bought the textbook C++ How to program 9th edition and I have come across a question that I am just stumped on, even though it is probably pretty simple. The question all summed up is this: "Use a while statement to determine and print the largest number of 10 numbers entered by the user". But here is the part that stumps me. The question wants me to use only 3 variables. counter, number, and largest. I know to make counter variable go up by 1 for each number entered until it gets to 10, and I know the number variable is used for input. I just can't seem to find out how to use the largest variable, or how to check to see what value is the largest without using other variables. This is all I have so far. Right now I put a break in the code so it wouldn't be an infinite loop.
UPDATED CODE
#include <iostream>
using namespace std;
void main()
{
int counter = 0;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (number > largest)
{
largest = number;
}
else if (counter == 10)
{
cout << "The largest number was: " << number;
break;
}
}
}
cout << "The largest number was: " << number;
should be
cout << "The largest number was: " << largest;
Inside the while loop, if number is greater than largest, then set largest = number.
Then at the end you can output largest.
Solution(you don't even need a while loop)
#define MAX_NUM 8
//user input goes in myints
int myints[MAX_NUM] = {3,7,2,5,6,4,9};
// using default comparison:
std::cout << "The largest element is " << *std::max_element(myints,myints+MAX_NUM) << '\n';
Other Solution using int arrays even though you can replace int array with one variable
int main()
{
int largest = 0;
int myints[10] = {3,7,2,5,6,4,9,7,2,6};
for(int i =0 ; i< 10;i++)
{
if (myints[i] > largest)
{
largest = myints[i];
}
}
cout << largest << endl;
return 0;
}
Compiled Code
Second Compiled Code
You just need to add in while loop checking is the number you entered bigger than largest. If it is you just store it in largest. And actually you are entering 11 numbers because you count from 0 to 10. Just set counter to 1 or while(counter < 10)
int counter = 1;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (largest < number)
{
largest = number;
}
}
cout << largest << endl;
Related
My problem is finding the minimum value out of user defined number of inputs. Everything so far works just fine, except that. Every time I try and rearrange some code or try a new method, I keep getting the same output on the screen:
Sum of numbers entered is: 145.4
Average of numbers entered is: 24.2333
The Highest number entered was: 45
The Lowest number entered was: 6.95283e-310
I get this every single time, regardless of what is entered, or what different suggestion I try:
The Lowest number entered was: 6.95283e-310
I am aware of the use and implementation of Arrays. However, the assignment I'm doing hasn't even covered arrays yet. That is some number of chapters later. Please don't suggest arrays...
I've looked here:
Finding Maximum and Minimum values in c++ by user input
Didn't work
http://www.cplusplus.com/forum/beginner/38799/
Didn't work
changing the values of max/min didn't work either
#include <iostream>
using namespace std;
int main()
{
double number, numberitems, sum = 0, average, max, min;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
max = number;
}
//minimum value entered
if (number < min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
std::cout << endl;
std::cout << endl;
std::cout << "Sum of numbers entered is: " << sum << '\n';
std::cout << "Average of numbers entered is: " << average <<'\n';
std::cout << "The Highest number entered was: " << max <<'\n';
std::cout << "The Lowest number entered was: " << min <<'\n';
return 0;
}
Made a temporary fix :3
double min = 99999999999999999999999999999999999999999999999;
I'm very new to this.
Updated
After reading more comments I saw I was missing <cfloat>. Using #include <cfloat> NOW everyone's suggestions above work. However, <cfloat> was not covered in class, at all. So I'm not sure if that is usable here?
#include <iostream>
#include <cfloat>
using namespace std;
int main()
{
int numberitems;
double number, sum = 0, average;
double max = 0;
double min = DBL_MAX;
cout << "Enter number of items: \n";
cin >> numberitems;
//Make sure user can not enter negatives
if ( numberitems < 0 ) {
//no request to perform sum
std::cout << "I said not to enter a negative number... '\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number >= max) {
max = number;
}
//minimum value entered
if (number <= min) {
min = number;
}
//Make sure user can not enter negatives
if ( number < 0 ) {
std::cout << "I said not to enter a negative number...'\n";
std::cin.clear(); //clear bad input flag
return 1;
}
//Sum of all the numbers
sum = sum + number;
//Average of all the numbers
average = sum / numberitems;
}
//Print the results
// some cosmetic...
std::cout << endl;
std::cout << endl;
std::cout << "\n=================REPORT====================\n";
std::cout << '\n';
std::cout << "\tYour Totals\tValues\n";
std::cout << "\t-----------\t------\n";
std::cout << "\t Sum: " << sum << '\n';
std::cout << "\t Average: " << average <<'\n';
std::cout << "\t Highest: " << max <<'\n';
std::cout << "\t Lowest: " << min <<'\n';
return 0;
}
Again, <cfloat> works fine, but I'm not sure if I'm allowed to use it. What other ways around this are there?
The question already got good answers - shortly: min and max are uninitialized.
However
Above is very specific.
Of course it helps in this specific case but I feel a broader advise that would work here and in many other cases is needed.
Add printouts
Adding debug printouts to your code ("debugging without a debugger") is always helpful in such cases.
For example adding the following in your example may help:
//Get the user's values
for (int i = 0; i < numberitems; i++)
{
std::cout << "Enter any NON-negative number: ";
std::cin >> number;
std::cout << '\n';
//Maximum value entered
if (number > max) {
// debug - (remove before submission)
std::cout << "number is the new max! number = " << number
<< ", max = " << max << std::endl;
// end of debug
max = number;
}
//minimum value entered
if (number < min) {
// (debug - remove before submission)
std::cout << "number is the new min! number = " << number
<< ", min = " << min << std::endl;
// end of debug
min = number;
}
When calculating minimum and maximum, you should initialize your variables to a default value. For minimum, it's the maximal possible value; for maximum - the minimal possible one.
double max, min; // BUG - not initialized
#include <float.h> // or <cfloat>
...
double max = 0; // CORRECT - initialized
double min = DBL_MAX; // CORRECT - initialized
For maximum, the initialization is usually -DBL_MAX (note: not DBL_MIN), but 0 is good enough in this case, when no negative values exist.
You need to set an initial value for min and max. For min, I'd suggest using an initial value of DBL_MAX, which is defined in the header cfloat.
i am confused about how does this code flows especially after inputtedin the set of integers.
for example how will the input be stored and then compared to find the largest among the set?
#include <iostream>
using namespace std;
int main()
{
int n, num, max, k=1;
cout << " Enter how many integers " << endl;
cin >> n;
cout << " enter " << n << " integers: "; // where input be stored
cin >> max; // this will input the last number right?
// if i entered 50 55 60 where they will be stored dont i need to store them in in 3 seprate places
while (k<n)
{
cin >> num; // what is the function of this line? from where the input will be
if (num > max)
max = num;
k++;
}
cout << " largest integer is :" << max << endl;
return 0;
}
Let's walk through this.
Let's consider the case the user selects n >= 1. (note also k = 1).
We first need the user to enter one number.
cin >> max;
We say that this number is the max, we don't know if it's true or not but we make this assumption.
We then read in integers while k < n is true.
while (k < n)
{
cin >> num;
if (num > max)
max = num;
k++;
}
So, we read a number into num (which we declared outside the while loop).
We then check if this number is greater than our assumption that the first number was the biggest, if it is we reassign max to be equal to num.
We then increment k.
We do this until we have read in n integers.
Resulting in max being the largest number we entered.
As for storage, we're not needing to store anything, inside the scope of the while loop we can do the check if the number is larger than max or not, if it wasn't we just discard it with the next iteration.
It doesn't store the entire set of numbers read.
It compares each new one entered to the current maximum. The initial maximum value is set to the first number read.
Problem statement of this program will be like : You are given n integers. Now you have to print the largest integer among all these integers.
cin >> max will take only one integer as input. max will hold the value.
cout << " enter " << n << " integers: "; will print this output in the console. For example, if value of n is 2, then this will print: enter 2 integers:
Look in the comment for further details:
#include <iostream>
using namespace std;
int main() {
int n, num, max, k = 1;
cout << " Enter how many integers " << endl; // print
cin >> n; // number of integer to input;
cout << " enter " << n << " integers: "; // print how many integers to enter as input
cin >> max; // input for 1st integer, assume it is the maximum integer
// this while loop will take input of the remaining n-1 intergers
// initially k=1, while loop will run until k is less than n
// while loop will run for n-1 times
while (k < n) {
cin >> num; // input for 1 integer
if (num > max) max = num; // if this input integer 'num' is greater than 'max', then update 'max'
k++; // increment 'k'
}
cout << " largest integer is :" << max << endl; // print the largest integer
return 0;
}
I know I'm missing something real simple but I can't seem to get the numbers to print out in rows of just odd or just even numbers using a while loop or loops. Also It keeps printing out "the even numbers are:"/ "the odd numbers are:" for every number.
#include<stdio.h>
#include <iostream>
using namespace std;
int main()
{
//declare variables
int number;
int n;
cout << "Enter value less than 100: ";
cin >> n; //take user input
while (n <= 100) //loop only if n equals 100 or less
{
for(number = n; number <= n; number++) //for loop to increment int value
{
if(number % 2 !=0) //determines if odd
{
cout << "The odd numbers are:" <<number << endl; //prints odd values
}
}
for(number = n;number <= n; number++) // for loop to increment int value
{
if(number % 2 ==0) //determines if even
{
cout <<"The even numbers are:" <<number <<endl; //prints even values
}
}
n++;
}
return 0; //end of program
}
You may want this:
#include <iostream>
using namespace std;
int main()
{
//declare variables
int number;
int n;
cout << "Enter value less than 100: ";
cin >> n; //take user input
// print odd values
cout << "The odd numbers are:";
for (number = n + 1 - (n % 2); number <= 100; number += 2)
{
cout << " " << number;
}
cout << endl;
// print even values
cout << "The even numbers are:";
for (number = n + (n % 2); number <= 100; number += 2)
{
cout << " " << number;
}
cout << endl;
return 0; //end of program
}
I've been having trouble with a problem from my C++ book. It wasn't required to do, but I want to get it to work:
Sum of numbers
Write a program that asks the users for a positive integer value and that uses a loop to validate the input.* The program should then use a second loop to compute the sum of all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of 1, 2, 3, 4, ... 50.
*I'm not asking for this first loop, just the second. But if you feel like coding it go ahead.
It's pretty simple to write a program that decreases a number until it reaches one:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
while(number >= 1)
{
cout << number << " ";
number--;
}
system("pause"); //I usually go with cin.get() but my current
//compiler doesn't handle it
return 0;
}
But if you to add "number - 1" to a number, the number becomes bigger and now number - 1 will increase from thereon. For example, 7 + 6 = 13, 13 + 12 = 25, 25 + 24 = 49, etc. Here's the program I am trying to adapt to make work:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
for(count = 1; count <= number; count++)
{
number += number - 1;
}
cout << "The sum is" << number << endl;
system("pause"); //
return 0;
}
This is an infinite loop, unfortunately.
Any ideas to how to adapt this program so it satisfies the question? Or links to source code that's already done it before, etc.
EDIT:
So this might be another issue entirely, but my code isn't compiling:
#include <iostream>
using namespace std;
int main()
{
int number, sum = 0;
cout << "Enter a number: ";
cin >> number;
for(count = 1; count <= number; count++)
{
number--;
sum += number;
}
cout << "The sum is" << sum << endl;
system("pause"); //
return 0;
}
EDIT 2: I just got rid of the for loop and changed it to "while(number >= 1)"
Something like this ?
int sum = number;
while (number-- > 0) {
sum += number;
}
I find a for loop neater, so I'll post an example for variety.
int n = Max Number
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += i;
}
And for your compiling problem, unless I'm reading it wrong, you shouldn't be decrementing the number; it's defining what the max number is. Each loop you're incrementing the count, decrementing the number, then comparing them. I can't imagine that will give you anything meaningful. Erase the number--;, and it should work.
I know this probably really simple but Im not sure what im doing wrong...
The assignment states:
For the second program for this lab, you are to have the user enter an integer value in the range of 10 to 50. You are to verify that the user enters a value in that range, and continue to prompt him until he does give you a value in that range.
After the user has successfully entered a value in that range, you are to display the sum of all the integers from 1 to the value entered.
I have this so far:
#include <iostream.h>
int main () {
int num, sum;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
{
int i;
int sum = 0;
for (num = 1; num <= 50; num ++)
sum = sum + num;
}
cout << endl << "The sum is " << sum << endl;
return 0;
}
Im just not sure exactly what i'm doing wrong... I keep getting the wrong sum for the total...
Your loop conditions are wrong.
First, you should use a separate variable as your index (in fact you already declared one using "int i" earlier).
Second, your upper limit shouldn't 50, it's whatever the user entered.
So you want to change all "nums" in the loop to "i", and the "50" to "num".
Actually, you can simplify the for loop into:
sum = ((num+1)*num)/2;
Credits to Carl Friederich Gauss. :D
The Corrected code is
#include <iostream.h>
int main () {
int num;
cout << "do-while Loop Example 2"
<< endl << endl;
do {
cout << "Enter a value from 10 to 50: ";
cin >> num;
if (num < 10 || num > 50)
cout << "Out of range; Please try again..."
<< endl;
} while (num < 10 || num > 50);
//<----Removed the extra set of {}
int i,sum=0;//<---- Changed the declaration here
for (i= 1; i <= num; i++) //<----Change Here
sum += i;
cout << endl << "The sum is " << sum << endl;
return 0;
}
Let me make sure I understand this correctly, your assignment asks for a user input for a given number and store it in num and then display a running sum of 1 up to num?
If that's the case, inside your loop you override the user's input of num when you call num = 1. You'll just calculate the running sum of 1-50 every time.
To correct that, you need to use a different variable to keep incrementing, i.e. count or the variable i since it's already been declared. Then you should loop up from i to num as long as i <= num.
Other than that, I cannot see any problems and it should work correctly.
Note to add about a good investment:
It would definitely be worth while to see if the IDE you are developing in has a debugger you can use. Debugging is a great tool to help figure out why your code is not being executing as it is intended to.
If there is no debugger (which would surprise me) might I suggest my go-to alternative method of stepping through the for loop on a sheet of paper and compare the sum to another hand-written solution already solved, i.e. num = 5 sum = 1+2+3+4+5 = 15
Hope this helps.
The for loop should be:
for (int x = 1; x <= num; x++)
{
sum += x;
}
#include <iostream.h>
int main () {
int num, sum; // here you define (but don't initialize) one variable named sum.
[ ... ]
{ // here you start an inner scope.
int i;
int sum = 0; // here you define *another* `sum`, local to the inner scope.
for (num = 1; num <= 50; num ++)
sum = sum + num; // here you add the numbers to the *second* sum.
} // here the second sum goes out of scope.
// and here you print out the first (still un-initialized) sum.
cout << endl << "The sum is " << sum << endl;
Your upper bound is not 50, but the number you entered.
Therefore your summation is from 1 t0 inclusive of your entered number.
Say you enter 10,
logic will be.
You add all the digits from 1 to 10.