0

I need to create a pseudo code that will prompt for time in 24 hours format, convert it to 12-hour format and also whether it is AM or PM. It will have to repeat until sentinel time of 9999 is entered. Below is what I had come out with, is it correct?

  1. Prompt for time
  2. Get time
  3. Enter this loop:

    DOWHILE (time != 9999)
    

    IF (time < 0000 OR time > 2400 OR (time%100 >=60))

    Display 'Invalid time'
    

    ELSE

    IF (time >= 1200 AND time <= 2400 )

        format  = 'pm'
        hours = (time/100) - 12
        mins = time%100
        Display 'The new time is ', hours, '.', mins, format 
    

    ELSE format = 'am'

    IF (time/100 = 00 )
        hours = (time/100) + 12
        mins = time%100
        Display 'The time is ', hours, '.', mins, format 
    
    ELSE
    
        hours = time/100
        mins = time%100
        Display ' 'The time is ', hours, '.', mins, format 
    
    ENDIF
    

    ENDIF

    ENDIF

    ENDO

user3296827
  • 1
  • 2
  • 3
  • Your code is clearly wrong. Given 1300, the answer should be 1.00 PM but your algorithm will print 13.00 PM. Remember that 12.59 PM is 2 minutes before 1.01 PM; this complicates life. – Jonathan Leffler Mar 21 '14 at 05:02
  • To check if it's correct, simply work out what the result will be for a few input values. To *get* the correct algorithm, similarly take a few input values with their output values, and determine the steps to go from the one to the other, then generalize it. – Bernhard Barker Mar 21 '14 at 05:12

1 Answers1

0

In Perl:

#!/usr/bin/env perl
use strict;
use warnings;

sub time_12h_to_24h
{
    my($t12) = @_;
    my($hh,$mm,$ampm) = $t12 =~ m/^(\d\d?):(\d\d?)\s*([AP]M?)/i;
    $hh = ($hh % 12) + (($ampm =~ m/AM?/i) ? 0 : 12);
    return sprintf("%.2d:%.2d", $hh, $mm);
}

sub time_24h_to_12h
{
    my($t24) = @_;
    my($hh,$mm) = $t24 =~ m/^(\d\d?):(\d\d?)/;
    my($ampm) = ($hh <12) ? "am" : "pm";
    $hh %= 12;
    $hh += 12 if $hh == 0;
    return sprintf("%d:%.2d %s", $hh, $mm, $ampm);
}

while (<>)
{
    chomp;
    my($input, $entry) = split / - /;
    my $time_24h = time_12h_to_24h($input);
    my $time_12h = time_24h_to_12h($time_24h);
    print "$input - $time_24h : $time_12h - $entry\n";
    #printf "%8s - %5s : %8s - %s\n", $input, $time_24h, $time_12h, $entry;
}

Sample data:

12:00 AM - 0000
12:01 AM - 0001
12:59 AM - 0059
01:00 AM - 0100
11:00 AM - 1100
11:59 AM - 1159
12:00 PM - 1200
12:59 PM - 1259
01:00 PM - 1300
11:59 PM - 2359
12:00 AM - 2400

Sample output:

12:00 AM - 00:00 : 12:00 am - 0000
12:01 AM - 00:01 : 12:01 am - 0001
12:59 AM - 00:59 : 12:59 am - 0059
01:00 AM - 01:00 : 1:00 am - 0100
11:00 AM - 11:00 : 11:00 am - 1100
11:59 AM - 11:59 : 11:59 am - 1159
12:00 PM - 12:00 : 12:00 pm - 1200
12:59 PM - 12:59 : 12:59 pm - 1259
01:00 PM - 13:00 : 1:00 pm - 1300
11:59 PM - 23:59 : 11:59 pm - 2359
12:00 AM - 00:00 : 12:00 am - 2400
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278