If statements in for loops - c++

how do I run only one of those if statements in a for loop? For example i have an input of 5...and i just want it to print five...but whenever i run this code, it will execute all if statement..please help me
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int a;
int b;
cin >> a;
for (a = 0; 0<a<10; a++)
{
if (a == 1)
{
cout << "one";
}
if (a == 2)
{
cout << "two";
}
if (a == 3)
{
cout << "three";
}
if (a == 4)
{
cout << "four";
}
if (a == 5)
{
cout << "five";
}
if (a == 6)
{
cout << "six";
}
if (a == 7)
{
cout << "seven";
}
if (a == 8)
{
cout << "eight";
}
if (a == 9)
{
cout << "nine";
}
else if (a > 9 && a%2 == 0)
{
cout << "even";
}
else if (a > 9 && a&2 != 0)
{
cout << "odd";
}
}
return 0;
}

The problem seems to be the for loop. Your program accepts a value for a as an input, but then as soon as the loop begins, it resets the value of a to 0 (for (a = 0;...
Therefore it's looping 10 times, and on each loop a will have a different value, starting from 0 and ending at 9. This means that all of your if statements will get hit at some point in the execution, generally one on each of the loops round the for.
To get your expected behaviour " input of 5...and i just want it to print five", simply remove the for loop from your code.

Your unnecessary for loop trashes the input value of a and loops forever! (At least until you overflow your signed type a).
You are replacing a by using it as the counter in the for loop! If you only ever want one output, then drop the for loop completely. If your for loop were to remain then your expression 0 < a < 10 ought to be recast as 0 < a && a < 10 : formally 0 < a < 10 is evaluated as (0 < a) < 10 which is either true < 10 or false < 10 which is always true.
Also consider refactoring your if else to set up explicitly mutually exclusive statements:
if (a == 1){
cout << "one";
} else if (a == 2){
cout << "two";
/*and so on*/
} else {
/*all other cases*/
}
Although in this case you might want to consider a switch block:
switch (a){
case 1:
cout << "one";
break; // to stop program control flowing into the next case
case 2:
cout << "two";
break;
/*and so on*/
default:
/*all other cases*/
}

if () {
} else if () {
}
Although,
switch() {
}
will be more efficient in your case.
Update 1
#Aleph0
Below is the solution
int main() {
int a;
cin >> a;
switch (a) {
case 1: cout << "one"; break;
case 2: cout << "two"; break;
case 3: cout << "three"; break;
case 4: cout << "four"; break;
case 5: cout << "five"; break;
case 6: cout << "six"; break;
case 7: cout << "seven"; break;
case 8: cout << "eight"; break;
case 9: cout << "nine"; break;
default: cout << ((a & (1 << 31)) ? "negative" : (a & 1) ? "odd" : "even"); break;
}
}
Question has been asked to do following
i have an input of 5...and i just want it to print five
And, someone has correctly mentioned above, for loop is immaterial here.

Related

C++ pull a card from deck

I'm trying to create a program that will pull a card from a deck of 52 regular playing cards.
Suits: Heart, Spad, Diamond, Club.
Rank: A,2,3,4,5,6,7,8,9,10,J,Q,K.
This should be the output:
Let's pull a card!
This time we got AH
Wanna pull a card again?
y
This time we got 3J
Wanna pull a card again?
n
My output is:
Let's pull a card!
DKThis time we got 00
Wanna pull a card again?
n
This is my code:
#include <iostream>
#include <ctime>
using namespace std;
// Function Declaration
int rankCard(), suitCard();
int main()
{
srand(time(0));
char answer;
cout << "Let's pull a card!" << endl;
do {
cout << "This time we got " << rankCard() << suitCard() << endl;
cout << "Wanna pull a card again?" << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
int rankCard() {
int rank = (rand() % 13) + 1;
switch (rank) {
case 1: cout << "A";
break;
case 10: cout << "T";
break;
case 11: cout << "J";
break;
case 12: cout << "Q";
break;
case 13: cout << "K";
break;
default: cout << rank;
break;
}
return 0;
}
int suitCard() {
int suit = (rand() % 4) + 1;
switch (suit) {
case 1: cout << "H";
break;
case 2: cout << "D";
break;
case 3: cout << "C";
break;
case 4: cout << "S";
break;
}
return 0;
}
I can't figure out why the cards pulled (DK) are in that position and why I also get the 00. What am I doing wrong? Thanks
Your calls to rankCard() and suitCard() always return 0.
That 0 value is what's passed to cout in your main function.
The weird 'DK' is caused by the calls to cout inside rankCard and suitCard.
You could modify your functions to avoid the confusion:
#include <string>
std::string rankCard() {
int rank = (rand() % 13) + 1;
switch (rank) {
case 1: return "A";
case 10: return "T";
case 11: return "J";
case 12: return "Q";
case 13: return "K";
default: return std::to_string( rank );
}
return "";
}
std::string suitCard() {
int suit = (rand() % 4) + 1;
switch (suit) {
case 1: return "H";
case 2: return "D";
case 3: return "C";
case 4: return "S";
}
return "";
}
This line:
cout << "This time we got " << rankCard() << suitCard() << endl;
So those functions print the card, and then they return 0, so if you call them in cout, they will do their thing witch is printing the card and then print the return value witch is 0.
What you can do is to call them outside the cout, just do:
//...
cout << "This time we got ";
rankCard();
suitCard();
cout << endl;
cout << "Wanna pull a card again?" << endl;
//...
Personally I would refactor the functions to return the respective card char:
Live sample
const char rankCard() {
int rank = (rand() % 13) + 1;
switch (rank) {
case 1: return 'A';
case 10: return 'T';
case 11: return 'J';
case 12: return 'Q';
case 13: return 'K';
default: return rank + 48; // convert to decimal digit
}
}
const char suitCard() {
int suit = (rand() % 4) + 1;
switch (suit) {
case 1: return 'H';
case 2: return 'D';
case 3: return 'C';
case 4: return 'S';
default: return 0; //ASCII code for null character
}
}

Is there a proper way to close program from within function?

I am currently making a program that has menu and sub menus and i'd like to have an opportunity to close entire thing from within any sub menu (which is inside function). I know i could do it different way (both way i have it now and way i know it could be done are below) but for future use (i could prove useful) i would like to know:
Is there a way to properly close the program from within a function ?
I've read a few answers here and here and from what i've gotten out of it is:
I should not simply terminate the code
I should not use any system specific code as to avoid compatibilty issues
A bit of clarifiacation - that is program for my personal educational purposes so it is kind of unnecessary to worry about it but i'd rather learn propper ways of dealing with those situations at the beginning than have to learn them anew once i discover how to do them later and have to go back and fix it.
As for code samples (using visual studio 2017):
//skipping unrelevant to question bits of code
void sub_menu()
{
char a=0;
system("cls"); //yet to get changed when i'll find other way of clearing screen
std::cout << "Pick function:\n"
<< "---------------------------------------------------------\n"
<< "1.Foobar_1\n"
<<"---------------------------------------------------------\n"
<< "ESC to go back to menu menu\n"
<< "x to close";
while (a != 27)
{
a = _getch();
switch (a)
{
case 49:foobar_1(); break;
case 120:
case 88: system("exit"); break; //i'd like to replace that part
default: break;
};
};
return;
}
void main()
{
char a=0;
system("cls"); //yet to get changed when i'll find other way of clearing screen
std::cout << "Pick what you want to do:\n"
<< "---------------------------------------------------------\n"
<< "1.Sub_menu\n"
<< "2.foo\n"
<< "3.bar\n"
<<"---------------------------------------------------------\n"
<< "ESC to close\n"
while (a != 27)
{
a = _getch();
switch (a)
{
case 49:sub_menu(); break;
case 50:foo(); break;
case 51:bar(); break;
case 120:
case 88: system("exit"); break; //i'd like to replace that part
default: break;
};
};
return;
}
The way i could implement it (i think it is merely byapssing the issue):
//skipping unrelevant to question bits of code
void main()
{
char a=0;
system("cls"); //yet to get changed when i'll find other way of clearing screen
std::cout << "Pick what you want to do:\n"
<< "---------------------------------------------------------\n"
<< "1.Sub_menu\n"
<< "2.foo\n"
<< "3.bar\n"
<<"---------------------------------------------------------\n"
<< "ESC to close\n"
while (a != 27)
{
a = _getch();
switch (a)
{
case 49:
{
{
char b=0;
system("cls");
std::cout << "Pick function:\n"
<< "---------------------------------------------------------\n"
<< "1.Foobar_1\n"
<<"---------------------------------------------------------\n"
<< "ESC to go back to menu menu\n"
<< "x to close";
while (b != 27)
{
b = _getch();
switch (b)
{
case 49:foobar_1(); break;
case 120:
case 88: a=27; break;
default: break;
};
};
return;
}
}
; break;
case 50:foo(); break;
case 51:bar(); break;
case 120:
case 88: system("exit"); break; //i'd like to replace that part
default: break;
};
};
return;
}
This Code will work as you mentioned.
int main()
{
int a;
while (true)
{
system("cls"); //yet to get changed when i'll find other way of clearing screen
cout << "Pick what you want to do:\n"
<< "---------------------------------------------------------\n"
<< "1.Sub_menu\n"
<< "2.foo\n"
<< "3.bar\n"
<< "---------------------------------------------------------\n"
<< "0. to close\n";
cin >> a ;
if (a == 0)
{
return 0 ;
}
else if (a == 1)
{
char b;
while (true)
{
system("cls");
cout << "Pick function:\n"
<< "---------------------------------------------------------\n"
<< "1.Foobar_1\n"
<< "---------------------------------------------------------\n"
<< "b to go back to menu menu\n"
<< "x to close\n";
cin >> b;
if (b == '1')
{
foobar_1();
}
else if (b == 'B' || b == 'b')
{
break;
}
else if (b == 'x' || b == 'X')
{
return 0;
}
else
{
cout << "invalid input";
}
}
}
else if (a == 2)
{
foo();
}
else if (a == 3)
{
bar();
}
else
{
cout << "invalid input";
}
}
return 0;
}

My program won't print anything...

So I'm working on building a calculator that mimics the ones we use everyday. What I have shown is the logic within my function.
Previously when I had my cout lines (deleted, not shown anymore) to see if my "y" was being correctly stores, and my two variables, finalNum1 & 2, everything was working, but when going back, trying to add new cout lines, nothing prints. If there are more issues, feel free to point them out, but this code is unfinished, my main concern is nothing is printing, I understand this code still needs work. If anyone can help that'd be greatly appreciated!
int Calculator::calculate()
{
if (userInput[0] != 'q' || 'Q') // Checks for user input "Quit" or "quit"
{
int stringSize;
std::cin >> userInput; // User Input
stringSize = userInput.length();
int y = 0;
while (y < stringSize)
{
if (isdigit(userInput[y]))
{}
else
{
posi = y;
}
y++;
}
first = userInput.substr(0,posi);
second = userInput.substr(posi+1,y);
finalNum1 = std::stoi(first); // Sigbart error
finalNum2 = std::stoi(second);
std::cout << finalNum1 + finalNum2; // won't print
switch (userInput[posi])
{
case '+':
std::cout << finalNum1 + finalNum2;
break;
case '-':
std::cout << finalNum1 - finalNum2;
break;
case '*':
std::cout << finalNum1 * finalNum2;
break;
case '/':
std::cout << finalNum1 / finalNum2;
break;
case '%':
std::cout << finalNum1 % finalNum2;
break;
}
}
else
std::cout << "Goodbye";
return 0;
}
For printing integer it is easier if you cast them to string.
using namespace std;
float tmp = finalNumber1 + finalNumber2;
string out = to_string(tmp);
cout << tmp << endl;
Then another thing. You should use for instead of while.

Decimal to binary/hex using arrays

I'm having trouble with the hexadecimal part of my c++ program. When I use the switch for hexadecimal nothing returns. also for some reason my binary conversion has a leading 0 I cant seem to get rid of.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
void binary(int, int);
void hex(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
int numb, base;
cout << "Enter a decimel number : ";
cin >> numb;
cout << "Enter a base you want number switched to: ";
cin >> base;
switch (base){
case 2: binary(numb, base); break;
case 8: break;
case 16: hex(numb, base); break;
default: break;
}
}
void binary(int numb, int base)
{
int bin[32] = { 0 };
int i = 0;
do
{
bin[i] = numb%base;
numb = numb / base;
i++;
} while (numb != 0);
cout << "\n";
while (i >= 0){
cout << bin[i];
i--;
}
cout << endl << endl;
}
void hex(int numb, int base){
int i;
int hex[10] = { 0 };
for (i=0; i > 10; i++){
hex[i] = numb%base;
numb = numb / base;
for (i; i > 0; i--)
{
if (hex[i] >= 10)
{
switch (hex[i]){
case 10: cout << "A"; break;
case 11: cout << "B"; break;
case 12: cout << "C"; break;
case 13: cout << "D"; break;
case 14: cout << "E"; break;
case 15: cout << "F"; break;
default: break;
}
}
cout << hex[i];
}
}
cout << endl;
}
binary
The problem is after the first loop, i is one greater than the last index. Just for example, say you enter 1: the do...while loop is entered, the digit 1 is put in array index 0, then i is incremented to 1.
Then, in the second loop, both indexes 1 and 0 are printed. You can solve this by decrementing i before entering this loop:
i--;
while (i >= 0){...}
You should be doing something like that anyway, because if you ended up using all 32 digits, you would try to access bin[32] and the program may crash or output gibberish.
hex
The first loop's condition is infinite:
for (i = 0; i >= 0; i++){...}
It should be the same as your condition in binary:
for (i = 0; numb != 0; i++){...}
But you are not done yet because I've noticed you also have a bug in your printing:
if (hex[i] >= 10)
{
switch (hex[i])
{
case 10:
cout << "A";
break;
...
}
}
cout << hex[i];
If hex[i] is greater than or equal to 10, it gets printed twice, once as a hex letter and once as a decimal number. To solve this you could, for example, use continue instead of break in your switch (to skip the second print), or use else:
if (hex[i] >= 10)
{
switch (hex[i])
{
case 10:
cout << "A";
break;
...
}
}
else
{
cout << hex[i];
}
You also need to make the same correction as in binary:
// decrementing i before entering the loop
// vvv
for (i--; i >= 0; i--){...}
Your revision is not correct, hex should not have a nested loop. It was fine before, just with the corrections I've pointed out.

Using the OR Operator with Strings in C++

To start, I'm trying to make a GPA calculator for my class.
I know how to compare strings, so I'm good there. The issue I'm having is that I'm trying to set up a situation so when the user inputs anything other than a letter grade value, it will return an error message. I've set up two arrays, one that stores string values and another that stores integral values. The idea was to use the string array to store the entered grade letter inputs, then use those to determine the GPA value for each class. It would then store that value into the integral array. I hate to be obnoxious, but here's the code for the first section alone:
void gpaCalSetClassNum5(){
string mathWeight5;
string scienceWeight5;
string historyWeight5;
string englishWeight5;
string elective1Weight5;
string elective2Weight5;
string gpaClassSet5[] = {"null", "null", "null", "null", "null"};
int gpaClassSet5int[] = {};
cout << "Enter the grade value of each of your classes." << endl;
/////////////////////////
MATH:
cout << "Math" << endl;
cin >> gpaClassSet5[0];
if (gpaClassSet5[0] == "A") {
gpaClassSet5int[0] = 4;
} else if (gpaClassSet5[0] == "a") {
gpaClassSet5int[0] = 4;
} else if (gpaClassSet5[0] == "B") {
gpaClassSet5int[0] = 3;
} else if (gpaClassSet5[0] == "b") {
gpaClassSet5int[0] = 3;
} else if (gpaClassSet5[0] == "C") {
gpaClassSet5int[0] = 2;
} else if (gpaClassSet5[0] == "c") {
gpaClassSet5int[0] = 2;
} else if (gpaClassSet5[0] == "D") {
gpaClassSet5int[0] = 1;
} else if (gpaClassSet5[0] == "d") {
gpaClassSet5int[0] = 1;
} else if (gpaClassSet5[0] == "F") {
gpaClassSet5int[0] = 0;
} else if (gpaClassSet5[0] == "f") {
gpaClassSet5int[0] = 0;
} else if (gpaClassSet5[0] != ){
cout << "Did you enter a letter grade value?" << endl;
goto MATH;
}
cout << "You have selected " << gpaClassSet5[0] << ", or " << gpaClassSet5int[0] << endl;
cout << "Is this class weighted? Use Y/N." << endl;
cin >> mathWeight5;
if (mathWeight5 == "Y" || "y") {
gpaClassSet5int[0] = gpaClassSet5int[0] + 1;
}
I'm looking for a simplified version of this. Why can't I use something like:
if(gpaClassSet5[0] == "A" || "a"){
//stuff//
}
I'm in need of a simplified version because, like a switch, I'd like to use different inputs to do different things -- but ultimately have a default in case any of the values listed weren't entered.
How can I do this? How can I set up a switch in C++?
Sorry if this question is a little dumb, I'm getting into C++ and these self-made programs are really my only practice.
Full program code here: http://justpaste.it/ee4u
Because that's not how C++ is specified to work, you need to do the comparison twice:
if(gpaClassSet5[0] == "A" || gpaClassSet5[0] == "a")
The logical OR operation means "if the left-hand expression is true, or the right-hand expression is true". In your case with the code as in your question, the right-hand side expression will always be true as "a" is not zero (i.e. false).
Operator precedence says you can't do it this way. gpaClassSet5[0] == "A" || "a" is the same as (gpaClassSet5[0] == "A") || ("a").
If you don't want to write gpaClassSet5[0] twice, you could use regular expressions if you don't mind a performance hit
std::regex_match(gpaClassSet5[0], std::regex("A|a"));
This gets more sensible if you test against a lot of possible matches:
std::regex_match(gpaClassSet5[0], std::regex("A|Grade A|1|Excellent|Outstanding|Perfect|Perfect Score)"));
If you are not using C++11 (don't have std::regex), you can use boost::regex from boost.org.
Or you could solve your specific code example with more compact logic:
char gradeLetter = std::tolower(gpaClassSet5[0])
if (gradeLetter >= 'a' && gradeLetter <= 'd')
gpaClassSet5int[0] = 4-(gradeLetter -'a');
else if (gradeLetter == 'f')
gpaClassSet5int[0] = 0;
else
{
cout << "Did you enter a letter grade value?" << endl;
goto MATH;
}
And extract a function to get rid of the goto and make the code easier to read:
int ConvertLetterToNumericGrade(char gradeLetter)
{
char lower = std::tolower(gradeLetter);
if (lower >= 'a' && lower <= 'd')
return 4-(lower -'a');
if (lower == 'f')
return 0;
throw std::runtime_error("cannot convert invalid grade letter");
}
void gpaCalSetClassNum5()
{
...
while (true)
{
cin >> gpaClassSet5[0];
try { gpaClassSet5int[0] = ConvertLetterToNumericGrade(gpaClassSet5[0]); }
catch (const std::runtime_error& )
{
cout << "Did you enter a letter grade value?" << endl;
continue;
}
break;
}
...
}
And with a switch (which is not supported for strings, but is supported for char and wchar):
int ConvertLetterToNumericGrade(char gradeLetter)
{
switch (gradeLetter)
{
case 'a':
case 'A':
return 4;
case 'b':
case 'B':
return 3;
case 'c':
case 'C':
return 2;
case 'd':
case 'D':
return 1;
case 'f':
case 'F':
return 0;
default:
cout << "Did you enter a letter grade value?" << endl;
throw std::runtime_error("cannot convert invalid grade letter");
}
}
Resp.
int ConvertLetterToNumericGrade(char gradeLetter)
{
switch (std::tolower(gradeLetter))
{
case 'a': return 4;
case 'b': return 3;
case 'c': return 2;
case 'd': return 1;
case 'f': return 0;
default:
cout << "Did you enter a letter grade value?" << endl;
throw std::runtime_error("cannot convert invalid grade letter");
}
}