EzDevInfo.com

if-statement interview questions

Top if-statement frequently asked interview questions

if else statement in AngularJS templates

I want to do a condition in an AngularJS template. I fetch a video list from the Youtube API. Some of the videos are in 16:9 ratio and some are in 4:3 ratio.

I want to make a condition like this:

if video.yt$aspectRatio equals widescreen then 
    element's attr height="270px"
else
    element's attr height="360px"

I'm iterating the videos using ng-repeat. Have no idea what should I do for this condition:

  • Add a function in the scope?
  • Do it in template?

Source: (StackOverflow)

Else clause on Python while statement

I've noticed the following code is legal in Python. My question is why? Is there a specific reason?

n = 5
while n != 0:
    print n
    n -= 1
else:
    print "what the..."

Thanks.


Source: (StackOverflow)

Advertisements

C# - Assignment in an if statement

I have a class Animal, and its subclass Dog. I often find myself coding the following lines:

if (animal is Dog)
{
    Dog dog = animal as Dog;    
    dog.Name;    
    ... 
}

For the variable Animal animal;.

Is there some syntax that allows me to write something like:

if (Dog dog = animal as Dog)
{    
    dog.Name;    
    ... 
}

Source: (StackOverflow)

"elseif" syntax in JavaScript

Is this correct?

if(condition)
{

} 
elseif(condition)
{

}
else
{

}

Source: (StackOverflow)

inline conditionals in angular.js

I was wondering if there is a way in angular to conditionally display content other than using ng-show etc. For example in backbone.js I could do something with inline content in a template like:

<% if (myVar === "two") { %> show this<% } %>

but in angular, I seem to be limited to showing and hiding things wrapped in html tags

<p ng-hide="true">I'm hidden</p>
<p ng-show="true">I'm shown</p>

What is the recommended way in angular to conditionally show and hide inline content in angular just using {{}} rather than wrapping the content in html tags?


Source: (StackOverflow)

break out of if and foreach

I have a foreach loop and an if statement. If a match is found I need to ultimately break out of that foreach and if.

foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;
        <break out of if and foreach here>
    }       
}

Source: (StackOverflow)

jQuery if checkbox is checked

I have a function below that I want to only trigger when a checkbox in the same tr is checked. Please tell me what I am doing wrong, the usual methods are not working. Thanks

JS

$(".add_menu_item_table").live('click', function() {
var value_td = $(this).parents('tr').find('td.td_name').text();
if ($('input.checkbox_check').attr(':checked')); {
    var newDiv = $('<div class="div_menu_button"></div>');
    var showDiv = $('<div id="show'+ "0" + numShow++ +'" class="menu_button_info hidden"></div>');
    var toggleTrigger = $('<a id="toggleshow'+ "0" + numToggle++ +'" data-target="#show'+ "0" + numTarget++ +'" class="toggle_trigger actions">&nbsp;</a><div style="padding:5px"></div>');
    var menuForm = $('<form id="menu_edit_form'+ "0" + numForm++ +'" class="menu_creation_form"></form>');
    $('#created_buttons_list').append(
        newDiv.text(value_td));
        newDiv.wrap("<li></li>");
        newDiv.append(toggleTrigger);
        newDiv.append(showDiv);
        showDiv.append(menuForm);
        menuForm.html('<label for="navigation_label">Navigation Label</label><input id="navigation_label'+ "0" + numLabelone++ +'" type="text" placeholder="Navigation Label" name="navigation_label"><label for="attribute">Attribute</label><input id="attribute'+ "0" + numLabeltwo++ +'" type="text" type="text" placeholder="Attribute" name="attribute"><label for="url">URL</label><input id="url'+ "0" + numLabelthree++ +'" type="text" type="text" placeholder="URL" name="url"><input type="button" value="Remove" class="button_link remove_button"> <input type="reset" value="Cancel" class="button_link">');
}
});

var numToggle = 0;
var numShow = 0;
var numTarget = 0;
var numForm = 0;
var numLabelone = 0;
var numLabeltwo = 0;
var numLabelthree = 0;

HTML

<table width="316px" border="0" cellspacing="0" cellpadding="0" id="table-data">
                  <tbody>
                  <tr>
                    <td width="20px"><input type="checkbox" style="width:20px;" value="1" name="checkbox"></td>
                    <td width="200px"><a rel='nofollow' href="/admin/feedbackmanager/sortby/2/sortdesc/0">Page Name</a></td>
                    <td width="20px"><a rel='nofollow' href="/admin/feedbackmanager/sortby/3/sortdesc/0">Add</a></td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
                    <td class="td_name">Timeplot</td>
                    <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
                    <td class="td_name">Operations Manuals</td>
                    <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
                    <td class="td_name">Company Structure</td>
                    <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
                    <td class="td_name">CMS Report</td>
                    <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
                    <td class="td_name">Test Document</td>
                    <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
                  </tr>
                  <tr>
                    <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
                    <td class="td_name">Test CMS page</td>
                    <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
                  </tr>
                  </tbody>
                  </table>

Source: (StackOverflow)

Can I use if(pointer) instead of if(pointer != NULL)?

Is it safe to check a pointer to not being NULL by writing simply if(pointer) or do I have to use if(pointer != NULL)?


Source: (StackOverflow)

How can a Java variable be different from itself?

I am wondering if this question can be solved in Java (I'm new to the language). This is the code:

class Condition {
    // you can change in the main
    public static void main(String[] args) { 
        int x = 0;
        if (x == x) {
            System.out.println("Ok");
        } else {
            System.out.println("Not ok");
        }
    }
}

I received the following question in my lab: How can you skip the first case (i.e. make the x == x condition false) without modifying the condition itself?


Source: (StackOverflow)

Python's equivalent of && in an if statement

Here's my code:

# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back
def front_back(a, b):
  # +++your code here+++
  if len(a) % 2 == 0 && len(b) % 2 == 0:
    return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):] 
  else:
    #todo! Not yet done. :P
  return

I'm getting an error in the IF conditional. What am I doing wrong?


Source: (StackOverflow)

How to avoid "if" chains?

Assuming I have this pseudo-code:

bool conditionA = executeStepA();
if (conditionA){
    bool conditionB = executeStepB();
    if (conditionB){
        bool conditionC = executeStepC();
        if (conditionC){
            ...
        }
    }
}

executeThisFunctionInAnyCase();

Functions executeStepX should be executed if and only if the previous succeed. In any case, the executeThisFunctionInAnyCase function should be called at the end. I'm a newbie in programming, so sorry for the very basic question: is there a way (in C/C++ for example) to avoid that long if chain producing that sort of "pyramid of code", at the expense of the code legibility?

I know that if we could skip the executeThisFunctionInAnyCase function call, the code could be simplified as:

bool conditionA = executeStepA();
if (!conditionA) return;
bool conditionB = executeStepB();
if (!conditionB) return;
bool conditionC = executeStepC();
if (!conditionC) return;

But the constraint is the executeThisFunctionInAnyCase function call. Could the break statement be used in some way?


Source: (StackOverflow)

Python style: multiple-line conditions in IFs

Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:

  if (cond1 == 'val1' and cond2 == 'val2' and
      cond3 == 'val3' and cond4 == 'val4'):
      do_something

Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.

For the moment I'm using:

  if (    cond1 == 'val1' and cond2 == 'val2' and
          cond3 == 'val3' and cond4 == 'val4'):
      do_something

But this isn't very pretty. :-)

Can you recommend an alternative way ?


Source: (StackOverflow)

How to do a logical OR operation in Shell Scripting

I am trying to do a simple condition check, but it doesn't seem to work.

If $# is equal to 0 or is greater than 1 then say hello.

I have tried the following syntax with no success:

if [ "$#" == 0 -o "$#" > 1 ] ; then
 echo "hello"
fi

if [ "$#" == 0 ] || [ "$#" > 1 ] ; then
 echo "hello"
fi

Source: (StackOverflow)

Too many 'if' statements?

The following code does work how I need it to, but it's ugly, excessive or a number of other things. I've looked at formulas and attempted to write a few solutions, but I end up with a similar amount of statements.

Is there a type of math formula that would benefit me in this instance or are 16 if statements acceptable?

To explain the code, it's for a kind of simultaneous-turn-based game.. two players have four action buttons each and the results come from an array (0-3), but the variables 'one' & 'two' can be assigned anything if this helps. The result is, 0 = neither win, 1 = p1 wins, 2 = p2 wins, 3 = both win.

public int fightMath(int one, int two) {

    if(one == 0 && two == 0) { result = 0; }
    else if(one == 0 && two == 1) { result = 0; }
    else if(one == 0 && two == 2) { result = 1; }
    else if(one == 0 && two == 3) { result = 2; }
    else if(one == 1 && two == 0) { result = 0; }
    else if(one == 1 && two == 1) { result = 0; }
    else if(one == 1 && two == 2) { result = 2; }
    else if(one == 1 && two == 3) { result = 1; }
    else if(one == 2 && two == 0) { result = 2; }
    else if(one == 2 && two == 1) { result = 1; }
    else if(one == 2 && two == 2) { result = 3; }
    else if(one == 2 && two == 3) { result = 3; }
    else if(one == 3 && two == 0) { result = 1; }
    else if(one == 3 && two == 1) { result = 2; }
    else if(one == 3 && two == 2) { result = 3; }
    else if(one == 3 && two == 3) { result = 3; }

    return result;
}

Source: (StackOverflow)

Difference between if (a - b < 0) and if (a < b)

I was reading Java's ArrayList source code and noticed some comparisons in if-statements.

In Java 7, the method grow(int) uses

if (newCapacity - minCapacity < 0)
    newCapacity = minCapacity;

In Java 6, grow didn't exist. The method ensureCapacity(int) however uses

if (newCapacity < minCapacity)
    newCapacity = minCapacity;

What was the reason behind the change? Was it a performance issue or just a style?

I could imagine that comparing against zero is faster, but performing a complete subtraction just to check whether it's negative seems a bit overkill to me. Also in terms of bytecode, this would involve two instructions (ISUB and IF_ICMPGE) instead of one (IFGE).


Source: (StackOverflow)