WAP to input time in millisecond and show in minuts and second
Objective
Write a C++ program to convert milliseconds into minutes and seconds.
Algorithm / Approach
- Read total milliseconds into
tms. - Convert total milliseconds to total seconds by dividing by 1000:
ts = tms / 1000. - Extract the total minutes by dividing the total seconds by 60:
tm = ts / 60. - Extract the leftover remaining seconds using the modulo operator:
ts = ts % 60. - Print the formatted time.
main.cpp
#include<iostream>
using namespace std;
int main() {
int tms, ts, tm;
cout<<"Enter Time in millis: ";
cin>>tms;
ts = tms/1000;
tm = ts/60;
ts = ts%60;
cout<<"Time- "<< tm<<":"<< ts;
return 0;
}
Expected Output
Enter Time in millis: 72014 Time- 1:12
Explanation of the Program
- This program uses a combination of integer division and the modulo operator (
%). - Integer division (
/) tells you exactly how many full units fit into a number (e.g., how many full minutes are in 75 seconds? 1). - The modulo operator (
%) tells you exactly what is leftover (e.g., 75 seconds modulo 60 is 15 leftover seconds).
Complexity
Time Complexity
O(1)
Space Complexity
O(1)