Break from a while loop repeating - c++

What I am trying to achieve is the user enters a value followed by a measurement. this is then placed either as smallest, largest or in between.
A count of how many values have been entered is kept. and the total of all the values in meters.
Initially the program works but when I type the break character, the program repeats the same line. What I do want is the program to end printing lines 129 and 130. Here's my code.
int main()
{
double var1; //the variable entered by the user
double sum; //the sum of calculations to convert into centimeters
double total=0/100; //converts to meters
int e=0; //will be used to count how many numbers were entered
string measurment; //the users desired measurement input
string centimeter = "cm";
string meter = "m"; //these are used to compare the users measurement input
string inch = "in";
string foot = "ft";
char d='t';//this will be used to break the loop (t is just the default)
char a='a';
char c='c';
char m='m';//char a-f are used for a switch
char i='i';
char f='f';
double small=20000;
double large=0;
double cm=1;
double me=100;//centimeters
double in=2.54; //centimeters
double ft=12; //inches
//the following code creates a break when the character is entered.
while(d!='q')//break rule
{
if(false)
break;
cout<<"please enter a double and a unit of measurement."<<'\n';
cin >>var1>>measurment;
e++;
// the following portion of code sets the char for the switch which
// which will be used in the following code. it will also perform the
// the math which will calculate between distances.
if (measurment==centimeter)
{
a=c;
sum=var1*cm;
}
else if (measurment==meter)
{
a=m;
sum=var1*me;
}
else if (measurment==inch)
{
a=i;
sum=var1*in;
}
else if (measurment==foot)
{
a=f;
sum=(var1*ft)*in;
}
else
{
cout<<"I am sorry. But, that is not a valid measurement for this program."<<'\n';
}
//the following code places the number entered into either
//smallest largest or in between.
if (sum<small)
{
small=sum;
total+=sum;
switch(a){
case'c':
cout<<small/cm<<centimeter<<" is the smallest measurement so far."<<'\n';
break;
case'm':
cout<<small/me<<meter<<" is the smallest measurement so far."<<'\n';
break;
case'i':
cout<<small/in<<inch<<" is the smallest measurement so far."<<'\n';
break;
case'f':
cout<<(small/in)/ft<<foot<<" is the smallest measurement so far."<<'\n';
break;
}
}
else if (sum>large)
{
large=sum;
total+=sum;
switch(a){
case'c':
cout<<large/cm<<centimeter<<" is the largest measurement so far."<<'\n';
break;
case'm':
cout<<large/me<<meter<<" is the largest measurement so far."<<'\n';
break;
case'i':
cout<<large/in<<inch<<" is the largest measurement so far."<<'\n';
break;
case'f':
cout<<(large/in)/ft<<foot<<" is the largest measurement so far."<<'\n';
break;
}
}
else if(sum>small&&sum<large)
{
total+=sum;
switch(a){
case'c':
cout<<var1<<centimeter<<" is neither the longest or shortest measurement."<<'\n';
break;
case'm':
cout<<var1<<meter<<" is neither the longest or shortest measurement."<<'\n';
break;
case'i':
cout<<var1<<inch<<" is neither the longest or shortest measurement."<<'\n';
break;
case'f':
cout<<var1<<foot<<" is neither the longest or shortest measurement."<<'\n';
break;
}
}
}
//after the break, this should be printed to screen
cout<<"Of a total of "<<e<<" entries. "<<small<<meter<<" is the smallest length."<<'\n';
cout<<"And "<<large<<meter<<" is the largest length. "<<total<<meter<<" is the total length."<<'\n';
return 0;
}
Apologies if the code is too long. I wasn't too sure what you would need. I have checked numerous posts and websites and tried different break codes but to no avail. I am stuck.

Maybe I am missing something glaring but the proper way to break a while loop is to make the conditional fail. Breaks are for FOR loops since they can be a non conditional loop. Instead of breaking out of the while loop you simply need to make the variable
d ='q'
Where ever you want to break out of the while. Note that the breaks are still valid to break out of a switch statement so if you need that then keep those breaks there.
sorry for any typos or if I missed a glaring issue, I am mobile and may have missed something

The first break statement will never be executed, because the 'if' condition is always false. All of the other break statements break from the switch statement, but not the while loop, so the loop will keep looping forever.
If I understand you correctly, I think you should change the 'false' to 'true' in the first 'if' condition. That being said, the code might overall have a bad design, but you mentioned you are a beginner, so I suggest you also learn how to optimize your code and write efficiently. Good luck.

Thank you for the help. Solved the problem by activating the break with my counter.
while(true)
{
if(e==d)
break;
When e reaches d value. The code breaks and outputs the information I want.
Its not how I wanted it to work but as stated. I think its poor programming.
thanks for your help guys, appreciated.

Related

cout doesn't works properly on my program, can somebody help me?

enter image description hereI am using the STL in c++ and inside a bucle the cout doesn't prints correctly a float.
my program ads values to a vector and then passes it to a function to see if the condition exist, actually it works perfectly but just the cout doesn't word, I already tried using printf() but it gave the same result.
note:please algo give me feedback on my question is the first time i do one and English is not my natal language
my code:
#include<bits/stdc++.h>
#include<vector>
using namespace std;
void isthereanumber(vector<float> array);
int main(){
string ans;vector<float> array;float number;
do{
fflush(stdin);
cout<<"insert a value for the vector: "<<endl;
cin>>number;
array.push_back(number);
fflush(stdin);
cout<<"would you like to keep adding values to the vector? "<<endl;
getline(cin,ans);
}while(ans.compare("yes")==0);
isthereanumber(array);
return 0;
}
void isthereanumber(vector<float> array){
float suma =0;
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+array[*j];
}
}
if(suma=array[*i]){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}
cout<<"there is not a number with such a condition: ";
return;
}
As stated by cleggus already there are some issues present. Those need to be adressed first. After that there's a logical error in that suma just keeps growing.
Given the input 5,5,10 once we test for 10 we would like suma to be set to 0 again for it to work but it will be something like 30 now instead.
That can be solved by moving suma inside the outer loop.
Working example for input 5,5,10: https://godbolt.org/z/gHT6jg
I think you may have a couple of issues...
In your for loops you are creating iterators to the vector, but rather than just dereferencing them to access the indexed element you are dereferencing them and then using that as an index to the same vector.
Also Your last if statement has an assignment = rather than a comparison ==.
I believe this is closer to what you are trying to achieve (sorry I haven't had time to compile and check):
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+*j;
}
}
if(suma==*i){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}

Find the next palindrome

Given a number, I am trying to find the smallest palindrome number greater than given number. Here is my code:
#include<bits/stdc++.h>
using namespace std;
char a[1000005];
int main(){
int t,len,ni,nj,nk,i,j,k;
cin>>t;
while(t--){
cin>>a;
char ch=getchar();
len=strlen(a);
k=len-1;
for(i=0;i<len;i++){
if(a[i]!='9'){
break;
}
}
if(i==len){ //if all digits are 9
for(i=len-1;i>0;i--){
a[i]='0';
}
a[0]='1';
a[len]='1';
a[len+1]='\0';
}
else{
for(i=0;i<len/2;i++){
if(a[i]!=a[len-1-i]){ //check if number is already palindrome
break;
}
}
if(i==len/2){ //add 1 if it is already palindrome
j=len-1;
while(1){
nj=((int)a[j])-48;
nj++;
if(nj<10){
a[j]=nj+48;
break;
}
else{
a[j]=48;
j--;
}
}
}
for(i=0;i<len/2;i++){
if(a[i]==a[k]){ //compare first with last,second with second last...
k--;
}
else{
nk=((int)a[k])-48;
ni=((int)a[i])-48;
if(nk<ni){
a[k]=ni+48;
}
else{
j=k; a[j]=ni+48; j--;
while(1){
nj=((int)a[j])-48;
nj++;
if(nj<10){
a[j]=nj+48;
break;
}
else{
a[j]=48;
j--;
}
}
if(j<=i){
i=j-1;
k=len-j;
}
}
k--;
}
}
if(len%2==0){
a[len/2]=a[len/2-1];
}
}
cout<<a<<endl;
}
return 0;
}
My code is working fine for all the inputs I have tried, but it is not getting accepted. Is my code right?
Some of the reasons why this code might have been rejected are:
length of code: finding the smallest palindromic number greater than a given input can be done with a lot less code.
memory efficiency: ~1MB of memory is by far too much for operations that can easily be done in-place. The total memory required would simply be the size of the number plus a few additional integer-vars.
runtime efficiency: This problem could be solved in O(n), where n is the number of digits of the number. I don't quite get the way your code works - and to be honest I won't put any effort in understanding that mess -, but that doesn't exactly look linear (or even close to it).
#include <bits/stdc++.h>: This header is GNU-specific, compiler-specific, ... . This code might not even compile if the tester uses another compiler. Apart from that the compilation takes more time with this header and will produce a larger executable than if you'd simply include the required headers. The reasons why it's a bad idea to use this header are described here in a more extensive way.
I can only speculate about the reason(s) why the solution really was rejected. The least information required to answer this would be a link to the judge that rejected it - which should aswell give a reason why it was rejected.

I have an error with my return statements that I don't know to fix

In a text adventure game that I am making, all the different places are run my different functions. In my diner, market, and supply store, I have a switch statement that takes numbers 1-10. All 1-9 work, but 10 doesn't. All of these methods return back to a method called TownCenter(), but on these 3, when I do return, you have to spam it in order for it to work. Here is a code example:
void Diner(){
int answer;
cout << "Blah, blah. Type '0' to go back to town.\n";
cin >> answer;
switch (answer){
case 0:
return;
break;
}
Diner()
}
Every time you type 0, it would just go to Diner() again. It eventually works if you spam 0 over and over, but why won't it work all the time?
I don't think there is any error with the code, except for the following considerations:
Missing semicolon after Diner() in line 10.
The break; statement is not required as return; is being used before it.
I don't think you mean to use recursion here. I would suggest using while loops while people are in individual locations. By calling the same location again at the end of your case statement to go back to the same area, you are going deeper in the callstack, requiring more "exits" to "leave" the room.
A do-while loop like the following would work nicely:
int answer;
do {
cout << "Blah, blah. Type '0' to go back to town.\n";
cin >> answer;
switch (answer){
// other case statements
case 0:
break;
}
} while (answer != 0);
Notice I don't call Diner() again at the end. Getting it to process the same room until the "leave" is accomplished by the loop instead of unnecessary recursion.

How can I properly set a condition for an specific space in array?

I'm Developing an small app for practice purposes in C++, I actually suceeded developing this algorithm without using arrays, but right now I want to do it using an Array. The program should accept four grades 2 of 15 points practices (First and third value), two of 20 points (Second and fourth values) and one of 30 points. this is my code:
int main(int argc, char** argv){
int grades[5];
int i;
int sum=0;
for(i=0; i<5; i++){
cin >> grades[i];
sum+=grades[i];
if(grades[0]>15||grades[1]>20){
cout<<"ERROR"<<endl;
break;
}else if(grades[2]||grades[3]){
cout<<"ERROR"<<endl;
break;
}if(grades[4]>30){
cout <<"ERROR"<<endl;
break;
}
}
}
The issue here is that it should not be printing Error on console and break it from continuing, only if the condition is met, at this point if I input values even within the condition's grace, it prints out "Error" and stops.
I'm not really looking for someone to solve this issue, I'm looking to know what I'm doing wrong without getting someone to solve it for me, in proper words, I'm looking for tips/hints.
This line here
}else if(grades[2]||grades[3]){
cout<<"ERROR"<<endl;
break;
}
will cause your error to display at any time your elements at indices 2 or 3 are non zero. You dont initialise your array elements so it is quite possible that the values are nonzero when your loop starts. To ensure that they are not, you could assign zero to all elements before you start. I am not sure what your code is trying to do, but when the user enters anything other than zero for the cin at i = 2 and i = 3 your loop will break with error output (assuming that the first if confition in your if-else block is not satisfied but if that condition was satisfied your loop would also exit anyway)

C++ Prime factor program 2 problems

Okay so I"m writing a program (in C++) that is supposed to take a number, go through it, find out if it's factors are prime, if so add that to a sum, and then output the sum of all of the imputed number's prime factors.
My program successfully seems to do this however it has 2 problems,
1) The number I am supposed to test to see the sum of the prime factors of this number (600851475143) but it's too big for an int. I'm not sure what other variable type to use, or which variable's types to change. I would really like a clear explanation on this if at all possible.
2) For some reason, when the program checks to see if 1 is a factor of the number, and then checks to see if 1 is prime, it says 1 is prime, even though the first step of the function for checking to see if it's prime is that if it's 1 then it isn't prime. I found a fix for this, by telling it to subtract 1 from the very last value for the sum of all prime factors. However, this is a fix, not really finding the problem. If someone could point out at least where the problem is I would appreciate it!
Here's the code, if you have questions, please ask!
#include <iostream>
using namespace std;
bool prime (int recievedvalue) { //starts a function that returns a boolean with parameters being a factor from a number
int j =1;
int remainderprime = 0;
bool ended = false;
while (ended == false){ //runs loop while primality is undetermined
if (recievedvalue == 1){ //if the recieved value is a 1 it isn't prime
//not prime
break; // breaks loop
return false;
}
remainderprime=recievedvalue%j; //gives a remainder for testing
if ((remainderprime==0 && j>2) && (j!=recievedvalue || j == 4)){ //shows under which conditions it isn't prime
ended=true;
//not prime
return false;
}
else if (j==1){
j++;
}
else if ( recievedvalue==2 || j==recievedvalue ){ // shows what conditions it is prime
ended = true;
//prime
return true;
}
else {
j++;
}
}
}
int multiple(int tbfactor){ //factors and then checks to see if factors are prime, then adds all prime factors together
//parameter is number to be factored
int sum = 0;
bool primetest = false;
int remainderfact;
int i=1;
while (i<=tbfactor){ //checks if a i is a factor of tbfactor
remainderfact=tbfactor%i;
if (remainderfact==0){ //if it is a factor it checks if it is a prime
primetest = prime(i);
}
if (primetest ==true){ //if it is prime it add that to the sum
sum += i;
primetest=false;
}
i++;
}
sum --; // for some reason it always ads 1 as a prime number so this is my fix for it
return sum;
}
int main()
{
int input;
int output;
cout << "Enter number to find the sum of all it's prime factors: ";
cin >> input;
output = multiple(input);
cout << output;
return 0;
}
I'm really new to this, like a few days or so, so I'm very unfamiliar with stuff right now so please explain easily for me! I look forward to your help! Thanks!
For 1), you need to use a larger datatype. A 64-bit integer should be enough here, so change your ints to whatever the 64-bit integer type is called on your platform (probably long, or maybe long long).
For 2), the problem appears to be that you have a break before your return false. The break causes the code to stop the while loop immediately and continues execution immediately after the loop. It doesn't appear that the return value is ever assigned in that case (which your compiler should be warning you about), so the actual value returned is effectively arbitrary.
While others have pointed out a problem with your data types, there's a few problems with the structure of the first function that immediately caught my eye. (BTW, your indentation is enraging.) Look at this stripped-down version:
bool prime (int recievedvalue) {
// ...
bool ended = false;
while (ended == false){
if (...){
break; // jumps _behind_ the loop
return false;
}
// ...
if (...) {
ended=true;
return false; // leaves function returning true
}
else if (...) {
// ...
}
else if (...) {
ended = true;
return true; // leaves function returning false
}
else {
// ...
}
}
// behind the loop
// leaves function returning random value
}
For one, every time you set the loop control variable ended, you leave the loop anyway using some other means, so this variable isn't needed. A while(true) or for(;;) would suffice.
Also, that break jumps behind the loop's body, but there isn't a statement there, so the code leaves the function without explicitly returning anything! That's invoking so-called Undefined Behavior. (According to the C++ standard, your program is, from this point on, free to do whatever it pleases, including returning random values (most implementations will do that), formatting your HD, invoking nasty Nasal Demons on you, or returning exactly what you expected, but only on Sundays.)
Finally, that break occurs right before a return false; which is therefor never reached. Actually your compiler should warn about that. If it doesn't, you're likely not compiling at the highest warning level. (You should turn this on. Always try to cleanly compile your code at the highest warning level.) If it does, learn to pay attention to compiler warnings. They are a very important tool for diagnosing problems during compilation. (Remember: Errors diagnosed during compilation need no testing and never make it to the customer.)
Use either a 64 bits number on a 64 bits system, or use a library that does arbitrary precision arithmetic
Remove the break before the return false. Because of the break, execution is resumed outside the loop and return false is never executed.
To store values larger than 4 bytes (the capacity of an int) you have a variety of options. Refer to this page for those options. As to why you're program is returning true for the check on whether or not 1 is prime, check out this section of code:
if (recievedvalue == 1){ //if the recieved value is a 1 it isn't prime
//not prime
break; // breaks loop
return false;
}
The break statement will exit and return false will never be reached. To solve the problem, remove the break statement.