Friday, 28 December 2018

Ciena Interview Experience

Coming Soon

Friday, 15 June 2018

Comma Operator inside for loop Condition in C++

You may have used Comma operator in initilialization and increment part of for loop like below

                 for(init;condition;increment) --> for(int i=0,j=5;i<j;i++,j--)


But can we used Comma operator inside for loop condition ?

The answer is Yes but it behave bit differently.

Predict the output of below program


void commaOperator()
{
    int i=0,j=0;
    cout<<"Using && inside for loop Condition"<<endl;
    for(;i<4&&j<6;)
    {
            cout<<i<<" "<<j<<endl;
            i++;
            j++;
    }
    cout<<"Using comma inside for loop Condition "<<endl;
    i=0,j=0;
    for(;i<4,j<6;)
    {
            cout<<i<<" "<<j<<endl;
            i++;
            j++;
    }

}



Output:
Using && inside for loop Condition
0 0
1 1
2 2
3 3
Using comma inside for loop Condition
0 0
1 1
2 2
3 3
4 4
5 5

As Comma operator is a binary operator it evaluates first operand but discards its result and then evaluates the second operand and returns its result.
In above example , for loop will run till second condition is true (j<6 ) and discards the first condition.

But what if we use comma operator in assignment like below
int a=5,b=7,c;
c=a,b;

Here c will be equal to a (5) as assignment has higher precedence than comma operator.


Please comment if you find anything incorrect.




Saturday, 26 May 2018

Find Consecutive Elements in Unsorted Array in O(n) - C++ Code



#include<iostream>
#include<set>

int findConsecutiveElements(int arr[], int n)
{
        std::set<int> s;
        int ans = 0;

        for (int i = 0; i < n; i++)
                s.insert(arr[i]);

        for (int i=0; i<n; i++)
        {
                if (s.find(arr[i]-1) == s.end())
                {
                        int j = arr[i];
                        while (s.find(j) != s.end())
                                j++;

                        ans = std::max(ans, j - arr[i]);
                }
        }
        return ans;
}

int main()
{
        int arr[] = {1,21, 24, 25, 9, 3, 11, 4, 20, 22,23};
        int n = sizeof arr/ sizeof arr[0];
        std::cout << "Length of the Longest consecutive elements is "
                << findConsecutiveElements(arr, n);
        return 0;
}