I'm learning about recursions and I have to later apply it a project. My project is going to include a deck of cards and I'm just curious if this counts as recursion? To me it seems like it since it calls itself. However since i'm still learning I want to make sure i'm understanding the concept and i'm not wrong. Please let me know.
string Card::suitName(Suit S) {
string suits;
switch (S) {
case clubs:
suits = "Clubs";
break;
case diamonds:
suits = "Diamonds";
break;
case hearts:
suits = "Hearts";
break;
case spades:
suits = "Spades";
break;
}
return (suits);
}
// declare the value of the cards
string Card::cardValue(Value Card) {
string card;
switch (Card) {
case two:
card = "Two";
break;
case three:
card = "Three";
break;
case four:
card = "Four";
break;
case five:
card = "Five";
break;
case six:
card = "Six";
break;
case seven:
card = "Seven";
break;
case eight:
card = "Eight";
break;
case nine:
card = "Nine";
break;
case ten:
card = "Ten";
break;
case jack:
card = "Jack";
break;
case queen:
card = "Queen";
break;
case king:
card = "King";
break;
case ace:
card = "Ace";
break;
}
return (card);
}
You've defined two functions Card::suitName() and Card::cardValue(). Neither function calls itself or any other user-defined function (excluding any std::string functions). There's no recursion anywhere in your code.
Recursion is defined as a function calling itself within itself. So suitName would need to have a call to suitName or cardValue to cardValue. Neither make such a call, so
There is no recursion in your code
Recursion requires a function to call itself (most commonly directly but it can be via another function).
Example:
bool doesHandContainAceRecursion(std::vector<Card> const& playersCards, int pos) {
// If we have tried all the cards and gone past the end
// Then return false.
//
// This is a classic part of recursion, checking if you have reached the end.
if (pos >= playersCards.size()) {
return false;
}
// Otherwise do the work you want to do.
if (playersCards[pos].value == 1) {
return true;
}
// This is the recursive call.
// It calls itself. This is a classic example of tail recursion.
return doesHandContainAceRecursion(playersCards, pos + 1);
}
// This is the function you call and it sets up a call to the
// recursive function above.
bool doesHandContainAce(std::vector<Card> const& playersCards) {
return doesHandContainAceRecursion(playersCards, 0);
}
No this is not recursions. Recursions is when method is calling itself
Example:
string Card::suitName(Suit S) {
string suits;
switch (S) {
case clubs:
suitName(diamonds); // Recursions
break;
case diamonds:
suits = "Diamonds";
break;
}
return (suits);
}
No, the code you provided does not involve recursion. Recursion is a programming technique where a function calls itself, either directly or indirectly, to solve a problem. In the code you provided, there are no function calls that reference the function itself.
The functions suitName and cardValue are simply taking in an input and returning a corresponding output based on a switch statement. They do not involve any kind of iterative or recursive process to arrive at the output.
In the context of a deck of cards, you might consider using recursion for a function that shuffles the cards, as shuffling involves repeatedly swapping pairs of cards until the deck is randomized. However, the code you provided does not involve recursion.
Related
I have this code:
#include <iostream>
using namespace std;
int main() {
int square; char state;
cout<<"Write a numbber"; cin>>square;
square *= square;
cout<<square;
switch(square) {
case 1: state = 'h';
case 3: state = 'm';
case 7: state = 'j';
case (square > 10): state = 'u'; // I try this, but not works
}
return 0;
}
I would like to know how a condition is made inside a switch, in c ++.
The expression following case must be a compile time constant. Hence, you may not use what you are trying.
Change that to default: and then use if.
default:
if (square > 10)
state = 'u';
If you have lots of items you should use a switch. If not, if else is better.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.
If you want to use condition or combine some:
switch(square) {
case 1: state = 'h'; break;
case 3: state = 'm';break;
case 7: state = 'j'; break;
case 8:
case 9: state = 'u';
case 10: state = 'z';break;
default: state = 'd';
}
Case 8, 9, 10 will be combined if the square is 8.
If you don't have a break at the end of a case region, control passes along to the next case label.
#include<bits/stdc++.h>
using namespace std;
void show(int errorCause)
{
switch(errorCause)
{
case 1:
{
cout<<"in 1\n";
break;
}
case 2: break;
case 3:
{
cout<<"in 3\n";
break;
case 4:
{
cout<<"in 4\n";
case 5: cout<<"in 5\n";
break;
}
}
break;
default:
{
cout<<"in deafult\n";
break;
}
}
return;
}
int main()
{
show(5);
return 0;
}
I used this sample of code and I could not figure out its flow.According to me it should match the default condition as the errorCause does not match anything,but its output is:
in 5
I don't understand why it is not going to default condition?
Here is my build environment details:
compiler:
g++ version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3)
System:
Ubuntu 14.04(64-bit)
You pass 5, why should the switch statement not go into 'case 5'?
To make it clear: Remove all these curly braces inside the switch-block, none of them is necessary. The re-align and format the code, then it should be clear.
case/default labels for a switch statement may appear anywhere within that switch statement, except within a nested switch statement.
A famous example of this usage is Duff's device for unrolling loops:
void copy(unsigned char *to, const unsigned char *from, size_t count)
{
size_t n;
if (!count)
return;
n = (count + 7) / 8;
switch (count % 8) {
case 0:
do {
*to++ = *from++;
case 1:
*to++ = *from++;
case 2:
*to++ = *from++;
case 3:
*to++ = *from++;
case 4:
*to++ = *from++;
case 5:
*to++ = *from++;
case 6:
*to++ = *from++;
case 7:
*to++ = *from++;
case 1:
} while (--n > 0);
}
}
(adapted from the original).
At first glance, that doesn't make any sense (and it is somewhat redundant if you allow the compiler to unroll loops for you), but it illustrates that case labels can be placed more or less where you like within the switch statement.
First, don't write code like that. <g>
Second, the reason that it gets to case 5: is simply that there's a case 5: inside the switch statement. It doesn't matter that it's nested inside two levels of curly braces; it's just a label for the code to jump to. It doesn't have to be at the outer level of the switch statement.
It's because actually the switch statement evaluation is "relaxed", so the braces do not matter there. Only case matters, but you can jump right into the middle of a scope by the case (or even to the middle of a loop, see Duff's device).
because the value you passed is 5 , which exactly matches with the switch case parameter.
case 5: cout<<"in 5\n";
break;
if you want to get the default statement then modify the main function as shown below :
int main()
{
show(6);
return 0;
}
hope this helps.
I used getchar() to stop the while string. My problem is that it does stop the while string if I type one or two characters, if the user input is more the two characters nothing happens.
here is the code:
printf("enter srting\n");
while ((tmp=getchar()) !='\n') { \\here is my problem
count_letters++;
/* COUNTING WORD THAT START WITH LETTES L,A,C,H */
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
} /* end of count letters while */
n1=n2;
n2=n3;
n3=tmp;
if (n1=='H' && n2=='Y' && n3=='A') {
count_hya++;
}
} /* end of getchar while */
printf("\n");
printf("%d", count_letters);
I believe it's your code :
"while (count_letters%3==0))"
is something wrong!
because when you type more than three letters,your variable "count_letters" will add to 3 due to the code:"count_letters++;".
May be you could change the "while" to "if" and see if it's working correctly~
Here's the problem:
while (count_letters%3==0) {
switch (tmp) {
case 'A': count_a++;
break;
case 'C': count_c++;
break;
case 'H': count_h++;
break;
case 'L': count_l++;
default:
break;
}
}
when your the third character is read, your program enters a infinite loop because of (count_letters%3==0)
I can't understand the purpose of your code.
I suggest using gets() and string manipulation functions because you are processing an entire line. (see string.h)
getchar() is also less efficient compared with gets() + for-loop
You can display a Value's type like this:
cout << val.type() << end;
and it print a number.
How can I map this number back to the actual type?
besides peeking in the header file, of course, which reveals all...
enum Value_type {
obj_type,array_type,str_type,bool_type,int_type,real_type,null_type
};
Nope, that seems to be the canonical way:
switch(v.type()) {
case obj_type: pp_obj(v, lev+1); break;
case array_type: pp_array(v, lev+1); break;
case str_type: pp<string>(v, lev+1); break;
case bool_type: pp<bool>(v, lev+1); break;
case int_type: pp<int>(v, lev+1); break;
case real_type: pp<double>(v, lev+1); break;
case null_type: pp_null(v, lev+1); break;
}
Value val;
read(is, val);
Object o = val.get_obj();
Then create a Pair, assuming it's type 0.
Pair pair = o[1];
where 1 is the iterated value. This took me forever to figure out, so I'm trying to save the time of anyone else who needs to look this up later. use sizeof(o)/sizeof(int) to iterate, along with the ++i instead of i++.
I'm writing a game and I'm wound up in needing a console for simple text input; filenames and simple values.
Using SDL, my console looks the following at it's simplest:
class Console
{
public:
typedef std::list<String> InputList;
enum Result
{
NOTHING = 0,
ENTERED,
ESCAPED
};
static const String& GetInput() { return input; }
static Result Query(SDLKey lastKey)
{
if(lastResult == ENTERED || lastResult == ESCAPED)
{
input.clear();
}
switch (lastKey)
{
case SDLK_a:
case SDLK_b:
case SDLK_c:
case SDLK_d:
case SDLK_e:
case SDLK_f:
case SDLK_g:
case SDLK_h:
case SDLK_i:
case SDLK_j:
case SDLK_k:
case SDLK_l:
case SDLK_m:
case SDLK_n:
case SDLK_o:
case SDLK_p:
case SDLK_q:
case SDLK_r:
case SDLK_s:
case SDLK_t:
case SDLK_u:
case SDLK_v:
case SDLK_w:
case SDLK_x:
case SDLK_y:
case SDLK_z:
case SDLK_0:
case SDLK_1:
case SDLK_2:
case SDLK_3:
case SDLK_4:
case SDLK_5:
case SDLK_6:
case SDLK_7:
case SDLK_8:
case SDLK_9:
case SDLK_SLASH:
case SDLK_BACKSLASH:
case SDLK_PERIOD:
case SDLK_COMMA:
case SDLK_SPACE:
case SDLK_UNDERSCORE:
case SDLK_MINUS:
input += static_cast<char> (lastKey);
lastResult = NOTHING;
break;
case SDLK_RETURN:
lastResult = ENTERED;
break;
case SDLK_ESCAPE:
lastResult = ESCAPED;
break;
}
return lastResult;
}
protected:
static Result lastResult;
static String input;
};
This would be called from the application's main event loop, if the console is active and the last event was a keypress, then the result of the input is processed at a state where it's necessary.
Of course, it looks incredibly awkward... What's a better way to implement a simple console that can be easily rendered in my game's window? (Not going anywhere near to highly unportable solutions like having to reroute std::cout or writing code to bring up a UNIX console etc.)
One suggestion I would offer is to use if statements instead of a switch in this case:
if(lastKey == SDLK_RETURN)
lastResult = ENTERED;
else if(lastKey == SDLK_ESCAPE)
lastResult = ESCAPED;
else if(lastKey >= SDLK_SPACE && lastKey <= SDLK_z)
{
input += static_cast<char> (lastKey);
lastResult = NOTHING;
}
I took some liberties and included some characters that you didn't have in your code above, such as the ampersand, quotes, parentheses, brackets, etc. If you don't want those keys, you can add a few more if statements to break it down a bit more.
This assumes that the enum for the keys doesn't change a lot. If it does change a lot you may be better off with what you had.