IF ELSE Loop (this is for your understanding)
###### Posted by JanWan
Last Updated: July 06, 2012

IF ELSE Loop

Another means of controlling the flow is to say "If <some circumstance exists>: <do this>." Obviously, if the circumstance does not exist, the computer will ignore the lot. Sometimes, however, it is nice to have a "default setting" for the program's flow, an "else": If <a particular circumstance exists>: <do this> else: <do that>. The following templates and examples illustrate how these two loops are written:

`````` if <condition>:
<action to be taken> ``````
or
`````` if <condition>:
<action to be taken>
else:
<default action> ``````
`````` if c < 0:
print c ``````
`````` if animal == dog:
print "bow-wow"
else:
print "meow" ``````

You might think it a bit cludgy to have to write 'if...else' statements for every possible option. You would be right, and this is why Python has an additional, optional part of the 'if' loop: 'elif'. 'elif' is for the various options that fit neither the 'if' nor the else. The template and an example are as follows:

`````` if <1st condition>:
<action to be taken>
elif <2nd condition>:
<other action to be taken>
else:
<default action> ``````
`````` if animal == 'dog':
print "bow-wow"
elif animal == 'cat':
print "meow"
else:

J.W. PRODUCTION

###### Find factorial using loop in C++
Samath | Nov 02, 2014
###### C Program that Print First 10 Natural Numbers using For, While and Do-While Loop
Samath | Jan 02, 2017
###### Java program that uses a loop to compute the sum of all even numbers between 2 and 100 (inclusive)
Samath | Apr 03, 2022
###### Javascript program that check if a word is palindrome using one for loop
SceDev | Feb 17, 2024
###### Java program that uses a loop to compute the sum of all squares between 1 and 100 (inclusive)
Samath | Apr 03, 2022
###### Java program that uses a loop to compute the sum of all even numbers between a and b (inclusive), where a and b are inputs
Samath | Apr 03, 2022
###### Java program that uses a loop to compute the sum of all odd digits of an input. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)
Samath | Apr 03, 2022