You'll never grok loops until you write a few bad ones, so write a fragment that:
- ...adds all the numbers from 1 to n inclusive, where n is a variable or a parameter that can be set to any number >= 1.
/* One solution (assume n has been set): */ int count = 1; int total = 0; while (count <= n) { total = total + count; count = count + 1; }- ...prints all the multiples of 3 between 0 and 20, inclusive.
/* One solution: */ int current = 0; while (current <= 20) { if (current % 3 == 0) { printf("%d ", count); } current = current + 1; } /* Another one that runs a little faster... */ int current = 0; while (current * 3 <= 20) { printf("%d ", current * 3); current = current + 1; } /* A third solution, perhaps the most elegant */ int current = 0; while (current <= 20) { printf("%d ", current); current = current + 3; }- ...prints an empty box of characters:
******************* * * * * *******************of height h and width w./* Once again, there are several ways. Here's mine (BTW I'm deliberately showing off a different indent style): */ int row_num = 1; int col_num; /* We want to print h rows... */ while (row_num <= h) { /* For each row, we start over at column number 1 */ col_num = 1; /* For first and last lines, print a full row of stars */ if (row_num == 1 || row_num == h) { while (col_num <= w) { printf("*"); col_num = col_num + 1; } } else /* For all the other rows, print something different: */ { /* Print first star and advance colum */ printf("*"); /* Now print h - 2 spaces */ while (col_num <= h - 2) { printf(" "); col_num = col_num + 1; } /* Print last star */ printf("*"); /* Opening star */ } /* Print newline and advance to next row. */ printf("\n"); row_num = row_num + 1; }- ...prints the Fibonacci sequence 1, 1, 2, 3, 5, 8..., asking the user if (s)he wants another number after each iteration. Use 0 for no, 1 for yes.
/* Faking a boolean type for convenience & readability */ #define TRUE 1 #define FALSE 0 /* We'll use these to keep a running total. */ int current = 1, last = 0; /* Initially, we want to continue. */ int continue = TRUE; while (continue == TRUE) { /* Print the current fibonacci number. */ printf("current: %d\n", current); /* Add the previous number to get the next in the sequence, and save the current number in last for next time. */ current = current + last; last = current; /* Ask the user if (s)he wants to continue. */ printf("Enter 1 to continue, 0 to quit: "); scanf("%d", &continue); }