[SOLVED] countdown loop problem in c

Status
Not open for further replies.

adrian.eremencu

Newbie level 3
Joined
May 25, 2013
Messages
4
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Visit site
Activity points
1,356
Hi,
I have a problem with the following loop in C. It's a countdown for 4 digits(mm:ss).


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void countdown(void)  // the countdown
{
  while ( min2 >= 0)
  { 
    while (min1 >= 0)
    {
      while (sec2 >= 0)
      {
    while ( sec1 >=0)
    {
      sec1--;
      delay_1s();
    }
    sec1 = 9;
    sec2--;
    }
    sec2 = 5;
    sec2--;
  }
  min1 = 9;
  min2--;
 }
}



For example: if i have the values 15:30 (mm:ss) it decreases the sec2 val until is less than 0, then the value of sec2 is changed to 9 and sec1 is decreased by 1, and this process continues until all digits are = 0. The countdown works but when it reaches 00:00 it doesn't stop.
 

Depending on unsigned/signed variable type, countdown will either never stop (>=0 is always true for an unsigned number) or stop when reaching negative values. That's how you wrote the code.
 
Reactions: tpetar

    tpetar

    Points: 2
    Helpful Answer Positive Rating
I used signed var. But i think i know why it doesn't stop.
Let's say that i have 00:02. The procces will be the following:
00:02
00:01
00:00 and then when the sec1 is lower than 0 it exits the loop and automatically becomes 9, the sec2 becomes 5 and the min1 becomes 9 and in my main before i call this function i have while ( (min2 != 0) || (min1 != 0) || (sec2 != 0) || (sec1 != 0)), therefore the loop begins again. I will change the while loop in my main with an if statement and that should solve my problem.

- - - Updated - - -

It works now. Thank you for the support.
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…