I'm trying to see if I can make a fizzbuzz c++ switch statement. I'm getting an error saying i is not usable in a const expression. Does that mean I can't make this thing work? Or is there a work around? Here's my code.
#include <iostream>
using namespace std;
int main() {
for(int = 1; 1 <= 100; i++){
switch(true){
case(i % 3 == 0 & i % 5 == 0):
cout << "fizzbuzz" << endl;
break;
case(i % 3 == 0):
cout << "fizz" << endl;
break;
case(i % 5 == 0):
cout << "fizz" << endl;
break;
default:
cout << i << endl;
}
}
}
If you really want to use switch/case then you could do it like this:
switch (i % 15)
{
case 0 : cout << "fizzbuzz\n"; break;
case 5:
case 10: cout << "buzz\n"; break;
case 3:
case 6:
case 9:
case 12: cout << "fizz\n"; break;
default: cout << i << "\n"; break;;
}
There are a couple of fundamental problems with how you're using switch/case.
The expected way to use it is to have the switch refer to a variable or expression, then the case sections refer to constant values.
Instead what you're doing is switch(true) which doesn't make any sense, even though it compiles. It's equivalent to switch(1). So in that case only case 1: would ever apply.
You cannot use expressions for case. These must be constant integer values. So for example you can either plain integers case 0:, or also commonly pre-processor defines case FIZZBUZZ:.
As stated in the comments, several times, you cannot always use a switch() statement like a if statement and there are several other issues with your code. I am not going to give you the right answer as I don't believe that will help you the most.
Here are some notes:
1) Instead of a switch you should use if, else if, and else statements.
2) In C++ a and is expressed as && not &
3) A for loop is declared like for(int i = 0; i <= 100; i++)
You should watch/read some simple tutorials on how to code C++ as it is important you understand these basics.
Related
everyone! I think it could be a silly question, but I was wondering if it is possible to show a case label in a switch statement in C++. This is the statement:
switch(TYPE)
{
case 'A':
(cost <= 30000);
break;
case 'B':
(30000 < cost <= 60000);
break;
case 'C':
(cost > 60000);
break;
}
In this code, the user writes the cost at the beginning of it. The ranges that are showed in each case are the prices of a product. Let's say they write 62000, so given that it costs more than 60000 it should go to the type C product. So I would like to show the type to the user, and I write:
cout <<"TYPE: "<< TYPE <<endl;
But when I run the code, this line appears empty. I would like to find the way to put the 'C' there, which is the type that corresponds to the cost. Or at least I would like to know if this is not possible so I can think of another way to make this happen. I appreaciate your time and consideration. :)
You are going about this backwards. A switch will not accomplish what you want. You need to use if..else instead, eg:
cout << "TYPE: ";
if (cost <= 30000)
cout << 'A':
else if (cost <= 60000)
cout << 'B':
else
cout << 'C':
cout << endl;
Which you can take a step further by wrapping the logic inside a function, eg:
char getTYPE(int cost)
{
if (cost <= 30000)
return 'A':
else if (cost <= 60000)
return 'B':
else
return 'C':
}
cout << "TYPE: " << getTYPE(cost) << endl;
It sounds like your logic might be a bit backwards. switch is used to check against the value of a variable that has already been set. Additionally, it can only check a single value per case; it cannot check a range.
If I interpret your question correctly, I think you want something like this:
if (cost <= 30000) {
TYPE = 'A';
} else if (cost <= 60000) {
TYPE = 'B';
} else {
TYPE = 'C';
}
I am in a beginner C++ course and I am trying to create a program that outputs the 12 days of Christmas song using the two given function calls show_ordinal(int) and show_verse(int) as an assignment. It is supposed to call the verse and show the day with it's ordinal suffix and then loop the remaining verses depending on where the user decides to start from, so if it was show_verse(3) it would be on the 3rd day of Christmas... all the way to the pear tree. I started writing for the function to get the ordinal but kept getting segmentation fault errors.
#include <iostream>
using namespace std;
string show_ordinal(int);
void show_verse(int);
int main()
{
cout << show_ordinal(2) << endl;
return 0;
}
string show_ordinal(int x)
{
switch (x % 10)
{
case 1:
if (x % 10 == 1)
{
cout << x << "st";
}
break;
case 2:
if (x % 10 == 2)
{
cout << x << "nd";
}
break;
case 3:
if (x % 10 == 3)
{
cout << x << "rd";
}
break;
case 4:
if (x % 10 != 1 || x % 10 != 2 || x % 10 != 3)
{
cout << x << "th";
}
break;
}
}
Testing the function by trying to call it with an int value of 2 in main,I have been working on it for awhile and cannot get it to work any help would be greatly appreciated.
show_ordinal returns nothing for
cout << show_ordinal(2) << endl;
to print out. It promises to return a string, but it never does. This is bad form. When a function has a non-void return type it must return a result on all code paths or the function, and the program, is ill formed. A crash or other segfault is a common result, but you could get silent corruption of data, and that is much harder to track down.
Rather than couting all of your results, assign the results to a string and return the string.
You never return a string from show_ordinal(), you just output to cout. Instead of using cout, I think you want to contsruct a string using x and your computed suffix and return that:
string show_ordinal(int x) {
string out;
switch (x % 10) {
case 1:
out = to_string(x) + "st";
break;
case 2:
out = to_string(x) + "nd";
break;
case 3:
out = to_string(x) + "rd";
break;
default:
out = to_string(x) + "th";
break;
}
return out;
}
You should probably count yourself lucky that you experienced a seg fault, because what you are doing is producing undefined behavior. If you don't believe me, check out what OnlineGDB does to your code.
The problem is that you define show_ordinal with a return value of std::string, but never return anything from the function. This produces undefined behavior in the C++ specification. To fix it you can do one of these two things:
Actually return a string. Rather than shifting into std::cout within the function, shift into an std::ostringstream instead, then return the stringified version:
#include<string>
#include<sstream>
std::string show_ordinal(int x) {
std::ostringstream oss;
switch (x % 10) {
case 1:
// Note: I got rid of your extraneous "if" statement.
// "switch" is already doing that work for you.
oss << x << "st";
break;
/* more cases here */
}
return oss.str();
}
Define the function to return nothing. If you really want the function to handle the shifting to std::cout, define it with a void return signature and don't shift the output to std::cout in main:
#include<iostream>
#include<string>
void show_ordinal(int x);
int main() {
show_ordinal(2);
}
void show_ordinal(int x) {
switch (x % 10) {
case 1:
std::cout << x << "st\n";
break;
/* more cases here */
}
}
Either of these should solve your problem.
Note: A few more things:
Please include all the headers for the standard libraries you are using. Add #include<string>.
You don't need those extra if statements in the case blocks. If your code made it to case 1, then x % 10 == 1 is guaranteed, so don't check it again.
show_ordinal won't do anything for x % 10 > 4. Consider replacing case 4 with default. See the documentation for the switch statement.
Please get out of the habit of using namespace std. It will get you in trouble in the future.
How to write this program with switch condition statement instead of if?
#include <iostream>
using namespace std;
int main() {
int i;
for (i = 1; i <= 100; i++) {
if ((i % 7 == 0) && (i > 0)) {
cout << i << endl;
}
}
return 0;
}
The code you're looking for should be something like this:
#include <iostream> // this is for std::cin and std::cout (standard input and output)
using namespace std; // to shorten std::cout into cout
int main() {
cout << "multiples of 7 lower than 100 are:" << endl;
for ( int i=1 ; i<=100 ; i++ ) {
switch ( i%7 ) {
case 0: // this case 0 is similar to if ( i%7 == 0 )
cout << i << " ";
break;
default:
break;
}
}
cout << endl;
return 0;
}
The output will then be:
multiples of 7 lower than 100 are:
7 14 21 28 35 42 49 56 63 70 77 84 91 98
Here you are:
#include <iostream>
int main()
{
for (int i = 1; i<=100; i++)
{
switch(i % 7)
{
case 0:
std::cout << i << std::endl;
break;
default:
break;
}
}
return 0;
}
Online compilation: http://ideone.com/uq8Jue
It sounds like you are a little unfamiliar with a switch statement. A switch statement is like an if-else statement, except that it isn't a Boolean argument. So essentially it asks: Tell me the value of . And then for each case (possible outcome), it has a follow up action.
So you want to ask: tell me the value of the number, modulus 7. If it is zero, add one to the counter. If it is 1, do .
So your code should have a general structure of:
Switch(i%7):
Case 0{increment counter or display to std. out or store in array}
Case 1{other action}
It is possible to replace the if statement with switch/case statement for your case. But I think you have some misunderstanding about where to use if and where switch/case statements. I will suggest you use this statement as they are used in real life.
Use if, if you're going to check the condition. For example:
if (a > b){...} or if (a == 7){...} or if (functionReturnsTrue()){...}
The switch/case statement could be used when you have a set of conditions and the logic is different for each element in that set. For example:
enum HttpMethod {
GET,
POST,
PUT,
DELETE,
};
...
void handleHttpRequest(HttpRequest req)
{
...
switch(req.getHttpMethod())
{
case GET: handleGETRequest(req); break;
case POST: handlePOSTRequest(req); break;
case PUT: handlePUTRequest(req); break;
case DELETE: handleDELETERequest(req); break;
default: throw InvalidHttpMethod(); // in case when noone corresponds to the variable
}
}
Of course, you can write the same using if statement, but switch/case statement also have some compilation effects. When you switch the variable of enum type, you might get a compiler warning at least, if you dont check your variable for all possible flows.
First, I realize that from a performance perspective, the design of this switch statement is slow because cout is being called several times in certain cases. That aside, is this style of writing a switch statement not good coding practice. In other words, would it be better to handle each case individually and break or is the fall-through better?
int main(void)
{
int number;
cout << "Enter a number between 1 and 10 and I will display its Roman numeral equivalent." << endl
<< "> ";
cin >> number;
cout << "Roman numeral: ";
switch (number)
{
case 3:
cout << "I";
case 2:
cout << "I";
case 1:
cout << "I";
break;
case 4:
cout << "I";
case 5:
cout << "V";
break;
case 6:
cout << "VI";
break;
case 7:
cout << "VII";
break;
case 8:
cout << "VIII";
break;
case 9:
cout << "I";
case 10:
cout << "X";
break;
default:
cout << "Error!\nYou did not enter a number between 1 and 10";
}
cout << endl;
return 0;
}
Switch statements aren't slow, they're usually optimised to jump-tables by the compiler. And if you're sure that switch statement works as expected, it's fine and is a pretty cool way of doing it.
That said, you'd have the same number of cases if you handled each one individually. If that's all you're doing, I'd probably change it to handle each one seperately and not do fall through. It's more comprehendable and easily maintained that way:
switch (number)
{
case 1:
cout << "I";
break;
case 2:
cout << "II";
break;
case 3:
cout << "III";
break;
case 4:
cout << "IV";
break;
case 5:
cout << "V";
break;
case 6:
cout << "VI";
break;
case 7:
cout << "VII";
break;
case 8:
cout << "VIII";
break;
case 9:
cout << "IX";
break;
case 10:
cout << "X";
break;
default:
cout << "Error!\nYou did not enter a number between 1 and 10";
}
And like #paxdiablo suggested, to enhance readability you can put the case, statement, and break all on the same line if it looks better to you:
case 1: cout << "I"; break;
case 2: cout << "II"; break;
// etc.
It's such a simple case, it's hard to say it's really "bad." I've heard differing opinions on lettings cases fall through into other cases. And I'm sure at some point, we've all done that. (I usually document it quite clearly with something like /* FALL-THROUGH */ so the next person reading the code knows I meant to do that.)
I think a more complex example would demonstrate it's not such a great idea. But not really because a fall-through itself is a bad thing. But because a better design wouldn't warrant it. In object oriented design, a case statement might indicate that you've got a "code smell" -- that you're not letting the object do what it needs to based on type rather than based on some other piece of information.
Now, if someone really wanted to get picky about your admittedly simple example, one could say you're mixing controller, model, and view together in bad ways. Your controller should simply get the input. Your model would have better ways of obtaining the alternate representation of the input (a map, or heck, a case statement, I dunno), and your view logic would not be scattered in and around your controller logic. By actually adhering to some other design concepts, the switch statement might vanish entirely. That might happen with other examples, too.
In short, I think if your design is sound, you might find that if a switch statement IS even in fact necessary, then the concern about a fall-through case statement isn't a big deal.
I tend not to use that style since it's often difficult to figure out the flow of control at a single glance. This is one reason why goto is generally considered a bad idea (though some people take that as gospel without understanding why - it's actually quite handy in some circumstances provided it doesn't render the code unreadable).
In other words, I prefer each case to be independent. If they have commonality, I will tend to break that out into separate functions and call those functions from each case.
That doesn't cover situations where the code is identical for different cases, where I just use something like (pseudo-code, obviously):
case 1: case 2: case 3:
print "It's one, two or three"
For your specific use case, I would probably just use a table lookup like:
char *roman[] = {"I", "II", "III", "IV", ... "X"};
if ((n < 1) || (n > 10))
cout << "Urk! I only have ten fingers!";
else
cout << roman[n-1];
just to keep the (source) code compact.
Using the Break for each case should be the perferred option. Using "Fall-Through" will move on to the code for the next case, which could cause errors and hinder performance.
You are right in that calling the '<<'-operator several times incurs a certain amount of overhead. However, you're talking about two statements here so this is probably not the point to optimize.
If you want to optimize the code, why not use a static array of strings containing the roman numbers? Like roman[0] = "I", roman[1] = "II", etc. I doubt this representation will cost you more memory than the above function and you get rid of the bloated switch statement.
That is very clever, and this will be plenty fast. But if you want to improve performance ...
In each switch statement, add the string you are couting to a running string buffer. Then, after the switch statement, cout the buffer.
This is a little confusing to read/understand. Simply handling each of the 10 cases individually would be simpler and would perform better (though using a minuscule amount more memory).
Switch statements can be optimized into jump tables by the compiler, so they're not always slow. And they're definitely better than writing a bunch of if - else if statements. I personally like fall through because it allows you to do some cool stuff in certain cases without having to repeat code; but in general, they are frowned upon because they can be harder to understand than handling each case individually.
As for your example, if you're worried about multiple calls to cout, you can always store the intermediate strings in a stringstream and print the final string. However, output to cout is buffered, so I don't know whether this will have any significant performance improvement.
#include <iostream>
#include <ios>
#include <sstream>
int main(void)
{
using namespace std;
int number = -1;
cout << "Enter a number between 1 and 10 and I will display its Roman numeral equivalent." << endl
<< "> ";
cin >> number;
ostringstream oss( "Roman numeral: ", ios_base::ate );
switch (number)
{
case 3:
oss << "I";
case 2:
oss << "I";
case 1:
oss << "I";
break;
case 4:
oss << "I";
case 5:
oss << "V";
break;
case 6:
oss << "VI";
break;
case 7:
oss << "VII";
break;
case 8:
oss << "VIII";
break;
case 9:
oss << "I";
case 10:
oss << "X";
break;
default:
cout << "Error!\nYou did not enter a number between 1 and 10";
return -1;
}
cout << oss.str() << endl;
return 0;
}
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do:
SELECT CASE Answer
CASE 1, 2, 3, 4
Example in C++ (For those that need it):
#include <iostream.h>
#include <stdio.h>
int main()
{
int Answer;
cout << "How many cars do you have?";
cin >> Answer;
switch (Answer)
{
case 1:
case 2:
case 3:
case 4:
cout << "You need more cars. ";
break;
case 5:
case 6:
case 7:
case 8:
cout << "Now you need a house. ";
break;
default:
cout << "What are you? A peace-loving hippie freak? ";
}
cout << "\nPress ENTER to continue... " << endl;
getchar();
return 0;
}
AFAIK all you can do is omit the returns to make things more compact in C++:
switch(Answer)
{
case 1: case 2: case 3: case 4:
cout << "You need more cars.";
break;
...
}
(You could remove the other returns as well, of course.)
Sure you can.
You can use case x ... y for the range
Example:
#include <iostream.h>
#include <stdio.h>
int main()
{
int Answer;
cout << "How many cars do you have?";
cin >> Answer;
switch (Answer)
{
case 1 ... 4:
cout << "You need more cars. ";
break;
case 5 ... 8:
cout << "Now you need a house. ";
break;
default:
cout << "What are you? A peace-loving hippie freak? ";
}
cout << "\nPress ENTER to continue... " << endl;
getchar();
return 0;
}
Make sure you have "-std=c++0x" flag enabled within your compiler
No, but you can with an if-else if-else chain which achieves the same result:
if (answer >= 1 && answer <= 4)
cout << "You need more cars.";
else if (answer <= 8)
cout << "Now you need a house.";
else
cout << "What are you? A peace-loving hippie freak?";
You may also want to handle the case of 0 cars and then also the unexpected case of a negative number of cars probably by throwing an exception.
PS: I've renamed Answer to answer as it's considered bad style to start variables with an uppercase letter.
As a side note, scripting languages such as Python allow for the nice if answer in [1, 2, 3, 4] syntax which is a flexible way of achieving what you want.
You can't remove keyword case. But your example can be written shorter like this:
switch ((Answer - 1) / 4)
{
case 0:
cout << "You need more cars.";
break;
case 1:
cout << "Now you need a house.";
break;
default:
cout << "What are you? A peace-loving hippie freak?";
}
You can use like this:
case 4: case 2:
{
//code ...
}
For use 4 or 2 switch case.
Your example is as concise as it gets with the switch construct.
If you're willing to go the way of the preprocessor abuse, Boost.Preprocessor can help you.
#include <boost/preprocessor/seq/for_each.hpp>
#define CASE_case(ign, ign2, n) case n:
#define CASES(seq) \
BOOST_PP_SEQ_FOR_EACH(CASE_case, ~, seq)
CASES((1)(3)(15)(13))
Running this through gcc with -E -P to only run the preprocessor, the expansion of CASES gives:
case 1: case 3: case 15: case 13:
Note that this probably wouldn't pass a code review (wouldn't where I work!) so I recommend it be constrained to personal use.
It should also be possible to create a CASE_RANGE(1,5) macro to expand to
case 1: case 2: case 3: case 4: case 5:
for you as well.
gcc has a so-called "case range" extension:
http://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Case-Ranges.html#Case-Ranges
I used to use this when I was only using gcc. Not much to say about it really -- it does sort of what you want, though only for ranges of values.
The biggest problem with this is that only gcc supports it; this may or may not be a problem for you.
(I suspect that for your example an if statement would be a more natural fit.)
No, unless you want to break compatibility and your compiler supports it.
#include <stdio.h>
int n = 2;
int main()
{
switch(n)
{
case 0: goto _4;break;
case 1: goto _4;break;
case 2: goto _4;break;
case 3: goto _4;break;
case 4:
_4:
printf("Funny and easy!\n");
break;
default:
printf("Search on StackOverflow!\n");
break;
}
}