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.
Related
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.
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.
Just going to change my question for now - I could just use some guidance as to why I have three compiler errors in my program, not quite sure what I did wrong/am missing - I have added comments into the code just to state where they are. Thanks
#include <iostream>
#include <string>
using namespace std;
class romanType
{
public:
void setRomanNum(string store);
// this function will store the Roman numeral
int convertNum(char rNum);
// this function will convert the Roman numeral to a decimal
void decimalPrint(int total);
// this function will print the decimal number
void romanPrint(char rNum);
// this function will print the Roman numeral
int getNum(char letter);
// this function will get the number input
romanType(int store);
//Constructor with parameter
romanType();
char roman[7];
string num;
int length = 0;
string dNum;
int equals;
};
romanType::romanType(int store)
{
dNum = 1;
}
void romanType::setRomanNum (string store)
{
dNum = store;
}
void romanType::romanPrint(char rNum)
{
cout << "The Roman numeral is: " << roman << endl;
}
void romanType::decimalPrint(int total)
{
cout << "The Decimal number is: " << equals << endl;
}
int romanType::convertNum (char rNum)
{
int letter;
int totalNum = 0;
for (int i = 0; i< dNum.length(); i++)
// "loop will run at most once (loop increment never executed)"?
{
switch (roman[i])
{
case 'M':
totalNum+= 1000;
break;
case 'D':
totalNum += 500;
break;
case 'C':
totalNum += 100;
break;
case 'L':
totalNum += 50;
break;
case 'X':
totalNum += 10;
break;
case 'V':
totalNum += 5;
break;
case 'I':
totalNum += 1;
break;
}
totalNum = totalNum + letter;
equals = totalNum;
return equals;
}
};
// "control may reach end of non-void function"
int main()
{
romanType output;
int rNumeral;
char entry;
cout << "Please enter a Roman numeral (Capitalized only): " << endl;
cin >> rNumeral;
cout << "Print Decimal or Roman Numeral? Type 1 for Decimal, 2 for Roman Numeral: " << endl;
cin >> entry;
if (entry == '1')
{
cout << "You chose to view the decimal conversion." << endl;
output.decimalPrint(rNum);
// How do I output the decimal conversion from the void romanType::decimalPrint(int total) function?
}
else if (entry == '2')
{
cout << "You chose to view the Roman numeral." << endl;
output.romanPrint(rNumeral);
}
else
cout << "Error: bad input" << endl;
return 0;
exit(1);
}
The mistake in the algorithm is that the Roman system is non-positional. See en.wikipedia.org/wiki/Roman_numerals and en.wikipedia.org/wiki/Subtractive_notation. You can't just add up consequent digits (i.e. letters) but you also have to identify and account for the cases when subtraction takes place.
why am I getting the error "no matching constructor for initialization of "roman type"?
Because the only provided constructor is not the default one, but takes one parameter of type int. Since such a constructor was provided, the default constructor wasn't generated by the compiler. Define romanType::romanType() or change the existing one to romanType::romanType(int i = 0) (add a default parameter). See Is there an implicit default constructor in C++? and why default constructor is not available by default in some case
expected expression?
Provide braces around the preceding else block. More than one statement -> braces required.
if (entry == '1') {
cout << "You chose to view the decimal conversion." << endl;
output.decimalPrint(rNum);
} else if (entry == '2')
cout << "You chose to view the Roman numeral." << endl;
output.romanPrint(rNumeral);
}
"control may reach end of non-void function"
This is a warning only, but it will turn into an error if you include the -Werror flag that tells the compiler to treat all warnings as errors.
Ok I was wrong on this one. Actually the trick is that it is (in theory) possible that the romanType::convertNum(int) function follows a route where the for loop will never get executed and thus no return statement will be executed either. That's bad since the function is declared to return int hence there must be present an explicit return statement that (surprise) would return a value. Move the return out of the loop. This error is also closely related to the next one, discussed below.
"loop will run at most once (loop increment never executed)"?
This is because the return statement is placed incorrectly: inside the for loop not outside of it, and inside the function body. Hence the loop runs once and the function returns. Move the return statement. Credit to #ATN_LR_boom for noticing this!
Also, please get in the habit of formatting code properly. It will save you a lot of headache down the way.
Other than that, I'd use a std::map for the conversion function, it's shorter and more clear to the reader compared to the switch statement. Something along the lines of
int romanType::convertNum(int rNum) {
const static std::map<char, int> conversion = {
{'M', 1000},
{'D', 500},
// more mappings
{'I', 1}
};
if ((auto it = conversion.find(rNum)) != conversion.end())
return it->second;
else
return -1;
}
Your logic for the switch is wrong, try something like this:
int totalNum = 0;
for (int i = 0; i< dNum.length(); i++)
// the loop ran once because you were returning values when catching a letter
{
switch (roman[i])
{
case 'M': // roman[i] is a char, the cases should try to catch chars
totalNum += 1000; // increment your global number
break;
case 'D':
totalNum += 500;
break;
...
}
return totalNum;
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
string numString(int k)
{
string str;
switch (k) {
case 0 : str ="ZERO"; break;
case 1 : str ="ONE"; break;
case 2 : str ="TWO"; break;
case 3 : str ="THREE"; break;
case 4 : str ="FOUR"; break;
case 5 : str ="FIVE"; break;
case 6 : str ="SIX"; break;
case 7 : str ="SEVEN"; break;
case 8 : str ="EIGHT"; break;
case 9 : str ="NINE"; break;
}
return str;
}
int main(int argc, char** argv) {
int value;
int digit;
cout << "Enter a number: ";
cin >> value;
while (value > 0 )
{
digit = value % 10;
value = value / 10;
cout << numString(value) << endl;
}
return 0;
}
My program is supposed to prompt the user for an integer value read that value, and output the word equivalent of each digit
For example if "9502" was entered it would output "NINE FIVE ZERO TWO"
Yet mine only outputs "NINE ZERO" and then stops. I can't figure out what I'm doing wrong, any help at all is greatly appreciated.
Yet mine only outputs "NINE ZERO" and then stops.
That's literally what you told it to do!
while (value > 0 )
You'll have to find some other way to signal a "termination" condition if zero is supposed to be valid.
Traditionally we let the system's own end-of-file signalling take care of that for us, so that we don't have to "reserve" some otherwise-valid input and use it as a signal flag.
while (cin >> value) {
digit = value % 10;
value = value / 10;
cout << numString(value) << endl;
}
That fixes your loop, although unfortunately your maths are still wrong and your output is not what you intend. In fact, your digit variable is not used at all. I am not going to spoonfeed an algorithm here: you'll have to work out on paper how to achieve the business logic. :)
This is an analysis of your program using the input 9502.
Iteration 1, in main:
(new) value = 9502 / 10;
(new) digit = 9502 % 10;
value == 950;
digit == 2;
call numString(950);
// Note: there is no case for 950 in numString so an empty string is returned.
Iteration 2, in main:
(new) value = 950 / 10;
(new) digit = 950 % 2;
value == 95;
digit == 0;
call numString(95);
// Note: there is no case for 95 in numString so an empty string is returned.
The above iterations and variable values can be obtained with pen & paper (or a note pad). You can also do the same with something called a debugger.
I hope this helps.
#include <iostream>
#include <sstream>
int main(int argc, char* argv[]) {
if ( argc != 2 ) {
std::cout << "usage: " << argv[0] << " <n> " << std::endl;
return 0;
}
std::stringstream strm;
strm << argv[1];
int count = 0;
int number;
strm >> number;
switch ( number ) {
case 0: ++count;
case 1: ++count;
case 2: ++count;
case 3: ++count;
case 4: ++count;
}
std::cout << "count: " << count << std::endl;
return 0;
}
I know this is a novice question, but i just started with C++. I took a game design course and this is the first example prof has on the SVN. When I run the prog after compiling,
./run 4
(i.e. I give argument 4) I get an output: count: 1
./run 3
I get an output: count: 2
./run 1
count: 4
./run 0
count: 5
Since count is initialized to 0, how come ./run 1 gives 4 or ./run 0 give count 5.
I am really sorry for such a silly question, but I would appreciate any explanation.
Thanks in Advance
Regards
With a switch statement, when control is passed to a case label, the code will continue on through all other case labels until a break or return (or other flow control mechanism) is encountered. This can be useful for unifying logic of specific cases, and can also be used for more complicated tasks. See for example: a Duff's Device.
A switch statement defines where to enter a set of code.
switch ( number ) {
case 0: ++count; //entrance point with number= 0
case 1: ++count; //entrance point with number= 1
case 2: ++count; //entrance point with number= 2
case 3: ++count; //entrance point with number= 3
case 4: ++count; //entrance point with number= 4
}
Inherently there is no exit except for getting to the end of the switch. However, it is possible to add a "break;" statement anywhere under a case to cause the code to exit the switch early (or break out of scope).
Additionally, but slightly off topic, the keyword "default" should be used in a case statement. The default keyword is called when the number doesn't have a defined case. Example, using the case above, is if someone sent the number 6 to the case.