Zan
Zan

Reputation: 288

Strange performance of a loop on C

I having a litte problem with a loop. I have to do a calendar. I created a procedure to print the calendar itself using data which comes from other functions (as if the year is a leap year for example). What I want is the function to write numbers up to the number of days of the month, inserting a space every week. The programm is not finished (right now it considers all the months starting by monday) but right now it prints 35 or 36 numbers. If 31 or 30 comes to be a monday or a wednesday the loop doesn't finish but it keeps writting the whole rest of the week. I expected it to end on 30 or 31 the value that month_days can have. The problem is not on that variable, when I print it it gives me a right value (30 or 31 depending on the month) What can be failing on the loop structure?

void imprimir_calendario (int mes, int anho, int month_days, int primer_dia_mes) {
  int index = 1;
  int printed_days= 1;
  printf ("\n%d\n",month_days); /*test sentence returns 30 or 31 as it should*/
  printf ("===========================\n");
  printf ("==   month & year  ==\n");
  printf ("===========================\n");
  printf ("  L   M   X   J   V   S   D\n");
  while (printed_days < month_days) {
    while (index<=7){
    printf (" %2d ",printed_days);
    printed_days++;
    index++;}
    index = 1;
    printf ("\n");}
  printf ("\n%d",printed_days);} /*TEST SENTENCE, RETURNS 35 OR 36*/

Upvotes: 0

Views: 72

Answers (1)

P.P
P.P

Reputation: 121357

Once entered, the inner loop runs 7 times ragardless of the current value of printed_days.

You probably need to check the condition and break the inner loop:

 while (index<=7) {
    printf (" %2d ",printed_days);
    printed_days++;
    index++;
    if (printed_days > month_days) break;
 }

Upvotes: 3

Related Questions