For Loops Solution


#include <stdio.h>

main() {
  int i, j;

  /* Print numbers from 1 through 10 by 1. */

  for(i = 1; i < 11; i++) printf("%d ", i);
  printf("\n");

  /* Print numbers from 10 through 1 by -1. */

  for(i = 10; i > 0; i--) printf("%d ", i);
  printf("\n");

  /* Print numbers from 0 through 20 by 2. */

  for(i = 0; i < 21; i = i + 2) printf("%d ", i);
  printf("\n");

  /* Print varying rows of *. */

  for(i = 1; i < 11; i++) {
    for (j = 0; j < i; j++)
      printf("*");
    printf("\n");
  }
}

Discussion


int i, j; We can declare more than one variable in the same statement.
/* Print numbers from 1 through 10 by 1. */
Comments are enclosed in /*  ...  */ pairs.
for(i = 1; i < 11; i++) printf("%d ", i); Print the numbers from 1 to 10. Note the space after the %d to separate the numbers.
printf("\n"); Prints a new line so that the next set starts on the next line.
for(i = 0; i < 21; i = i + 2) printf("%d ", i); This skips by 2 instead of by 1.
for(i = 1; i < 11; i++) { This sets up a counter from 1 to 10.
for (j = 0; j < i; j++) This is a nested for loop. The inner loops prints i *s. Since i goes from 1 to 10, it will print the first row with one *, the second with two *, etc.
printf("\n"); We need this to break the line. If it weren't here, all of the * would run into each other.



Return to Homepage    Return to Programming Pages
Updated November 24, 2005. For comments and questions, send email to Vector.x64 @ gmail.com (without the spaces).