Dangling else query (or an excercise in reading bad code) [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The book I'm reading (C How to Program with an into to C++ Global Edition, Deitel&Dietel, 2016) gives the following code: Note that this is how the book presents the code in the exercise section, without braces and indentation on purpose. I would assume to teach you that using correct indentation makes reading code a lot easier.
int main(){
int x = 9, y = 11;
if (x < 10)
if (y > 10)
puts("*****");
else
puts("#####");
puts("$$$$$");
}
The output is
*****
$$$$$
The book states the compiler always associates an else with the previous if unless told to do otherwise by the placement of braces so by that logic the else is associated with
if (y > 10)
which is true and the else shouldn't execute, giving an output of
*****
and not
*****
$$$$$
So my question is why is the line
$$$$$
in the output?

[too long for a comment]
Even without braces it is quite clear what goes where if indented and new-lined properly (which can be automated, BTW):
int main() {
int x = 9, y = 11;
if (x < 10)
if (y > 10)
puts("*****");
else
puts("#####");
puts("$$$$$");
}

You wrote this (equivalent to yours)
if (x < 10) {
if (y > 10) {
puts("*****");
}else{
puts("#####");
}
}
puts("$$$$$");
And it is following what you said. The else matches with the closest if. Here y>10. And the if and else always consider the single statement when we don't use brackets. Here if-else block inside the outer if serves the purpose of the single statement. Same way the for the else the single puts("####") serves the purpose. The last puts will be executed no matter what the value of x and y be.

Related

My while loop is not evaluating conditions or performing tasks inside a nested loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 days ago.
This post was edited and submitted for review 7 days ago.
Improve this question
I am writing a program where several functions are performed within a while loop. When I run the program, nothing inside is done, though. Only the things written before the while loop were performed. Here is the code:
int main() {
int x;
int y;
int a = 1;
for (x = 0; x < 9; x++) {
for (y = 0; y < 9; y++)
board[x][y] = '\0';
}
displayBoard();
while (cWhoWon == '\0') {
printf("\n%c\n", cWhoWon);
if (iCurrentPlayer == 1 || iCurrentPlayer == 0) {
printf("\nPLAYER X\n");
and so on with nested loops until this if loop ends. (it's indented properly in the real code, i appreciate your patience) No malloc was used, nor struct - I am only a beginner with knowledge of arrays, loops, booleans, and basic functions like isdigit.
I tried to add another condition, a = 1, to the while loop with the 'and' boolean operator (&&) and ';' but the same thing happens. I thought that this would make the while loop iterate, at least, but it doesn't. Is it my compiler? I'm using "OnlineGDB.com" C compiler.

C - struggling to understand how to use int function within if/ while loops [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So I'm doing CS50 and struggling with an error that occurs when I include the following two lines:
if (int i < (number -1))
if (int i =< number)
when compiling, 'error: expected expression' comes under 'int'. Am I using it incorrectly within while if statements?
No you can not declare variable in an if statement. But if you want your variable in a local scope you can create a block and declare your variable, initialize it and use. We have to use <= for checking less than or equal to instead of =<
example:
{
int i =5,number=10;
if(i < number-1)
{
//Add your code
}
if(i <= number)
{
//Add your code
}
}
int i; is a variable declaration/definition.
That confuses your compiler when it tries to understand your if condition.
I have to guess a little, but am confident. You probably want
if (i < (number -1)){ /* assuming code here */ }
if (i <= number) { /* assuming code here */ }
Note that is also changed =< to <=.

how would I write "while( x/y is not a multiple of 4)" [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am relatively new to programming and I want to it to loop in a "do while" loop while the quotient of two variables is not a multiple of 4.
The modulo operator, or % will do exactly as you need. It will return the "remainder" of dividing a number by a given value. Using that logic, if the result is 0, then the specified number was divided evenly by the value.
Therefore:
do
{
// do stuff that changes x and/or y
} while ((x / y) % 4) != 0)
Should accomplish your goals.
You divide your x/y value, and then use % 4 on the result. If the result is zero, then the it was evenly divisible by 4, if it is not zero, there was a remainder and it was not evenly divisible.
As pointed out in a comment below, the do...while syntax first "does", then evaluates, which although not indicated in your question, is unlikely the intended behavior, and what you need is simply a while loop without the do. This first evaluates, and then "does" only if the result was true, otherwise does nothing.
while (y != 0 && (x / y) % 4) != 0)
{
// do stuff that changes x and/or y
}
I'll give you the math. Let Z = X / Y. Then you want Z % 4 to be non-zero.
try like this.You can use z to store result of (x/y)%4.
main(){
int x=0,y=0, z=0;
do{ // do anything
}
while((x/y)%4 != 0);
}

Why not use a while loop for FIZZBUZZ in C? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Only been coding in C for about a month, but wondered why the while loop wasn't used more often for FIZZBUZZ. Is it not as clean or some other reason? Here's what I came up with:
int main()
{
int num=1;
while(num<=100)
{
if (num%3==0 && num%5==0)
{
printf("FIZZBUZZ!!!\n");
}
else if (num%3==0)
{
printf("FIZZ!!!\n");
}
else if (num%5==0)
{
printf("BUZZ!!!\n");
}
else
{
printf("%d\n", num);
}
num++;
}
return 0;
}
Your loop can be neatly folded into a for loop:
for(int num = 1; num <= 100; ++num)
There are two advantages here:
num is scoped inside the loop, when before it was bleeding into whatever scope followed the while. Restricting variables to the minimum possible scope is a good rule of thumb, because it minimizes the amount of variables to think about at any given point.
The range over which your program will operate is now summarized in a single place: you can see the bounds (1 to 100) and the step (1) inside the for. That kind of ranges is pretty well balanced to be read and memorized quickly before reading the body of the loop. For example, if you now wanted to only check odd numbers, it would be immediately clear from reading the num += 2 in the for header, rather than stumbling upon it at the very end of the loop's body.

Refusing to use <= in C [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have this habit in C (and many other languages) where rather than foo <= bar I will do foo < bar + 1 and no idea where this even came from...
Is this bad, per se, or just nonstandard? I mean from the context of coding and later modifying the code...I assume any good compiler compiles both of them the same.
This is bad for multiple reasons:
Does not work for floating point numbers
Does not work for signed numbers (-2.5 <= -3 is false, but -2.5 < -3 + 1 is true)
Makes your code difficult to understand
Increases the chances that you'll (needlessly) create an overflow error
It's bad and nonstandard. There's really no reason to continue reinforcing the habit - you're just shooting yourself in the foot for later in your coding career.
I think it's less clear, personally. Also it could be bad if foo and bar are not integers; for example the two will mean something different if foo= -7 and bar = -7.5.
Based on your comment:
it helps prevent errors with how many iterations of loops take place
You're most likely referring to looping in these two ways:
Method I:
for(int i = 0; i < length; i++){ // } which would go between 0 and length-1.
Versus:
Method II:
for(int i = 0; i <= length-1; i++){ //} which also goes between 0 and length-1.
In these particular cases, either will work, but as Derek Redfern outlined in his answer above, don't make your code any more complicated than it should be.
It is very broken, especially when you do
int foo = <whatever>;
int bar = INT_MAX;
if (foo < bar + 1) {
/* guaranteed to never be called */
}
Also, it is likely to break if you "adjust" it in the other way, like so
int foo = INT_MIN;
int bar = <whatever>;
if (foo - 1 < bar ) {
/* again guaranteed never to be called */
}
In short, far better to check for equal and greater (or equal and less than) than to create code that adjusts a value during the comparison.

Resources