Search This Blog

#Day2- #100DaysChallenge- Matlab Loops| Get a single Digit

#Day2-Get a single Digit

Task: Write a function that accepts only a single-digit value from 1 to 9 as input, if it is not within the given limit then print as Invalid output and ask the user to enter the input until they enter a single digit.

Matlab Code:

function digit=get_digit()
digit=0;

while digit==0     % continue untill input is single digit
    in=input('Enter  a digit');
    if (in<=9) && (in>=0) && (mod(in,1)==0)  % condition  to check if the given value is single digit or not    
    digit=in; 
   else  
     fprintf('invalid Output\n');  %printing output value
   end
   
end
end

Sample Input:



 digit=get_digit()

Enter  a digit 3456789

invalid Output

Enter  a digit -89

invalid Output

Enter  a digit  567

invalid Output

Enter  a digit 34

invalid Output

Enter  a digit 5

digit =

     5

Click Here for Code explanation


Join us on Telegram: https://t.me/matlabirawen Join us on Facebook Group: https://www.facebook.com/groups/matlabcodes



1 comment:

  1. % Without function
    clc;clear all;

    x=input('Please input a Single Digit:');
    if x < 9 && x > 0
    display(x)
    else
    display('Please enter Between 0 and 10:')
    end

    %but after second entry it stopped. Anyone could correct?

    ReplyDelete

MATLAB