Switching the status of a state machine from inside a loop - c

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.

Related

Slot Machine Game In C - Printing Reels Issue

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 ==.

Process terminated with status -1073741819 mid loop?

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.

Loop through array, find zero, perform action, stop

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.

If you have to put breaks in the if statements, why do we need to bother with conditions in the while operation?

This is just a general question really.
I wrote this originally
do
{
scanf("%i", &Carselect);
if (Carselect == 1)
{
mass = 1100;
velomax = 200;
}
else if (Carselect == 2)
{
mass = 1888;
velomax = 415
}
else if (Carselect == 3)
{
mass = 18000;
velomax = 129;
}
else
{
printf("Error in input. Please enter 1, 2 or 3.\n");
}
}
while (Carselect != 1 || Carselect != 2 || Carselect != 3);
And I got stuck in the loop. I put breaks in the statements for the valid conditions and that allowed me to get out, like this
do
{
scanf("%i", &Carselect);
if (Carselect == 1)
{
mass = 1100;
velomax = 200;
break;
}
else if (Carselect == 2)
{
mass = 1888;
velomax = 415;
break;
}
else if (Carselect == 3)
{
mass = 18000;
velomax = 129;
break;
}
else
{
printf("Error in input. Please enter 1, 2 or 3.\n");
}
}
while (Carselect != 1 || Carselect != 2 || Carselect != 3);
but I thought that the conditions for while were repeat conditions, so as soon as Carselect equals 1, 2 or 3 it will exit the loop. If you have to put breaks in the if statements, why do we need to bother with conditions in the while operation?
What is there, on the machine level or otherwise, that requires this seemingly trivial bit of logic?
Edit (as the question's title is changed):
The checking condition in the while/do-while loop is the one that is primarily checked to determine if the program is to stay in or to get out of the while/do-while loop - not the break statement.
The break statement is normally used if:
you want to get out of the while/do-while block before it is executing every statement in the block or
when certain exceptional termination condition is reached before you loop through your entire loop iteration or
You create an infinite loop and you capture an error which makes you unable to continue the loop or
Some other other cases which I might not be aware of...
Essentially, break-statement is not normally used to terminate the while/do-while block as long as the program follows (for lack of better term) "standard/main" path in the loop block.
In contrast, condition in the while/do-while loop is used to terminate the loop when the program follows "standard/main" path in the loop block.
Original:
You should change your inequality check (!=) into NOT equality check (==).
while (!(Carselect == 1 || Carselect == 2 || Carselect == 3));
This is because what you really want is for the loop to continue as long as
the Carselect is not (1 or 2 or 3)
Alternatively, you could change the or operator (||) to and operator (&&) which results in the same logic:
while (Carselect != 1 && Carselect != 2 && Carselect != 3);
the Carselect is not 1 and not 2 and not 3
In C break takes you to the statement immediately following } of the containing block, and continue takes you to to the statement immediately following { of the containing block. Both are useful in a long block, for example if an error condition occurs, or if a simpler input is detected, and not all the processing of the complete block is required, but you want to continue and get the next input.

While loop not behaving as expected

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.

Resources