Need help understanding what's going on in my while loop - c++

My program executes just fine, but I have questions about how my while loop is set up.
I know the Boolean values for true and false are 1 and 0, respectively, but I'm not understanding why my output displays the even and odd numbers backwards (to my understanding, it's backwards). Simply put, I don't understand why if ( number % 2 == 0 ) would display that a number is even and when I change it to 1, it displays odd. I'm reading this line as, if (even number equals to false). I don't know if that's where I'm going wrong. What's the correct way to read this line?
The way I have my code set up now displays the numbers correctly, I'm just not understanding why. Can anyone help?
// Program indefinitely displays an even
// or odd number until a negative number
// is entered.
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Please enter a number: ";
cin >> number;
while ( number >= 0 )
{
if ( number % 2 == 0 )
{
cout << number << " is even \n";
cout << "Please enter a number: ";
cin >> number;
}
else
{
cout << number << " is odd \n";
cout << "Please enter a number: ";
cin >> number;
}
}
cout << "Thank you. \n";
return 0;
}

number % 2 is 0 if number divides 2 (i.e. is even), 1 if number is positive and does not divide 2 (i.e. is odd), and -1 if number is negative and does not divide 2 (i.e. is odd). (The last point must be the case from C++11 onwards).
So, since 0 == 0 is true, number % 2 == 0 is true if, and only if, number is even.
So you've written if ( number % 2 == 0 ) to trap all even cases, and the else traps the odd cases.
Testing if ( number % 2 == 1 ) is only a test for positive oddness, but older C++ standards allow this to be true for negative number.

Related

trying to output all odd numbers from a sentinel loop, almost got it but not quite and also want to know why I am doing what needs to be done

Hi so I have to write this program, Write a sentinel controlled while loop.
Ask user to input integer numbers. Output all odd numbers. Program quits when the value:
-999 is entered. I have most the program functioning correctly except inputting multiple numbers and outputting only odd numbers, I created the program below and it quits the program at -999 and asks for input and outputs odd numbers, but I have tried to get it to do what the program requires and have been having issues getting it to input multiple integers and outputting just the odd ones. My program is posted below
#include <iostream>
using namespace std;
int main()
{
const int SENTINEL = -999;
int num;
cout << "Enter a number to stop enter -999 " << endl;
cin >> num;
while (num != SENTINEL)
{
if (num % 2 != SENTINEL)
cout << "odd integer is: " << num << endl;
cout << " Enter a number " << endl;
cin >> num;
}
return 0;
}
to test if num is an odd, use:
if (num % 2) instead of if (num % 2 != SENTINEL)
because the remainder is calculated when divided by 2 using the % modulus operator, if it isn't zero this integer is odd, your test != SENTINEL doesn't really make sense.

Displaying a character based on integer entered by user

I am sure this will seem very novice to many on here but I am currently trying to learn C++ and have an in depth full understanding to apply my knowledge in the real world.
The Problem Description:
Write a program that graphically depicts an integer’s magnitude by using asterisk, creating a
histogram. Hint: The inner loop handles the printing of the asterisk and the outer loop handles
exciting until zero is entered. Make sure you don’t accept negative numbers.
Sample run:
Enter a positive integer (0 to quit): 5
*****
Enter a positive integer (0 to quit): 8
********
Enter a positive integer (0 to quit): -5
Enter a positive integer (0 to quit): -10
Enter a positive integer (0 to quit): 15
***************
Enter a positive integer (0 to quit): 0
Good Bye!
My Current Code (I know this isn't right by any means, but helps demonstrate my thinking, I know you need to use a nested loop to answer this properly.):
#include <iostream>
using namespace std;
int main()
{
int ast; //Number of asterisk wanted to be displayed
char asts='*'; //Actual display coressponding to asterisk
cout<<"Enter a positive integar, (0 to quit)"<<endl;
cin>>ast;
while(ast!=0)
{
if(ast>0) // Ensuring no negative integars are entered
{
asts=ast;
cout<<asts<<endl;
cout<<endl;
}
else //Display if negative or other invalid data is entered
cout<<"Invalid Data, negative values are not accepted, try a positive integar or 0 to quit"<<endl;
cout<<"Do you want to continue? If so, enter another integar (0 to quit)"<<endl;
cin>>ast;
}
cout<<"Thank you for using the program."<<endl;
return(0);
}
Thank you for the help ahead of time!
-Colin
The basic idea is (with pseudo-code):
get number of asterisks
while number is not zero:
if number is negative:
output error message
else:
do number times:
output *
output newline
get number of asterisks
Your nested loops there are while number is not zero and do number times.
However, one of the earliest skills you should learn as a developer is to properly assign tasks to specific pieces of code (methods, functions, libraries and so on). In particular, it's a good idea to modularise your code so that each piece has a well defined purpose, then build the "upper" layers out of those pieces.
To that end, this is how I would approach the problem. First, define the functions that would be useful in this case.
Start with getAsterCount() which is responsible for asking the user how many asterisks they want and verifying that it's valid (asking again and again, until it is). For example:
#include <iostream>
int getAsterCount() {
// Until we get valid response.
for(;;) {
int count;
// Get value, checking for error, forcing exit if so.
std::cout << "Enter the number of asterisks, zero to exit: ";
if (! (std::cin >> count)) {
std::cout << "*** ERROR: could not read number\n";
return 0;
}
// Any non-negative value is allaowed.
if (count >= 0) {
return count;
}
std::cout << "That was less than zero, try again.\n";
}
}
Once that's in place, you never have to worry again about the user providing invalid information for this program, since this function will capture it (and you can call it from anywhere, as shown in the main() function below.
Next, provide a function that will actually output the asterisks, based on the count you now have:
void outputAster(int count) {
// Simple loop for asterisks then new line.
for (int i = 0; i < count; ++i) {
std::cout << '*';
}
std::cout << '\n';
}
With that in hand, your main code becomes the conceptually much simpler:
int main() {
int count = getAsterCount();
while (count > 0) {
outputAster(count);
count = getAsterCount();
}
std::cout << "Thank you for using the program. Now get off my lawn.\n";
}
Right now you are trying to do:
asts=ast;
Which doesn't make much sense, as this will only assign the entered integer to asts.
To print the magnitude in * you need to loop from 0 to the inputted integer and print out an asterix every time:
for(int i = 0; i < ast; i++) {
std::cout << "*";
}
std::cout << "\n";
Output:
Enter a positive integar, (0 to quit)
5
*****
Do you want to continue? If so, enter another integar (0 to quit)
3
***
Do you want to continue? If so, enter another integar (0 to quit)
5
*****
Do you want to continue? If so, enter another integar (0 to quit)
0
I like a somewhat different approach, without a loop.
char asts[] = “*********\n”;
After checking that the input value is in range, just write out the tail of the string:
std::cout << (asts + 9 - ast);

A program that counts how many prime numbers are between 2 and a given number

I've just had one of my exams at the college
one of the questions were to program a function that counts how many prime numbers are between 2 and a given number from the user(including the number).
I wrote this algorithm which works for me but they still deducted all of the points of the question as if it was completely wrong.
Can please someone tell me what's wrong with the code?
Thanks a lot.
#include <iostream>
using namespace std;
void main()
{
int count = 0;
int num;
cout << "Please enter a natural number " << endl;
cin >> num;
for (int i = 2; i <= num; i++)
{
if ((i == 2 || i == 3 || i == 5||i == 7) || (i % 3 != 0 & i % 5 != 0 & i % 7 != 0 & i % 2 != 0))
count++;
}
cout << "There are " << count << " prime numbers beteween 2 amd " << num << endl;
}
Your code only checks if a number is a multiple of 2, 3, 5, or 7. That's missing a lot of multiples, meaning your code likely gives many false positives.
That condition is also quite difficult to read, so you probably would have lost points for that as well.
You would have been much better off replacing that condition in the loop with another for loop, and checking every odd number from 3 to the square root of the test number.

Need help in basic C++ regarding how to properly loop through part and finding smallest value

Hi I'm needing some help. I'm in a intro to programming class and we are using c++. I am hoping someone can help me with an assignment that was due yesterday (I understand not to expect miracle responses but a girl can always try).
I'm having two problems that I know of. The first is regarding the smallest value.
The big one is in trying to make it loop for requirements of three times but not lose out on my total count. I cannot use arrays or anything I haven't learned yet which is why I've posted this. I've seen similar problems and questions but they have ended up with answers too complex for current progress in class. So here is the problems instructions:
Instructions
1) Write a program to find the average value, the largest value, and the smallest value of a set of numbers supplied as input from the keyboard. The number of values in the data set must be in the range 0 to 20, inclusive. The user will first enter the number of values in the data set(use variable int Number). Give the user 3 attempts at entering Number in the range given. If the value for Number entered is out of this range, write an error message but continue. If the user does not enter a valid value for Number within the 3 attempts print an error message and terminate the program.
2) Format only the output for the Average value to 3 decimal places when printed.
3) The values in the data set entered as input can be any value positive, negative, or zero.
4) Make the program output readable(see the example below). (Note: that you will notprint out the input values that were entered in this program like you normally are required to do. This is because we have not covered the “tool” needed to do so yet in our studies).
Below will be the output from the execution of your program:
(using these values in order for the data set --> 19.0 53.4 704.0 -15.2 0 100.0)
The largest number: 704
The smallest number: -15.2
The average of the 6 numbers entered: 143.533
yourName L4p2XX.cpp
Lab#4 prob 2 XX-XX-12
Here is my poor excuse at the solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double Number = 0, minValue, maxValue, average, total = 0;
int ct = 0, numCount;
cout << "How many numbers would you like to enter? ";
cin >> numCount;
for(ct = 1; ct <= numCount; ct += 1)
{
cout << "Enter Value from 0 to 20, inclusive: ";
cin >> Number;
if(Number > 20|| Number < 0)
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
{
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
total += Number;
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
} //end for loop
cout << "The smallest number entered was " << minValue << endl;
cout << "The largest number you entered was " << maxValue << endl;
average = total/numCount;
cout << setprecision(3) << fixed << showpoint << "You entered " <<
numCount << " numbers. The average of these is " << average;
//Program ID
cout <<"\n" << "L4P2LB.cpp\n" << "11-05-12\n";
system ("pause");
return 0;
} // End main
Thank you in advance to anyone who can steer me in the right direction. Not looking for anyone to do my work I just need help in direction if nothing else or any suggestions as to what to do. Thanks again. Lynda
Also I need somehow to pause after the third time and exit properly. If I put the second pause in it won't work so am I missing something obvious there too!
The first problem I see is that you didn't initialize a couple of variables.
You should either initialize both minValue and maxValue variables with something which will overwritten in every case in the first loop (typically "positive/negative infinity", as provided by <limits>), or just set both to Number in the first iteration, regardless of their current value. So I'd suggest to fix this by replacing
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
with
if(maxValue <= Number || ct == 1)
maxValue = Number;
if(Number <= minValue || ct == 1)
minValue = Number;
as ct == 1 will be true in the first iteration.
That said, you check the 0..20 range condition on the wrong variable. You check it on the Number variable, but you should check the numCount variable. But you also didn't respect the requirement that the variable to store the "number of numbers" should be Number, so you did check the correct variable, but used the wrong to read the input into. This should fix this issue (I changed the variable name in the cin >>... line + moved the check outside your main loop):
cout << "How many numbers would you like to enter? ";
cin >> Number;
if(Number > 20|| Number < 0)
{
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
...
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
}
for(ct = 1; ct <= Number; ct += 1)
{
...
}
...

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!