While function doesn't work like I want it to - c++

Had a new problem with the while function. As easy as it sounds, I still can't wrap my head around it.
Like my last program, this one closes unexpectedly after the correct and wrong messages.
I want this to loop after entering a number, so that the program won't stop.
Thanks for the help, if any.
#include <iostream>
using namespace std;
int main()
{
int X = 0; //setting the first variable
int num; //setting the second
while (X == 0) //this should happen whenever X is equal to 0
{
cout << "Type a number bigger than 3. "; //output
X++; //This should increase X, so that the next while function can happen
}
while (X == 1) //again, since I increased x by one, (0+1=1 obviously) this should happen
{
cin >> num; //standard input
if (num > 3) //if function: if num is bigger than three, then this should happen
{
cout << "Correct! Try again!" <<endl; //output
X--; //Here I'm decreasing x by one, since it was 1 before, now it becomes 0. This should make the "while (X == 0)" part happen again, so that another number bigger than three can be entered
}
if (num <= 3) //if function: if num is lesser than or equal to 3, this should happen
{
cout << "Wrong! Try again!" <<endl; //output
X--; //This is supposed to work like the "X--;" before, repeating the code from "while (X==0)"
}
}
}

now it becomes 0. This should make the "while (X == 0)" part happen again
Nope. While loops don't magically take effect at any point during execution of the program. You only enter a while loop when you've reached it from code above. Programs are executed top-to-bottom, generally.
You would need a loop around the entire program if you want to keep going round and round. Those whiles you have now should probably be ifs.

Merge the two while loops into one, while(true).
Put each previous while body into an if state with the clause from the old while in it.
while(true) {
if (X==0) {
// the X==0- case
} else if (X==1) {
// the X==1 case
}
}
in order to end your loop, do a break;.
You have to think of C++ programs as a sequence of instructions, like a recipe. while just means a loop: you check the condition. If true, you run the body. After running the body, you check only that condition again, and run the body if true. Whenever the condition is false at the start or end of the body of the while (the {} enclosed code after it), you end the loop and proceed to the next one.
The first loop runs, finishes, then the second loop runs in your code. Once the first loop exits, you do not go back into it just because the condition becomes true.
Understanding flow control is one of the "hard" steps of learning to program, so it is ok if you find this tricky.
There are many improvements you can do your code beyond getting it working -- there is, actually, little need for X at all. But baby steps! Once you get it working, you can ponder "how could I remove the variable X?".
Before making such fundamental changes to your program, you should get it working, and save a copy of it so you can "go back" to the last working version.

You want to wrap all that code in it's own while loop:
while (true /* or something */)
{
while (X == 0) //this should happen whenever X is equal to 0
{
// ...
}

At least put your second while loop inside the first one to get it working as intended. Otherwise your program has no reason to go back again.
Nevertheless it's not a good design.

Related

C++: Why/How a Break Statement Works In This Code?

I have started to use C++ programming language as a complete beginner. With the aim of becoming a better programmer for my STEM degree and with the goal of competitive programming in mind. I have started Functions and Loops in C++ recently and there was a problem I was not sure how to approach.
The probelem: "Write a function to check whether a number is prime"
My Approach:
-> I wanted to implement it on my own so I didn't want to copy paste code online where others have used functions with return type bool.
-> Here is the final version of my code that works:
void prime(int k){
for(int k1=2;k1<k;k++){
if(k%k1==0){
cout<<"int is not prime"<<endl;
break;
}
else{
cout<<"int is prime"<<endl;
break;
}
}
}
->I would then call this in int Main() and get the user to input integers and so on.
-> The above code was due to many trial-and-errors on my part and my thought process was as follows: 1)if i don't include the "break;" statement my code results in an infinite loop 2)I needed a way to stop my code from going toward an infinite loop 3) I remember a topic covered in the functions segment of this website , where we can use it to terminate a loop at will. Thats why i incorporated it into my code to produce the final version
My Question:
Can someone explain how the break; statement is working in the context of my code? I know it produces my desired effect but I still haven't gotten an intuition as to how this would do my work.
Many online resources just cite the break statement as something that does so and so and then gives examples. Without going through the code mechanics. Like how a loop would be going through its conditions and then when it encounters the break; statement what does it do? and as a consequence of that what does it do to help my code?
Any advice would be helpful. I still couldn't wrap my head around this the first time I encountered it.
In your case if k % k1 does not show that the k1 being a factor of the k, the loop is broken after the print statement. If the k % k1 does show that the k1 being a factor of the k, it also breaks out of the loop.
So, either of the break statements leads to the loop termination on the first iteration here. If you test for whether a number is being a prime, it does not work.
In essence, you don't need either of the break statements here. They are mostly forced here. Take a look at the following approach:
#include <iostream>
#include <cmath>
bool prime(unsigned k){
if (k != 2) { // Direct check, so to remain similar to the OP's structure of the code
unsigned up_to = sqrt(k) + 1; // Calculate the limit up to which to check
for (unsigned i = 2; i < up_to; ++i) {
if (k % i == 0) {
std::cout << "Is not prime" << std::endl;
return false;
}
else std::cout << "Checking..." << std::endl;
}
}
std::cout << "Is prime" << std::endl;
return true;
}
// Note, we can check just up to the square root of a k
A note on the behavior of the break
The fact that it breaks out the the closest loop to it - has crucial nature for nested loops (all of them: for, while, and do while):
while (/* condition 1 */) // Outer loop
while (/* condition 2 */) // Inner loop
if (/* condition 3 */) break;
Here if the condition 3 is satisfied, the break will lead to break out of the Inner loop but the Outer loop will still continue to iterate.
For more, you may be interested in "How to exit nested loops?" thread. It addresses your second question.
Analogy... I found it in the last place I looked... like always!
Looking for your keys is the LOOP you are in... when you find them... you BREAK out and move on to another task... like maybe getting into your car...
SO if you are IN your car and know your car is where you left your keys... then you are in the PROCESS of getting prepared to drive away... BUT that process requires keys... THUS you change modes/focus and begin a cyclic process of looking for keys... when found to BREAK that searching process IMMEDIATLY and resume what your were doing.
MANY people would make use of the RETURN instrucion in your code pattern... in place of the break! Both do the same thing... however the RETURN is more descriptive english... and one should be concerned with the programmer behind him... Also a bit of digging might show how one is more efficient than the other...

Difference in while and do-while loops

Can someone explain the purpose of having two different types of while loops? I am new to programming. Also supply example situations with the proper while loop if possible.
I understand how to use a while loop. This is what I made:
bool myBool = true;
int i = 0;
while (myBool) {
if (i > 10) {
myBool = false;
}
i = i + 1;
}
A while loop will only execute when the boolean condition is true.
while (true) {
// INSERT CODE HERE
std::cout << "boolean condition is true - inside my while loop";
}
A do while whill check the boolean condition after the loop executes once.
do {
// INSERT CODE HERE
std::cout << "inside my while loop regardless of boolean condition";
} while (true);
Explicitly: the do while loop is guaranteed to execute at least once, whereas the while loop is not guaranteed to execute at all.
Similarly,
while (false) {
// INSERT CODE HERE
std::cout << "this will never execute";
}
will never execute and
do {
// INSERT CODE HERE
std::cout << "this will execute only once";
} while (false);
will execute once.
The do while loops are control flow statements, they execute a block of code at least once and then the iteration of loops depends on the condition which is checked at the bottom of the loop, They are best to use when you want at least once the loop to be executed, for ex
#include <stdio.h>
int main () {
int c = 50;
/* The do will be executed */
do {
printf("value of c: %d\n", c);
c = c + 1;
}while( c < 20 );//It will depend on the condition
printf("any string");
return 0;
}
Here is a Flow diagram of do while loop
Simple answer is while loop will execute only if condition inside of while statement is true.
do while loop will execute once regardless of the while statement condition.
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
int i = 1;
while( i < 1){ // this loop will never execute as 1 is not smaller then 1
i++; // if the loop was working we would get print 2 here
cout << i << endl;
}
cout << i << endl; // this one will print outside of loop value 1
do{
i++; // increase i to 2
cout << i << endl; // this will print 2
} while (i < 1); // This loop will execute at least once and as the condition of 2 is not smaller then 1 it will exit after one execution
return 0;
}
The difference between while and do-while is that in
while (<condition>)
{
//statements
}
we can control whether to enter the loop by using the test condition.
Whereas in
do
{
//statements
} while (<condition>);
the code has to enter the loop at least once before it can exit by using the condition.
So if we want to enter the loop at least once we should use do-while whereas if we want to test and decide whether to enter the loop or not, we have to use while.
To explicitly answer your first question:
Why does C++ have different kinds of loops? -> Legacy. Other languages (in particular, C) before C++ had this feature, so C++ chose to have it.
Why did other languages have it? -> This gets muddy, but a good explanation is that early languages often did not have optimizing compilers, so your code mapped quite directly to machine code. Providing various loop syntaxes allowed programmers to write structured code that still generates good machine code for their particular case.
In practice, it is rare to see a true do {} while () loop. This may be because for (or range-based for) and while () {} have strictly greater capabilities than do {} while (): An unconditional first loop iteration is possible with every loop, but the reverse is not true. In the very common case of iterating over a (possibly empty) sequence, having a guaranteed loop body execution like do {} while () is actually wrong.
There are plenty of answers with examples and explanations about the loops, so I won't bother repeating this here. I will add though that the most that I personally have seen do {} while () used is, ironically, not for looping but for this.
do-while loop performs the task before the condition in while(). It is for situations when you are trying to prompt the same thing for every wrong action (i.e., user authentication, wrong menu entry). On the other hand, a simple while loop performs till a condition is true (Note: In most cases people use for loops instead of while to define counter, initialize, set condition and increment/decrement - all in the same line).

While loops within while loops for a beginning programmer in C++

I'm in an introduction to C++ programming class. I am suppose to create a program that loops the whole program if a character y is inputted at the end of the program.
I cannot seem to get the loop to loop even when I input the value for y
I have defined the variables as follows:
char value, y;
float percent;
value=y;
y=value;
while (value==y)
It checks the condition the condition and runs the program the first time, however it does not loop.
The ending statement looks as follows:
"cin<< value;"
The brackets check out, too.
Is there a rule I'm missing about having multiple while loops within while loops (I have two other loops that work fine inside the bigger loop), or is it because I cannot have the "while (input==y)" as a condition?
Thank you very much
I think you should do something like
int main() {
char value = 'a', y;
do {
// do something
cout << "hello" << endl;
cin >> y;
} while (y == value);
return 0;
}
It runs the loop once, checks input character at the end and repeats if y equals to the specified value.
Doesn't cin works that way? :
cin>>value;
http://www.cplusplus.com/doc/tutorial/basic_io/
And your condition is good, but if it loop once, its because the value doesn't change (maybe because the cin didn't work because of the syntax?)

How does this bool variable work exactly?

I am new to programming, so please forgive me if my question is too basic.
For the following code, I don't know how exactly the bool variable "more" works. It says that while loop will do the content of the loop whenever the "more" is true, but
how does the computer know that the more is true? Is it smart enough to know that "more" literally means when the user inputs additional value through keyboard? Also, does it know that a negative input is not considered "more" but only positive input is considered "more"?
Inside the while loop, it says that the more is false when the input value is 0. However, it does not logically make sense that more is false when it already goes through the while loop, which only runs when the more is true!
I learned that we will get an infinite loop when "while is always true". It seems like the while loop will always be true since more = true.
Please help me out with this question!!
vector<double> salaries;
cout << "Please enter salaries, 0 to quit:" << endl;
bool more = true;
while (more)
{
double s;
cin >> s;
if (s == 0)
more = false;
else
salaries.push_back(s);
}
(1): The computer (or the compiler) is not smart enough to connect more to a literal meaning.
(2): more can be changed inside the loop, which is what happens when you enter 0. After changing more to false, the condition in while (more) is re-evaluated. As more is now false, the loop is exited.
(3): No, more is not always true, see (2).
Ok, so point by point:
1) The compiler knows that more is true because on line 3 it says:
bool more = true;
This creates the bool more and gives it the value true.
2) more is then set to false if s is equal to zero. Although more is true at the beginning of the loop there is nothing to say it can't be changed within the loop (this is called mutability).
3) Because more gets set to false within the loop, the loop will stop executing. This will only happen if someone enters 0 for the input. If this doesn't happen you are correct, the loop will get run forever.
This is a fairly common while loop construct which allows an arbitrary number of values to be added to the vector salaries. In your question you hint that positive numbers should not be allowed, it is worth noting that there is nothing in the code enforcing this. Perhaps it would be better to change the line:
if (s == 0)
to:
if (s <= 0.0)
This way the loop will stop executing if a 0 value is entered or if a negative value is entered.
In your code snippet variable more is explicitly set two times: before the loop and inside the loop if s is equal to zero
bool more = true;
while (more)
{
//...
if (s == 0)
more = false;
//..
}
Thus when more will be set to false within the body of the loop
if (s == 0)
more = false;
the loop stops its iterations because the condition in while will not true
while (more)
Take into account that the condition above is equivalent to
while (more == true)
Though there is no great sense to write such a way because variable more is already a boolean expression.
Also take into account that according to the C++ Standard
4.12 Boolean conversions
1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer
to member type can be converted to a prvalue of type bool. A zero
value, null pointer value, or null member pointer value is converted
to false; any other value is converted to true. For
direct-initialization (8.5), a prvalue of type std::nullptr_t can be
converted to a prvalue of type bool; the resulting value is false.
You could rewrite your code snippet in other way without using variable more. For example
vector<double> salaries;
cout << "Please enter salaries, 0 to quit:" << endl;
double s;
while ( cin >> s && s != 0 )
{
salaries.push_back(s);
}
Or the condition in while could be written even like
while ( cin >> s && s )
So according to the quote of the C++ Standard if s is not equal to 0 then it is converted to bool true. As for expression cin >> s then class std::istream has explicit conversion operator that converts std::cin to boolean value if the stream is not in erroneous state.
The variable more is explicitly set to true before the loop is entered. In the loop's body, if more is set false, nothing else is executed in the loop's body afterwards. The flow of execution goes again to the beginning of the loop, where the loop's condition is evaluated. As more is false, the loop's body is not executed again.
No, the computer(compiler, more appropriate) does not know the intent behind your coding, specifics behind your variables and functions, It only working on set of instructions, which need to be syntactically correct.
in while(more) it's job is to run the loop for as long as more boolean is true and skip to next instruction when false.
while(condition),here condition is checked once for every iteration, and during the iteration, the compiler does not bother to check and skip the rest of the code upon more being false. the condition is checked only before beginning an iteration.
Absolutely, just assume while(true){set of instructions;} the condition is always true and therefore the block of code is always executed and we call this an Infinite Loop.
Well, it seems that you don't really understand the way your compiler works.
First of all, your computer is not smart or dumb, it's merely a machine and interprets whatever you give them to. So, it all comes to the way you have programmed your program. Having said that we move on:
The
while(condition) {
commands;
}
loop works basically as follows:
It checks the condition whatever that might be at the time it your
program flow enters the loop.
It continues to execute whatever commands are if and only if the previous checked condition was true.
If it wasn't true then your programs continues to execute whatever command follow your while loop.
When the execution of commands have finished it goes again to check the condition in while.
Again, if it's true it carries on with commands.
If not, then again it continues to the following your while commands.
So, to sum up, your compiler, computer or your digital friend does not check for logical flows in how you name your variables, if false does not make sense, etc. It merely checks if condition is true. That's it.
Finally an infinite loop will occur if the initial condition was true when entering the loop and when exiting the loop always continues to be true (not does not change inside the loop because it could change and also get a true values when exiting the loop).
You have some misunderstandings with how things work in C++. You can think of your program as an abstract machine. Each variable is a storage location that maintains some state. The more variable is an example of this state. You can think of the variable as a location in memory that maintains the value that you give it. The total program state is allowed to change throughout the duration of the runtime of the program.
Each assignment (the = operator) sets the state of the variable to the value on the right hand side of the assignment.
So when you say:
bool more = true;
The storage location named more is set to the value true. The storage location will remain true until you assign a new value to it.
Note that in C++ statements are evaluated sequentially. Since the values of the variables may change over time, the order of the statements matters.
Later on when you say:
while (more)
{
// ...
}
The first time that more is evaluated, it is true, but again, since more is a variable, that value may change over time.
Once you are inside the while loop, the more variable is conditionally assigned false when the variable s is equal to 0. Notice that the == is truly an equality check unlike the = operator.
if (s == 0)
more = false;
Note that you should be aware that s is of type double and the literal 0 is of type int. Fortunately for you, this will work since C++ will automatically promote the int to a double type to do the equality comparison. However, it probably makes since to use a literal 0.0 to be clear that you expect for s to be a double.
Since the value of s is dependent on the value that is read from cin, the equality condition will sometimes be true and sometimes false depending on what is entered by the user. But if more is assigned false, it when then cause the while loop to terminate on its next iteration. In other words, when you reach the close brace } the program will repeat back to the beginning of the while and try to re-evaluate more, at that point, when more is false the while loop will end.
vector<double> salaries;
cout << "Please enter salaries, 0 to quit:" << endl;
bool more = true;
while (more)
{
double s;
cin >> s;
if (s == 0)
more = false;
else
salaries.push_back(s);
}
A while loop will iterate over and over until the condition between the ()is not met. When you start the cycle you start with bool more = true; That way you're telling the while(more) loop to keep iterating while more is true. Inside the code you ask for input with cin >> s; and if the input is 0 the variable more will change to false, it will iterate again and since while(more) is awaiting for the morevariable to be true the condition won't be true and the cycle will end. If you input other value than 0 the cycle will store that value into the vector<double> salaries vector.
One way for getting the values that were stored in the vector is:
for(int i = 0; i<salaries.size(); i++){
cout<< salaries[i] << endl;
}
In which case you're telling the compiler to iterate with a variable called i starting from the value 0 until the value of i is < than the value of salaries.size(), for each iteration, i will increase and when the condition is no longer met, the cycle will end.
As a recomendation, use the std namespace for your types, it will be of help in future code to avoid bringing everything from the std namespace into your code.
std::vector<double> salaries;
std::cout << "Please enter salaries, 0 to quit:" << std::endl;
bool more = true;
while (more)
{
double s;
std::cin >> s;
if (s == 0)
more = false;
else
salaries.push_back(s);
}
and
for(int i = 0; i<salaries.size(); i++){
std::cout<< salaries[i] << std::endl;
}

Check multiple OR operators in IF statement

I have the following C++ code:
if(x==y||m==n){
cout<<"Your message"<<endl;
}
If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".
Is there a way to print each "Your message" independently based on each condition using a single if statement?
The output would be identical to the below using multiple if statements.
if(x==y){
cout<<"Your message"<<endl;
}
if (m==n){
cout<<"Your message"<<endl;
}
Not that I'd ever do it this way, but ...
for(int i = 0; i < (x==y)+(m==n); ++i) {
std::cout << "Your message\n";
}
Let me expand on this. I'd never do it this way because it violates two principles:
1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.
2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.
Given these two principles, here is how I would actually code it:
if(x==y) {
std::cout << "Your x-y message\n";
}
if(m==n) {
std::cout << "Your m-n message\n";
}
Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.
I don't think that's possible. What you have inside your bracket is a statement which is either true or false, there's no such thing like a true/true or true/false statement. What you could do is a do/while loop with a break statement. But I don't think that's the way to go. Why do you want to avoid two if statements?
single "|" or "&" gaurantees both side evaluation even if the result can be determined by left side operator alone.
You could do something like this, to build up the "message":
string msg = "Your Message\n";
string buildSt = x == y ? m == n ? msg + msg : msg : m == n ? msg : "";
Compiler checks only one condition when both are true because you've connected your conditions with OR.
If even one condition in ORs chain is true there is no need to check others as a result already true and will be false if one of them is false. So if you think that your logic is right then there is no need to do multiple checks. Your code is asking that you will print a message if one of the conditions is true and program doing it. If you want something special for a case when both conditions are true then add it separately. Shortly you should never expect from the compiler to do all checks in the expressions connected by OR.
Regards,
Davit
Tested code:
#include <iostream>
#include <string>
using namespace std;
void main() {
int x=1;
int y=1;
int m=1;
int n=1;
string mess1="Your message 1\n";
string mess2="Your message 2\n";
cout<<((x==y)?mess1:"")+((m==n)?mess2:"");
getchar();
}
If you are trying to see if both statements are true an && is what you will want to use.
Take a look at Boolean Operators to see all of the possible options when comparing boolean (true/false) values.
To answer your question:
if ((x==y) && (m==n))
{
cout<<"Your Message"<<endl<<"Your Message"<<endl;
}
else if((x==y) || (m==n))
{
cout<<"Your Message"<<endl;
}