I'm trying to create a small slot-machine game that has three reels and four possible symbols for each reel (bell, orange, cherry, and horse).
I started by generating a random value between 1-4 and now I'm trying to get the first reel to print out the text associated with the generated values.
Here is the code, I hope someone can help and point out why it doesn't work and how I can fix it. From the code below I was expecting the program to print out 3 different pieces of text that were associated with the generated numbers but instead "Cherry" prints out three times.
// Generates 3 different random values between 1-4 and stores them within the slotVal array.
int slotVal[3], counter;
srand(time(NULL));
for (counter = 0; counter < 3; counter++) {
slotVal[counter] = rand() % 4 + 1;
}
// Checks generated values and prints associated text.
for (counter = 0; counter < 3; counter++) {
if (slotVal[counter] = 1) {
printf("Cherry");
}
else if (slotVal[counter] = 2) {
printf("Bell");
}
else if (slotVal[counter] = 3) {
printf("Orange");
}
else
printf("Horseshoe");
}
Your if statements are wrong, you are assigning(=) not comparing(==):
// Checks generated values and prints associated text.
for (counter = 0; counter < 3; counter++) {
if (slotVal[counter] == 1) {
printf("Cherry");
} else if (slotVal[counter] == 2) {
printf("Bell");
} else if (slotVal[counter] == 3) {
printf("Orange");
} else {
printf("Horseshoe");
}
}
If you do if(something = 1) the condition evaluated will be the 1 because the assignment operator returns the assigned variable. Since 1 evaluates to true, your first condition would be met and the other else blocks would be ignored.
Some useful tips to avoid this particular error are:
Do if(1 == variable) instead of if(variable == 1), because the first raises a compilation (if you only use one = sign) error and the second doesn't;
Define a name for the comparison, for example: #define EQUALS == which will allow you to do if(variable EQUALS 10)
When you program in C, always enable all compiler warnings that you can find. C is not a beginner-friendly language, and it provides you with plenty of ways to shoot yourself in the foot. Enabling compiler warnings protects against a few of these ways.
When you use GCC, at least enable the -Wall -Wextra warnings. They will warn you that in the if conditionals, you are using the assignment operator = instead of the comparison operator ==.
Related
Assuming there are no duplicate words in either list, I would like to compare the words of listA with the words in listB.
If there is a match, I want to print the word that matches and compare the next 'n' words in listB to see if there is a match.
Likewise, if there is no match, (i.e once I reach the last word in listA), I want to print the word that could not be found and compare the next 'n' words in listB to see if there is a match.
I am stuck on how I should implement statements (if, break, continue) in my for loop so that it meets the specifications listed above.
When I run the code below, it only prints the instance in which there is a match, but it does not print anything at all if there is no match.
alineno & blineno refer to current line number in the arrays aline & bline where the words are stored
// index through listA
for(i = 0; i < alineno; i++){
// index through all the words in listB
for(j = 0; j < blineno; j++){
if(strcmp(aline[i], bline[j]) == 0){
printf("%s is in the list!", bline[j]);
}
continue;
if(strcmp(aline[strlen(aline[0])-1], bline[j]) != 0){
printf("%s is not in the list!", bline[j]);
}
}
}
Input:
listA: Aardvark,Cat,Bear,Dog
listB: Cat,Badger
Expected Output:
Cat is in the list!
Badger is not in the list!
Actual Output:
Cat is in the list!
EDIT:
I understand that my continue statement is the reason why the second condition is not being checked. Removing it would print a word is / is not in the list 'j' amount of times, which is not my desired output. In other words, I would appreciate guidance on how I should implement such statements in order to meet the specifications.
My suggestion is that you change the loops, so you have the loop over "listB" as the outer loop, and iterate over "listA" in the inner loop.
Then you can easily set a flag in the inner loop, and break out of it when a match is found. In the outer loop you check this flag to decide what to print.
In pseudo code perhaps something like this
for (to_find in listB)
{
found_flag = false;
for (animal in listA)
{
if (to_find == animal)
{
found_flag = true;
break;
}
}
if (found_flag)
printf("Animal found");
else
printf("Animal not found");
}
Your continue is always executed; you will never reach your second if.
The best way to do this is probably binary search or a hash table, depending on the amount of data. That being said, the code could be improved in the following way:
for(int i = 0; i < alineno; i++)
{
int j;
for(j = 0; j < blineno; j++)
{
if(strcmp(aline[i], bline[j]) == 0)
break;
}
if(j == blineno)
printf("%s is not in the list!", aline[i]);
else
printf("%s is in the list!", bline[j]);
}
Note: aline[i] not bline[i] in the printf. bline[i] would be a potential array out of bounds bug, if alineno and blineno are allowed to have different lengths.
First, use goto, like this:
void something(void) {
// index through listA
for(int i = 0; i < alineno; i++){
// index through all the words in listB
for(int j = 0; j < blineno; j++){
if(strcmp(aline[i], bline[j]) == 0){
printf("%s is in the list!", bline[j]);
goto doneAnimal;
}
}
printf("%s is not in the list!", bline[i]);
doneAnimal: ;
}
}
Second; to avoid the risk of "goto is bad" nonsense (see Historical Note below), make the code harder to read by splitting it into 2 different functions, so that you can convert the goto into a return, like this:
void something(void) {
// index through listA
for(int i = 0; i < alineno; i++){
doAnimal(i, blineno);
}
}
void doAnimal(int i, int blineno) {
for(int j = 0; j < blineno; j++){
if(strcmp(aline[i], bline[j]) == 0){
printf("%s is in the list!", bline[j]);
return;
}
}
printf("%s is not in the list!", bline[i]);
}
Historical Note
Once upon a time higher level languages (like assembly language) did not have structured programming features (do, while, break, continue, switch, ...). Instead programmers would write code using goto, like (e.g.) "if(x < MAX) goto loopStart; instead of a "} while(x < MAX);.
To encourage the adoption of structured programming features, in 1968 Edsger W. Dijkstra wrote a letter to the editor of ACM entitled "go to statement considered harmful". This letter had the desired effect - structured programming features (do, while, break, continue, switch, ...) were adopted in all major languages.
However; it also had one unintended side-effect - the letter was a little too effective; and ignorant people (that failed to read the letter or understand its context) started becoming zealots, making their code worse (for cases where the new structured language features aren't enough) to avoid goto without understanding why, and encouraging other people to make their code worse without understanding why.
Examples of this include complicating code by introducing extra variables purely for the sake of avoiding a simpler goto, and/or complicating code to introduce extra branches purely for the sake of avoiding a simpler goto.
Later (in conversations with Donald E. Knuth); Dijkstra himself said "Please don't fall into the trap of believing that I am terribly dogmatical about [the go to statement]. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline!"
Sadly; once ignorance begins to spread common sense is fighting a losing battle.
Beginner in C and running into a problem with a function that initializes an array. Compiled in Code:Blocks 16.01 on Windows 10. Specific code I'm having issues with is:
void initAuction(float auction[2][MAXAUCTIONITEMS]) {
int i;
for (i = 0; i < MAXAUCTIONITEMS; i++) {
auction[1][i] = -1;
printf("\n%f\t%d\n", auction[1][i], i);
};
for (i = 0; i < MAXAUCTIONITEMS; i++) {
auction[2][i] = 0;
printf("\n\n%f\t%d", auction[2][i], i);
}
printf("\n%f\n", auction[2][70]);
return;
}
I've set up print statements to see how far I'm getting before the crash and I make it to the second for loop but it crashes at i=140. If I change the constant (which is equal to 1000) then the highest I can set it to without crashing is i<84 oddly enough. What would cause the termination status -1073741819 mid loop when the first row initialized no problem but row 2 chooses to crash at around i=140.
I've tried searching on google and here and it seems the termination code isn't a very specific code since I've seen solutions from needing a return statement, trying to access something that doesn't exist, etc. Really lost.
The valid indices are auction[0][*] and auction[1][*].
You are setting elements of the array beyond its boundaries: the initial dimension of auction is 2, the only valid values for this index are 0 and 1.
You can fix and simplify the code this way:
void initAuction(float auction[2][]) {
for (int i = 0; i < MAXAUCTIONITEMS; i++) {
auction[0][i] = -1;
auction[1][i] = 0;
}
}
Note that the second dimension is not part of the type of auction, it is ignored by the compiler.
I am relatively new at programming, and I'm having trouble figuring out how to loop through an array until the counter finds zero, and when it finds zero once, performs an action and exits the loop. Here is the loop I have so far:
for (int i = 0; i<13; i++)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
}
}
Currently, this loops through the array until it finds zero, calls deal(), prints the value of pHand, and then loops back through the same sequence until i=0. Please help. I am completely stumped on how to fix this.
The break statement can be used to exit an enclosing loop (e.g., a while, do-while, or for) or switch.
for (int i = 0; i<13; i++)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
break;
}
}
// code will continue executing here if the for loop condition becomes
// false (i is 13) or if the break statement is reached.
In your code, if you encountered ZERO value cell, you just call "deal" function and printf, but you don't exit the loop, your are continuing to the next iteration.
In order to exit the loop, add "break" statement in the "if" scope and you will go out the loop once you fulfill the condition.
Some consider break to be harmful. I've used it plenty, but some people have issues with it. If you wanted to avoid using break, you could do the following:
int i = 0;
char finished = 0;
while (i < 13 && !finished)
{
if(pHand[i] == 0)
{
pHand[i] = deal(numArray);
printf("%d\n", i);
printHand(pHand, "Your");
finished = 1;
}
i++;
}
You could also rework it to use do-while. Some would say that this kind of solution is a little nicer, semantically.
I have an array (nchar[12]) and I wrote this code to print it as vertical columns composed of "X"'s.
I first wrote a version with an accumulator and a while-loop and it worked fine, but it only could print colums as long as a given limit.
Then I tried to write it as a state machine, but the output is just an endless series of blank spaces.
I declared status as an int and assigned a value of 1 to it, then:
while (status = 1) {
for (i = 1; i <= 12; ++i) {
status = 0;
if (nchar[i] > 0) {
printf(" X");
--nchar[i];
status = 1;
}
else
printf(" ");
}
It should stop when it doesn't find any value to print for the last processed line, but it just goes on forever and I don't understand why.
The loop never ends because = is the assignment operator not == which is the comparision operator. You probably want
while (status == 1)
Or simply
while (status)
instead of
while (status = 1)
Also if you have an array declared as
type nchar[12];
then the valid indices for it start from 0 and end at 11. So, your loop should start with i=0 and should loop until i<12 becomes false.
I am working in an assignment and am experiencing some weird stuff. I have this while loop in my program that does not seem to branch into the for loop. I have placed two print statements and only the "1" prints over and over again. Note that this only happens when I compile and run from the linux terminal. Now what seem weird is that if i run the exact same code (while loop plus everything else) in Netbeans it seems to compile and behave as expected. Anyone know what might be wrong. Here is the code. I appreciate your help.
while(strstr(p,string_a)!= NULL)
{
p = trailerp + pholderp;
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
printf("1");
for( i = 0; i <= index; i++)
{
printf("2");
p2[trailerp2] = pholderp[trailerp];
trailerp++;
trailerp2++;
if(i == index)
{
int j;
for(j=0; j <= lenb-1; j++) // insert the new string
{
p2[trailerp2] = string_b[j];
trailerp2++;
}
trailerp++;
}
}
}
Edit: I have found the problem. Netbeans seems to be broken in this OS.
This is because strstr(p,string_a) returns either p or 0 in this part:
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
which results in index < 0 and prevents going into the loop.
You must print both p and string_a immediately before this statement to see what is going wrong there.