Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop enhanced but with ambiguities [closed]

Tags:

c

for-loop

All I want to know is whether this statement is feasible or not

for(j = 2; (j <= i) && flag; j++)

flag is initialized to i before this loop. I have not seen any such thing before.

like image 281
ashi200 Avatar asked Jan 31 '26 00:01

ashi200


1 Answers

The general for loop condition is like this:-

for(initialization ; condition; increment)

So what you are doing is correct.

Breaking down your for loop means:-

for(j=2;(j<=i)&& flag ;j++)

initialization is j=2;

condition is (j<=i)&& flag ;

increment is j++

One example:-

int main(int argc, const char * argv[])
{
    int sum = 0;
    int j = 100;
    for(int i = 1; i<=100/2 && j>100/2; i++){
        sum += i+j;
        j--;
    }

    return sum;

}

Second Example with flag:

Remember bubble sort, In bubble sort we need two nested loops, outer loop runs for number of passes and inner loop do swapping task for each pair a[i], a[i + 1]. To save execution we can make use of some flag variable. If in some pass no swapping done this means no need to execute next pass and sorting completeed, read: Optimizing bubble sort:

Now code for this:

FLAG = 1;
for(i = 0; FLAG && (i < n - 1); i++){//If flag = ), break outer loop sorting done
  FLAG = 0; // set flag = 0
  for(j = 0; j < n - 1 - i; j++){
   if(arr[j] > arr[j + 1]){
    swap(arr[j], arr[j + 1]);
    FLAG = 1; // if any swapping need, then check in next round  
   }
 }
}

Notice outer loop condition FLAG && (i < n - 1), I think this is what you wants. Hope this help!

like image 127
Rahul Tripathi Avatar answered Feb 02 '26 15:02

Rahul Tripathi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!