]> Exercises

Exercises

Please complete each exercise or answer the question before reviewing the posted solution comments.

  1. Add comments and use good programming practices to make the following code fragment easy to read and understand. Do not change the execution order or values computed. Do change ' output ' and ' alternate output ' to reflect the actual computation of this fragment.

    HINT: First, add whitespace (spaces, tabs and newlines) to break the program into lines and code blocks. Then, trace the execution line by line with sample input values, follow the changes to each variable and guess what is information is determined and should be output to the user. Try executing the code for different input values to determine what the code does for various input values. Finally, rename the variables and comment the algorithm appropriately.

              a=input('value: ');b=a+2;if( isprime(a)  isprime(b)){disp(' output ');}
              else{disp(' alternate output ');}
              
              % The code determines if a value and the next odd number 
              % are both primes, also known as "Sophie Germain primes".
    
              v1 = input('value: ');         % get the input value
              v2 = value + 2 ;               % create the next value
    
              % test for Sophie Germain primes and output results
              if ( isprime(v1)  isprime(v2) ) { 
                  disp(' values are Sophie Germain primes ');
              }
              else { 
                  disp(' values are not Sophie Germain primes ');
              }
              

    Hopefully, you agree that this is more readable and much preferrable to the code lines above.