UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

repeat-n-times

The C for loop

for (i = 0; i < n; i++)
{
    ...statements...
}

Printing a message 10 times

The Program /* File: do_ten.c Print a message ten times. */ #include <stdio.h> main() { int i ; /* Repeat 10 times */ for (i = 0 ; i < 10 ; i++) { printf("I will not chew gum in class.\n") ; } } and the sample run. lassie% cc do_ten.c lassie% lassie% a.out I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. I will not chew gum in class. lassie%

Printing a message 10 times with numbers

The Program /* File: numbered.c Print a message ten times indexed by a number. */ #include <stdio.h> main() { int i; /* Repeat 10 times */ for (i = 0; i < 10; i++) { printf("%d) I will not chew gum in class.\n", i); } } and the sample run. lassie% cc numbered.c lassie% lassie% a.out 0) I will not chew gum in class. 1) I will not chew gum in class. 2) I will not chew gum in class. 3) I will not chew gum in class. 4) I will not chew gum in class. 5) I will not chew gum in class. 6) I will not chew gum in class. 7) I will not chew gum in class. 8) I will not chew gum in class. 9) I will not chew gum in class. lassie%

Adding a list of 10 numbers

The Program /* * File: add10.c * ------------- * This program adds a list of ten numbers, printing * the total at the end. Instead of reading the numbers * into separate variables, this program reads in each * number and adds it to a running total. */ #include <stdio.h> main() { int i, value, total; /* Print description for user */ printf("This program adds a list of 10 numbers.\n"); /* Initialize total */ total = 0; /* Get 10 integers from the user, adding each to total */ for (i = 0; i < 10; i++) { printf("Enter an integer : "); scanf ("%d", &value); total += value; } /* Print the result */ printf("The total is %d\n", total); } and the sample run. lassie% cc add10.c lassie% lassie% a.out This program adds a list of 10 numbers. Enter an integer : 1 Enter an integer : 2 Enter an integer : 3 Enter an integer : 8 Enter an integer : 21 Enter an integer : 22 Enter an integer : 1 Enter an integer : 17 Enter an integer : 19 Enter an integer : 20 The total is 114 lassie%


CSEE | 201 | 201 F'98 | lectures | news | help

Saturday, 12-Sep-1998 16:33:26 EDT