Examples

  1. Open your input_demo program from the previous lesson and then do File->Save As and save it as if_else_demo.m. Then modify the new program to ask if the user has celebrated their birthday yet this year. Then use that user input to determine the actual age of the user. Here are the necessary modifications:
        %% Test of input
        name = input(' Hello, what is your name? ', 's' );
        reply = input([' It is good to meet you, ', name, ...
              '. How are you today? '], 's' );
        birth_year = input([' ', name, ', what year were you born? ' ]);
        birthday = input(' Did you celebrate your birthday yet this year?  Enter 1 for yes or 0 for no? ');
    
        if ( birthday == 1 )
           age = 2006 - birth_year;
        else 
    	    age = 2006 - birth_year - 1;
        end
    
        disp([' ', name, ', you are looking ', reply , ...
                ' today for a ', num2str(age), ' year old person. '] )
    
    Notice that the conditional expression in the if statement is used to test if the user's birthday has occurred yet this year. The conditional operator == is used to test for equality. This and other operators are discussed in the next lesson.

    If the birthday value is 1, then one calculation is performed, if the birthday is NOT 1, then a different calculation is performed.