Changing the if statement into a while statement - c

I'm trying to change an if statement into a while statement.
For example
int A=1; if(A==1){};
is similar to int A=1 while(A!=1).
My If statement has no codes, I just need it to do nothing in order to avoid the else-if statements.
My If statement is inside 1 While statement and 1 If statement.
So I want the program to do the same thing in the while statement rather than going in 1 While statement and 1 If statement with an If statement with no code.
Original codes something like this
while(C1)
{
if(C2)
{
if( h->data[temp] < h->data[temp*2] && h->data[temp] < h->data[temp*2+1] )
{
break;
}
else if(C4)
{
DO();
}
}
}
I've changed it to
while( C1 && h->data[temp] > h->data[temp*2] && h->data[temp] > h->data[temp*2+1] )
{
if(C2)
{
if(C4)
{
DO();
}
}
}
and the result is different. The original code gives the correct result but the changed code gives an incorrect result. I've only changed the location to if to while and also changed the direction of the < operator to the > operator.
The total code seems like I've spent less effort in it, making down votes. So I'm posting the code somewhat like a pseudo code.

For example int A=1; if(A==1){}; is similar to int A=1 while(A!=1).
As already mentioned, your loop is breaking. The above statement is also incorrect.
int a = 1;
if(a == 1) {} //this is true, and will happen once
BUT
int a = 1;
while(a != 1) {} //false on entry, skip loop ( never entered )
You could also consider a switch / case if you can isolate the condition.
This might achieve your goal of removing the ifs, and make the code more readable.
e.g
int a = 1;
while(a)
{
switch(a)
{
case 1: ++a; continue;
case 2: do();
default: break; //end loop
}
}

In the original code, if (for example) h->data[temp]>h->data[temp*2] were false, DO() wouldn't be executed, but the loop would continue. In the new version, the loop would stop.

As others said, there is no reason to obfuscate the code with an extra while statement; the original is perfectly clear. There is also no need for the else in your original:
while(C1)
{
if(C2)
{
if( h->data[temp] < h->data[temp*2] && h->data[temp] < h->data[temp*2+1] )
{
break;
}
if(C4)
{
DO();
}
}
}

Related

while loop replicating a for loop

Hi im trying to do a disk scheduling algorithm (C-SCAN).I have a for loop with an if statement that works, however im trying to change it to a while loop or another option to remove the break statement.
for(i=0;i<n;i++)
{
if(initial<RQ[i])
{
index=i;
break;
}
}
while ( initial>RQ[i] )
{
index =i;
i++;
}
The above for loop is what im trying to replicate as seen in my while loop. however it is not working the same way.
any help will be much appreciated
A for loop of the form
for (initialization; condition; repetition) {
// body code
}
is equivalent to:
initialization;
while (condition) {
// body code
repetition;
}
So your loop would be rewritten as:
i = 0;
while (i < n) {
if (initial < RQ[i]) {
index = i;
break;
}
i++;
}
One possibility of removing the break statement would be to introduce an additional flag variable which gets set when the loop should be terminated.
#include <stdbool.h>
[...]
bool terminate = false;
for( i=0; i<n && !terminate ; i++ )
{
if(initial<RQ[i])
{
index=i;
terminate = true;
}
}
However, I personally consider it better to use a break statement.

Can I use an if statement as condition in another if statement in C?

Can I do that? I´ve searched for an answer, but I couldn´t found any. What I want to do is this:
if(a==5)
{
printf("25");
}
if((if(a==5))==TRUE)
{
printf("\n30");
}
Is this permissible in C?
Can I use an if statement as condition in another if statement in C?
No, you can´t do that, it isn´t syntactically correct. You would get this or a similar error for the inner if test, if you would attempt to compile code that has any occurrence of that in its source code:
error: expected expression before 'if'
But it is already redundant since you can proof several expressions inside just one if statement´s condition test by using the logic operators &&(AND) and ||(OR):
int a = 5;
int b = 10;
if(a == 5 && b == 10) // If a is 5 AND b is 10. - true
{
/* some code */
}
or
int a = 6;
int b = 10;
if(a == 5 || b == 10) // If a is 5 OR b is 10. - true
{
/* some code */
}
Given your example:
if(a==5)
{
printf("25");
}
if((if(a==5))==TRUE)
{
printf("\n30");
}
The inner if statement inside the condition of the outer if statement - if((if(a==5)) == TRUE) isn´t permissible but also redundant, because an if statement proofs on its own whether the condition or a sub-expression is true or not.
Thus, if((if(a==5)) == TRUE), if((a==5) == TRUE) and if(a==5) would be all equivalent, if a if condition test inside the condition of another were permissible and the if statement shall somehow be evaluated to 1.
So even in this surreal case, the code in the example would be equivalent to:
if(a==5)
{
printf("25");
printf("\n30");
}
This
if(a==5)
{
printf("25");
}
if((if(a==5))==TRUE)
{
printf("\n30");
}
can be rewritten this way with keeping the same logic
int condition;
if( ( condition = a == 5 ) )
{
printf("25");
}
if( condition )
{
printf("\n30");
}

How to simplify compound negated logic

Lets say I have array of boolean values B[], or I am figuring out true/false using function. How can I simplify this code, it there are many values (maybe tens of them)? Here is pseudocode:
if(!B[0]){
doTask1;
}
if(!B[0] && !B[1]){
doTask1;
doTask2;
}
if(!B[0] && !B[1] && !B[2]){
doTask1;
doTask2;
doTask3;
}
...
Edit 1: I forgot to mention, that I want doTask1 etc. happen only once (if any of there ifs is true), not doing it multiple times(if for example 1.st if is true, second one is true too, i still need to happen it only once)
You can use array of function pointers.
typedef void *(* funcPtr)(void);
funcPtr arrayFunPtr[N];
Then store the functions into the array.
arrayFunPtr[0]= task1;
arrayFunPtr[1]= task2;
....
arrayFunPtr[N-1]= taskN;
Then loop the bool array and call respective index function.
for(int i=0;i<N;i++)
{
if(!B[i]) arrayFunPtr[i]();
}
#Edit.
If you want to stop calling tasks function once you hit B[i]=true use the below code.
for(int i=0;i<N && !B[i] ;i++)
{
arrayFunPtr[i]();
}
(Assuming you don't want to make the same task more than once, even though your original code will)
Make a function doTask() which will take the number of the task to do (or just make an array of function pointers). And then:
for(i=0; i < numberOfTasks; i++)
{
if (!B[i])
doTask(i);
else
break;
}
Or more concisely:
for(i=0; i < numberOfTasks && !B[i]; i++)
{
doTask(i);
}
Function pointers is the way to go here.
If you do not like function pointer you might use the switch construct as shown below:
switch(i) {
case 3:
if(!B[0] && !B[1] && !B[2]) doTask3();
case 2:
if(!B[0] && !B[1]) doTask2();
case 1:
if(!B[0]) doTask1();
}
Or you can do :
You can write a method :
simplify(int[] B, int l) {
for (int i =0 ; i < l, i++) {
// write the code using &&
}
}
Then can call this method as :
if(simplify(B, 1){
doTask1;
}
if(simplify(B, 2){
doTask1;
doTask2;
}
etc.

Implementing loops on the basis of condition in C

I have a set of statements that need to be executed in two different loops; the loops identified on the result of a check condition. There are multiple such sets of this type.
Set A : statement 1
statement 2
statement 3
Set B : statement 4
statement 5
statement 6
and so on..
Now they need to be executed as follows:
if(condition 1)
loop over some Loop A
execute Set A
else if(condition 2)
loop over some loop B
execute Set A
These loops can be completely different from each other.
Now, for the sake of code clarity, I don't wish to write the code as mentioned above. Another reason being I'll have to make multiple sets in order to group them together.
Is there any mechanism by which I could achieve the following:
CHECK_CONDITION_AND_LOOP_HERE
execute Set A
I've tried using macros to achieve this, using braced-group within expression but could not . I also tried using ternary operators as well as fall through a switch case to achieve this, but could not get the same result.
Is there any way in C using which I could achieve the desired behavior?
Sample code for the problem:
if(condition A)
for(i=0; i<10; i++, k*=2) {
execute Set A; //Operations performed here use variable k
}
else if(condition B)
for(j=5; j<75; j+=5, k*=arr[j]) {
execute Set A; //Operations performed here use variable k
}
The answer to Version 1 of the question:
Given that the only difference is the range of values over which the statements are executed, you can use a couple of variables to store the range end-points, e.g.
int first = 0;
int last = -1;
if (condition1) {
first = 1;
last = 10;
} else if (condition2) {
first = 3;
last = 7;
}
for ( int i = first; i <= last; i++ )
execute set A
Note that initializing last to be less than first prevents the body of the loop from running if neither condition is met.
The answer to Version 2 of the question:
Here's the code from the question. I've made some changes for clarity, and to make the question more concrete.
if (cond1)
for (initA;condA;updateA)
execute SetX
else if (cond2)
for (initB;condB;updateB)
execute SetX
Here's the refactored code
int is1 = cond1;
int is2 = is1 ? 0 : cond2;
if (is1)
initA;
if (is2)
initB;
while ( (is1 && condA) || (is2 && condB) )
{
execute SetX
if ( is1 )
updateA;
if ( is2 )
updateB;
}
A function, maybe?
void func_A() {
printf("Here0\n");
printf("Here1\n");
}
...
if(a < b) {
for(i = 1; i <= 10; i++) {
func_A()
}
}
else if(a == b) {
for(i = 3; i <= 7; i++) {
func_A()
}
}
Or if you want to only make one call/block:
if(a < b) {
min = 1; max = 10;
}
else if(a == b) {
min = 3; max = 7;
}
for(i = 3; i <= 7; i++) {
printf("Here0\n");
printf("Here1\n");
}

Is there a difference between multiple if statements and else if?

If I write
int a = 1;
int b = 2;
if (a == b) {
//Do something
} else if (a > b) {
//Do something else
} else if (a < b) {
//Do something else
}
as opposed to:
if (a == b) {
//Do something
}
if (a > b) {
//Do something else
}
if (a < b) {
//Do something else
}
Is there a difference be it the way the compiler interprets the code or speed? I see no logical difference, but there surely must be a reason why an if else statement exists. It's just a single line break difference.
In the scenario above, they are the same, other than speed. If/else will be faster than a series of ifs, because else statements are skipped if the if condition is satisfied. In a series of ifs, on the other hand, each condition is evaluated separately.
In other scenarios, of course, the logic is not the same, and so replacing if/else with a series of ifs breaks the program. Example:
// this:
if(x <= 0) {
x = 1;
}
else { // only true if x started out > 0
x = 37;
}
// is different from this:
if(x <= 0) {
x = 1;
}
if(x > 0) { // always true in this version
x = 37;
}
In else-if statements, when a condition is met, all other else-ifs are skipped.
Whereas in multiple if statements, it has to go through all of them.
To be more precise, Lets suppose a=b.
Consider your first code block:
int a = 1;
int b = 1;
if (a == b)
{
//Do something
}
else if (a > b)
{
//Do something else
}
else if (a < b)
{
//Do something else
}
While executing, since a=b, it will skip all other conditions (a>b & a<b).
Checks if a=b.
Executes the code block.
All others are skipped.
Consider your second code block:
int a = 1;
int b = 1;
if (a == b)
{
//Do something
}
if (a > b)
{
//Do something else
}
if (a < b)
{
//Do something else
}
Even the first condition is met, all of them will be evaluated.
Checks if a=b.
Executes the code block.
Checks if a>b.
Checks if a<b.
In second type of code you wrote. Compiler will show out put for each true statement and will not skip any condition. Else command is use to make sure that one of two conditions are matched.
the time complexity of if-else statements is less as compared to multiple if statements. Therefore if-else steements are much advantageous

Resources