Site icon TestingDocs.com

Octave If Statement

Overview

In this tutorial, we will learn about Octave if statement. The if statement is a decision-making statement.

If statement

In the simplest form, the if statement syntax looks like this:

if (if-condition)
    if-body
endif

or

if (if-condition)
    if-body
end

The if-condition is an expression that controls the flow of the if block. The if-body is executed only if the condition is true. The condition expression in an if statement is true if its value is non-zero, and false if its value is zero.

If – else statement

if (condition)
     if-body
else
     else-body
endif

or

if (condition)
     then-body
else
     else-body
end

 

We can also have the else body for the if statement.
If condition expression evaluates to true, if-body is executed; otherwise, the else-body is executed.

Sample Script

% ======================================
% Sample Octave Script
% If statement demo
% Octave Tutorials – www.TestingDocs.com
% ======================================

fprintf(‘Welcome.\n’);
% Prompt user
a = input(‘Enter value for a :’);
b = input(‘Enter value for b :’);

% if statement to check if a > b
if(a > b)
fprintf(‘a is greater than b. \n’);
else
fprintf(‘a is less than or equal to b. \n’);
end
fprintf(‘Good Bye!\n’);

 

Output

>> IfElseDemo

Welcome.
Enter value for a :9
Enter value for b :16
a is less than or equal to b.
Good Bye!
>>

if-elseif-else ladder

We can also have multiple decisions combined in a single if statement

if (condition)
     if-body
elseif (condition)
    elseif-body
else
     else-body
endif

 

Example

% Sample Octave Script 
% If Statement Demo
% Octave Tutorials - www.TestingDocs.com
marks = input('Enter marks:');

% if-else ladder statement
if( marks >= 90 && marks <= 100) 
 fprintf('Grade: A+ - Excellent :-) \n'); 
elseif( marks >= 80 && marks < 90) 
 fprintf('Grade: A - Good \n'); 
elseif( marks >= 70 && marks < 80) 
 fprintf('Grade: B+ - Above Average \n'); 
elseif( marks >= 60 && marks < 70) 
  fprintf('Grade: B Average \n'); 
elseif( marks >= 50 && marks < 60) 
  fprintf('Grade: C+ Need Improvement \n');
elseif( marks >= 40 && marks < 50)
  fprintf('Grade: C Poor \n');
else
  fprintf('Fail: No Grade :-( \n');
end

Octave Tutorials

Octave Tutorial on this website can be found at:
https://www.testingdocs.com/octave-tutorial/

More information on Octave can be found on the official website:
https://www.gnu.org/software/octave/index

Exit mobile version