Professional Documents
Culture Documents
Computer Science 1510: November 2, 2016 Lecture Outline
Computer Science 1510: November 2, 2016 Lecture Outline
Lecture 23
November 2, 2016
Lecture Outline
Repetition
CS1510 Lecture 23
Repetition
There are three types of loops in C: a while loop,
a do while loop, and a for loop.
The while loop is analogous to the DO WHILE in
Fortran, while the for loop is somewhat analogous
to the counter controlled DO loop in Fortran.
Unlike a DO loop in Fortran, which iterates for a fixed
number of iterations, all loops in C will continue to
iterate as long as their condition is true.
We will look at each of these loops in detail.
CS1510 Lecture 23
while loop
Syntax:
while (logical-expression){
statement-block;
}
where logical-expression is any valid C
expression that evaluates to an integer that can
be interpreted as true (non-zero) or false (zero).
Example:
while (x<10 && y!=5){
scanf("%d",&y);
x++;
}
CS1510 Lecture 23
#include <stdio.h>
int main (int argc, char *argv[])
{
int m,n,q,r;
printf("Please enter two integers M and N, where M>N\n");
scanf("%d %d",&m,&n);
r=1;
while (r!=0){
q=m/n;
r=m-q*n;
printf("%d = %d * %d + %d\n",m,n,q,r);
m=n;
n=r;
}
printf("The greatest common divisor is %d\n",m);
return 0;
}
CS1510 Lecture 23
CS1510 Lecture 23
for loop
Syntax:
for (start-condition; end-condition; update){
statement-block;
}
Example:
for (i=0; i<10; i++){
scanf("%d",&y);
printf("%d",y);
}
Note that the for loop begins counting at i=0.
The default in C is to count from zero since array
indices start from 0. (Fortran starts from 1).
CS1510 Lecture 23
CS1510 Lecture 23
Example: loops
Approximation of sine and cosine:
#include <stdio.h>
int main(int argc, char *argv[]){
int i,n;
double x,term,approx;
char func,junk;
printf("Enter s for sin, and c for cos or q to quit\n");
scanf("%c",&func);
while(func!=q){
printf("How many terms would you like to include?\n");
scanf("%d",&n);
printf("Enter a value for x\n");
scanf("%lf",&x);
switch (func){
case s:
term=x;
approx=x;
for(i=0;i<n-1;i++){
term=(-1)*term*(x*x/(2*(i+1)*(2*i+3)));
approx=approx+term;
}
printf("sin(%f) is approximately %f\n",x,approx);
break;
case c:
term=1;
approx=1;
for(i=0;i<n-1;i++){
term=(-1)*term*(x*x/(2*(i+1)*(2*i+1)));
CS1510 Lecture 23
approx=approx+term;
}
printf("cos(%f) is approximately %f\n",x,approx);
break;
default:
printf("Invalid entry, try again\n");
}
printf("Enter s for sin, and c for cos or q to quit\n");
scanf("%c",&junk);
scanf("%c",&func);
}
return 0;
}
CS1510 Lecture 23
do while loop
Syntax:
do{
statement-block;
} while (logical-expression);
where logical-expression is any valid C
expression that evaluates to an integer that can
be interpreted as true (non-zero) or false (zero).
Example:
do{
scanf("%d",&y);
x++;
} while (x<10 && y!=5);
In a do while loop, the first iteration is not
dependent on a condition, ie. at least one iteration
of the body of the loop is completed.
CS1510 Lecture 23
CS1510 Lecture 23
10
CS1510 Lecture 23
11
12