for.c

/*
 * this demponstrates the use of for, while, and do...while loops
 * each loop prints the integers from 0 to 9; note the do ... while
 * loop can also be set up to miscount
 *
 * compile with -DBAD to get the code that counts from 1 to 10 in
 * the do...while loop; do not define it to get the code that counts
 * from 0 to 9 in that loop
 *
 * Matt Bishop, ECS 36A
 * April 9, 2024	original version
 */
#include <stdio.h>

int main(void)
{
	int i, j, k;		/* counters in various loops */


	/*
	 * for loop: count from 0 to 9 includive
	 */
	for(i = 0; i < 10; i++)
		printf("FOR: i = %d\n", i);

	/*
	 * now the while loop: note the initialization
	 * outside the loop, and the increment is ibn
	 * the loop
	 */
	j = 0;			/* initialize j */
	while(j < 10){
		printf("WHILE: j = %d\n", j);
		j = j + 1;	/* increment j by 1 */
	}

	/*
	 * do ... while loop: like the while loop
	 * and the increment comes after the printf
	 * if you put the increment before, it doesn't
	 * work right
	 */
	k = 0;			/* initialize k */
	do{
#ifdef BAD
		k = k + 1;	/* increment k by 1 -- ERROR */
#endif
		printf("DO...WHILE: k = %d\n", k);
#ifndef BAD
		k = k + 1;	/* increment k by 1 */
#endif
	}while(k < 10);

	/*
	 * Adios amigos!
	 */
	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh