COMP 1917 Computing 1
Session 2, 2016

Lab Solutions - Week 4


Note: This code should be appropriately commented.

  1. $ mkdir lab4
    $ cd lab4
    
  2. int rotate_right( int ch )
    {
       if( ch == 'Z' ) {
          return( 'A' );
       }
       else if( ch == 'z' ) {
          return( 'a' );
       }
       else if(  ( ch >= 'A' && ch < 'Z' )
               ||( ch >= 'a' && ch < 'z' )) {
          return( ch + 1 );
       }
       else {
          return( ch );
       }
    }
    
  3. int rotate_left( int ch )
    {
       if( ch == 'A' ) {
          return( 'Z' );
       }
       else if( ch == 'a' ) {
          return( 'z' );
       }
       else if(  ( ch > 'A' && ch <= 'Z' )
               ||( ch > 'a' && ch <= 'z' )) {
          return( ch - 1 );
       }
       else {
          return( ch );
       }
    }
    
  4. int encode( int ch, int shift )
    {
      int i;
    
      if( shift >= 0 ) {
        for( i=0; i < shift; i++ ) {
          ch = rotate_right( ch );
        }
      }
      else {
        for( i=0; i < -shift; i++ ) {
          ch = rotate_left( ch );
        }
      }
    
      return( ch );
    }
    
  5. int main( void )
    {
      int shift;
      int ch;
    
      printf("Enter shift: " );
      scanf( "%d", &shift );
    
      printf( "Enter Text:" );
    
      while(( ch = getchar()) != EOF ) {
        putchar( encode( ch, shift ));
      }
    
      return 0;
    }