0

Hello. I have an exercisse to convert from 24-hour to 12-hour clock. code:

/*ALGORITHM
READ INPUT VALUE IN 24-HOUR FORMAT
DISPLAY THE EQUIVALENT 12-HOUR CLOCK WITH THE PERIODS AM OR PM
*/

#include<stdio.h>
#include<conio.h>

int InputValid24Hour(void);
void Output12HourClock(int);

void main() {
    int data;

    data = InputValid24Hour();
    Output12HourClock(data);
    _getch();
}

int InputValid24Hour(void) {
    int input24hour;
    int First2Digit, Last2Digit;

    printf("Enter time in 24-hour format: \r\n"); //ask for input

    do {
        scanf_s("%d", &input24hour); //read input

        First2Digit = input24hour / 100; //get first 2 digits
        Last2Digit = input24hour % 100; //get last 2 digits

        if ((First2Digit < 0) || (First2Digit > 24) || (Last2Digit >= 60))
            printf("\r\nInvalid 24-hour clock..");

    } while ((First2Digit < 0) || (First2Digit > 24) || (Last2Digit >= 60));

    return(input24hour);
}

void Output12HourClock(int i) { //int i value from InputValid24Hour() see main()
    int First, Last;

    First = i / 100;
    Last = i % 100;

    if (First > 12) {
        First = First - 12;
        printf("%02d = %02d:%02d pm\r\n", i, First, Last);
    }
    else if (First == 00) {
        First = 12;
        printf("%02d = %02d:%02d am\r\n", i, First, Last);
    }
    else {
        printf("%02d = %02d:%02d am\r\n", i, First, Last);
    }

}

Output : http://imgur.com/a/OtfJL

the problem'ss at 24, it doessn't sshow 00 when it sshould sso it sshould be 0024 = 12:24 am; how do i get 00 to be displayed?

thankss

2
Contributors
2
Replies
24
Views
8 Months
Discussion Span
Last Post by nadiam
1

In the output scenarios you use printf("%02d = %02d:%02d am\r\n", i, First, Last);
Each %02d tells the compiler you want a two-digit number with leading zeroes.
However, the first %02d in each output line should be %04d since we want a number 4-digits long with leading zeroes.
Try that instead.

Three words on coding style for beginners: (if you believe ignorance is bliss please disregard)

  1. main should always be declared as a int instead of a void. Assuming no errors, return 0; at the end is fine.
  2. getch(); and also system("pause"); at the end of a program are bad form and you'll want to break that habit early on. Put in the return value at the end of main and, once you've learned to use the debugger, set a breakpoint there. This keeps your window open until you're done with it.
  3. Using #include<conio> makes your code "non-portable" (i.e. could break this code on another C compiler on another platform) and is discouraged. Getting rid of the getch(); means you can get rid of #include<conio> .

But most importantly, good luck and have fun coding.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.