Tom Kelliher, CS 116
Nov. 29, 2000
Return exams on Friday.
Read 8.2.
Lab 6.
while loops.
for loops.
Arrays.
Example: summation.
while (<condition>) statement;How do we achieve a multi-statement loop body?
int input;
int sum = 0;
input = getNextInput();
while (input != 0)
{
sum += input;
input = getNextInput();
}
int digitCount(int n)
{
int count = 0;
if (n == 0)
return 1;
while (n != 0)
{
++count;
n /= 10;
}
return count;
}
while (true) statement;
for (<initialization>; <condition>; <update>) statement;
int count; int sum = 0; int i; count = getNextInput(); for (i = 0; i < count; ++i) sum += getNextInput();
.
int summation(int n)
{
int sum = 0;
int i;
for (i = 0; i <= n; ++i)
sum += i;
return sum;
}
n.
int evenSummation(int n)
{
int sum = 0;
int i;
for (i = 0; i <= n; i += 2)
sum += i;
return sum;
}
Complete the bodies of the following methods:
using a for loop:
double pow(double x, int n)
{
// ...
}
. (
, by definition). Use a
while loop.
int fact(int n)
{
// ...
}
Yes, loops can be nested, like ifs.
How many times is statement executed in each of the following:
int i;
int j;
for (i = 0; i < 5; ++i)
for (j = 0; j < 5; ++j)
statement;
int i;
int j;
for (i = 0; i < 5; ++i)
for (j = i; j < 5; ++j)
statement;