Refusing to use <= in C [closed] - c

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.

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.

I don't know what to put in the place of β and α in order to print all 3 digit numbers different from 0 and unique [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 3 years ago.
Improve this question
I don't get what I should put in the place of: "α" and "β" in order to print all the 3 digit numbers which are different from 0 and from one another.
It is required to replace those 2 variables, with some code
We are entering G(0)!!!
It's from an exam paper, I really don't get it, please help.
void G(int k)
{int i;
for(i=1;i<=α;i++)
{ p[k]=i;
if(β)G(k+1);
else
printf("%d%d%d\n",p[0],p[1],p[2]);
}
}
For any of this to make sense, it must be that p is declared as a global int array of dimension at least 3. I assume for the purposes of this answer that it is in fact so declared.
Note that the function sets p[k] = i, but it later reads back only p[0], p[1], and p[2]. This should give you a pretty good idea about what makes sense for expression β, which controls whether to recurse (increasing k) or print.
Note also that the function sets p[k] = i, and that when it reads back those p[k] for various k, it wants to get values ranging from 1 to 9 (no more and no less). This should give you a pretty good idea of what expression makes sense for α, the inclusive upper bound on i.
Having figured those out, it remains to satisfy yourself that the natural substitutions for those expressions indeed produce a resulting function that behaves as required when initially called as G(0). I suspect that you will find that easier than you did discerning the needed expressions.
(Details are left as an exercise.)

Display the progress of completion while the program is being executed [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to display the progress of my C program in percentages while it is running. The actual work in the program whose progress should be measured is confined in a loop. Here is what I tried:
int i;
int to = 100000000;
while (i++ < to) {
printf("\rPercent done: %d", (100 * i)/to);
}
Might be a dumb question, but how does one display a progress while
the program is running?
Not like this.
You have multiple issues:
Your i is uninitialized, so the program will print garbage. (Fix: -> int i = 0; instead)
Your "progress counter" will only count the progress while in the loop. As soon as Percent done: 100 will be printed, only the loop will be over.
You're printing 100 million lines to the console. Maybe think that through again.
With (i*100)/to you're hitting integer overflow about half way through, so use i / (to / 100) instead. Notice depending on the compiler the compiler could optimize that out by itself.
A little less obnoxious way would be:
#include <stdio.h>
int main (void) {
int i = 0;
int to = 100000000;
while (i++ < to) {
if (i % 1000000 == 0) {
printf("\rPercent done: %d", i / (to / 100));
}
dostuff();
}
printf("\rLoop finished");
return 0;
}
Note that this will only accurately reflect how far the program has come executing the loop. Any work before/after the loop will not be measured by this.
This only prints a console message for every full percent. Still obnoxious that you're getting 100 console messages, but nowhere near as bad as 100.000.000 (!) calls to printf. Still though, that's still a performance impact.

What is the complexity of the following simple program? [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 6 years ago.
Improve this question
I am having trouble finding understanding complexity. Could someone help me understand what the complexity of the code below is and why.
for (int i = 1; i < n; i++) { // (n is a number chosen by the user)
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
An explanation would be great.
Assuming i starts at 0, the complexity would be constant. The complexity is always expressed relative to a variable defining the number of executions, which is not the case here.
If one term should be used to describe this behavior, it is "constant". There will be a number of executions, but this number will never change
Original Question: Because i's initial value is undefined, the behavior of the code is unpredictable. There is no way to usefully answer the question other than that the complexity is undefined. There is no way to know how many operations the code will perform.
Updated Question: It's O(1). The code will always do precisely the same amount of work.
You can compute the time complexity of this code fragment by evaluating the number of operations, namely the number of calls to printf() which for simplicity's sake we shall assume to be equivalent:
Assuming i starts at 1 (you initially forgot to initialize it), the outer loop runs 99 times, for each iteration, the inner loop runs i times. Gauss was supposedly 9 years old when he computed the resulting number of iterations to be 99 * (99 + 1) / 2.
The complexity of the original piece of code was O(1) since it did not depend on any variable, but since instead you updated the code as:
void fun(int n) {
for (int i = 1; i < n; i++) {
for (int j = i - 1; j >= 0; j--) {
printf("i=%d, j=%d", i, j);
}
}
}
The time complexity would come out as O(n2).

Usage of ternary if [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 9 years ago.
Improve this question
From Wikipedia, the following sections of code are equivalent:
if (a > b) {
result = x;
} else {
result = y;
}
And:
result = a > b ? x : y;
Obviously the use of the ternary if is much more concise, though not as clear.
What I'm wondering is: Is it bad (In terms of readability of code, execution time etc.) to use the ternary if instead of a traditional if statement?
It all depends. I can only think of one situation where a ternary operator undeniably improves readability and even performance (see bottom of this answer). But generally, using the ternary isn't going to improve readability/maintainability of your code. If you use it occasionally, and only for simple assignments then it's OK. not good, just acceptable IMO. Others are, of course, free to disgree with me on that.
Ternaries are expressions, so they should only be used as such (part of an assignment, for example). If you start using ternaries as statements, then you're in trouble. Ternaries are not statements, using them as such is like using a spoon as a screwdriver. Silly.
On the whole, though: it's a matter of taste as long as you don't overdo it. Once you start nesting ternaries, using them with pointers to pointers, or as statements, it's a matter of lunacy.
But to be honest: when in doubt: don't use the ternary operator. It saves you 1 line of code and doesn't improve performance. Take your example:
if (a > b) result = x;
else result = y;
//vs:
result = a > b ? x : y;
if result is the return value of a function, you could even write:
if (a > b) return x;
return y;
Even though I now have 2 return statements, I still find this code easier to read than:
result = a > b ? x : y;
//or
return a > b ? x : y;
That one use-case where a ternary is the best option is this:
const int two_options = some_arg ? 23 : 1;
This enables you to define + initialize a const within a function's scope, depending on a condition, without the overhead of an additional function call (const int two_opts = arg_func(some_arg);, where the function contains the if-else)

Resources