Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanted to create a minute and seconds countdown timer in c++. So, i tried something and it worked. But i dont know if my approach is correct and i want to be sure if i was doing it the right way. So, please can anyone comment on my code and suggest me if anything is required to be changed.
Thanks .

C++
#include <iostream>
#include <conio.h>
#include <Windows.h>

using namespace std;

int main()
{
	int m,s;
	int total;


	
	cout<<"Enter m and s"<<endl;
	cin>>m>>s;


	
		for(int sec = s; s>=0; s--)
		{
			
			cout<<"You have "<<"minutes"<<m<<"seconds"<<s<<endl;
			Sleep(200);
			
			if(s ==0)
			{
             total = m*60;

			 for(int min = total; total>=0; total--)
			 {
		 cout<<"You have the remaining seconds"<<total<<endl;
				 Sleep(200);
			 }



			}
		}

	



	 system("pause");


}
Posted

1 solution

It's kinda odd - and probably very annoying for users, but that's neither here nor there.

Look at it: what is the point of assinging s to sec? You never use sec again...
And what happens when m is 10, and s is 30?
It starts off telling the user he has 10 mins and 30, 10 and 29, ...10 and 1.
Then it launches into 600 seconds, 599 seconds,...
Well - almost, it doesn't count in seconds at all - 200 is not a second, it's 2/10ths of a second.

I would do it differently:
Read in the minutes and seconds.
Generate a "total" in seconds.
Loop until the total is zero.
In the loop, convert the current total into minutes and seconds and print it.

In fact what I'd do is take the current date and time, add the offset and set that as the target time. I'd then read the current time in the loop and compare that to the target - this allows for system events outside the application which slow the progress by suspending the app. But that's probably a little advanced for a beginner!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900