Questions tagged [if-statement]

An "if" statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If statements are also commonly also called conditionals. When using this tag please also include an appropriate language tag, such as e.g. "java" if your question is language-specific.

An if statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If-statements are also commonly known as conditionals.

When using this tag please also include an appropriate language tag, such as e.g. if your question is language-specific.


Basic Syntax

The if statement has the following syntax:

if <condition>
then
     <statement-1>
else
     <statement-2>

<condition> may be parenthesized (as it is in JavaScript), the keyword then may be omitted (Python, C-like languages, JavaScript and others).

The else section is optional in most languages.

An example if statement in JavaScript:

var myVariable = 100;

if (myVariable >= 20) {
    console.log('My variable is greater than or equal to 20!');
} else {
    console.log('My variable is less than 20!');
}

if-else statements may also be nested, where another if may appear in if statement, and/or in else statement. For example:

if ( number1 > 20 )
   if ( number2 > 50 )
      print('Both numbers satisfy condition')
   else
      print('Second number doesn't satisfy condition')
else
   if( number2 > 50 )
      print('Only Second number satisfies condition')
   else
      print('None of the two numbers satisfy condition')

else+if is used to chain if statements:

if ( number > 20 )
     print('Greater than 20')
else+if ( number > 10 )
     print('Greater than 10')
else
     print('Less than 11')

else+if statements may simply be an else statement followed by an if (e.g else if; done in JavaScript and many C-like languages), or a special keyword such as elif (Python), or elsif (Perl).


As a ternary operator

In C and C-like languages, conditional expressions can take the form of a ternary operator called the conditional expression operator, ?:, which follows this template:

(condition)?(evaluate if condition was true):(evaluate if condition was false)

In Python, if is used explicitly, and the ordering is slightly different:

(evaluate if condition was true) if (condition) else (evaluate if condition was false)

An example of the ternary operator in JavaScript:

var myVariable = 100;

myVariable>20 ? console.log('Greater than 20!') : console.log('Less than or equal to 20!');

See also:

52698 questions
6
votes
4 answers

Only allow letters and numbers for a UITextField

I have a signup view controller where the user needs to enter an email address, a username, and a password. For the username and password fields, right now you can currently sign up with a username like "user%$&" and a password like "password%^&$".…
user3344977
  • 3,454
  • 4
  • 29
  • 82
6
votes
1 answer

Boolean Not Equal To in Lua programming

How to write if statement in Lua with not equal symbol for boolean variable. //In Java, boolean a; a = false; if(!a){ //do something } -- In Lua I am trying to replicate the same code local a a = false if(~a) then -- do…
Venkatesh
  • 2,788
  • 7
  • 25
  • 34
6
votes
3 answers

Is there a better way to rewrite this ugly switch and if statement combination?

Essentially I have a system of gamma detectors that are segmented into 4 crystals each, in the case when only 2 of the of crystals register a hit we can determine if the pair was perpendicular or parallel to the plane of the reaction generating the…
James Matta
  • 1,514
  • 15
  • 34
6
votes
4 answers

Why does not the true match 'true' with double equals sign '==' in JavaScript?

This small portion of code took a long time to be noticed. I thought if I do the following, it would be fine if('true' == true) { alert("Does not happen"); } But it does not pass the if condition. I thought the double equals == matches the …
me_digvijay
  • 5,087
  • 5
  • 41
  • 78
6
votes
5 answers

sql if exists update else insert not working

i have a table with 3 generic keys which are also foreign keys. This is my query -- IF (EXISTS(SELECT * FROM table1 WHERE col_1 =4)) BEGIN UPDATE table1 SET col_2 = 3, col_3 = 100 WHERE col_1 = 4 …
user983983
  • 160
  • 1
  • 2
  • 11
6
votes
4 answers

How do I loop a request for user input until the user enters the correct info?

I am a beginner who is trying to learn Ruby. I have learned some of the easier stuff so far, but I seem to be stuck in trying to combine a couple of things I've learned. What I am trying to do is to ask the user a question and tell them to enter…
Bushido Code
  • 63
  • 1
  • 1
  • 4
6
votes
2 answers

Adding braces for If-else using Uncrustify

I was wondering if there is any way to add braces in nested If-else using Uncrustify. For example: if( stat_error == -1 ){ if ( debug > 0 ) printf( "...ERROR ); //I would like to add braces around here. exit( -1 ); } else { I have seen…
Cod1ngFree
  • 1,813
  • 5
  • 19
  • 32
6
votes
7 answers

Possible to use && or || in switch statement? Visual C#

So I was making a Rock Paper Scissor game and I've sort of made adjustments to it to include life and other things. Now I got stuck with the switch statement. My if statement works fine: private void Result_TextChanged(object sender, EventArgs e) { …
user2911044
  • 97
  • 1
  • 2
  • 4
6
votes
5 answers

How to check if string character is a space?

I've just started programming in C#. I'm trying to build a simple Vigenere text encryption tool as a personal project. My problem should be very easy to fix, yet it's really stressing me out to find the error. In my code I'm trying to do a simple…
ninjatogo
  • 63
  • 1
  • 1
  • 4
6
votes
8 answers

Are these 2 statements identical?

Do the following 2 code snippets achieve the same thing? My original code: if (safeFileNames != null) { this.SafeFileNames = Convert.ToBoolean(safeFileNames.Value); } else { this.SafeFileNames = false; } What ReSharper thought was a better…
JL.
  • 71,902
  • 119
  • 298
  • 446
6
votes
4 answers

IF function with 3 conditions

I'm looking to create a formula with 3 conditions. It is currently only working with 2 conditions. Here's what I'm looking for: E9 has a number If the number is 21+ then I want it to show Text 1 If the number is between 5 and 21, then I want it to…
Dalilah Perez
  • 63
  • 1
  • 1
  • 3
6
votes
6 answers

In Objective-C Check an array of Boolean Values and see if at least ONE is YES

I have a mutable array of Boolean values and I want to check to see if ANY of the values are YES. At present I am creating another array alongside this one which is always ALL False like so; [MyArray addObject:[NSNumber…
Recycled Steel
  • 2,204
  • 3
  • 27
  • 35
6
votes
7 answers

Performance Differences of Nested If Else Statements vs. ElseIf Statements

A coworker and I have differing opinions on If statements and their performance. My view is that If...ElseIf statements should be used. His view is that he doesn't believe in ElseIf, and writes everything with nested If statements. Let's assume that…
Nicholas Post
  • 1,783
  • 1
  • 17
  • 28
6
votes
4 answers

Shortcut for if else

What is the shortest way to express the folowing decission rule df<-data.frame(a=LETTERS[1:5],b=1:5) index<-df[,"a"]=="F" if(any(index)){ df$new<-"A" }else{ df$new<-"B" }
Klaus
  • 1,676
  • 1
  • 18
  • 34
6
votes
2 answers

A Return inside and outside an If Statement

This is probably a fairly easy question to answer, but it has been bugging me some time. If there is a return statement inside an if statement, inside a method (in the Java language), but I add another at the end as a catch-all and to avoid the…
A13X
  • 310
  • 1
  • 3
  • 21