|
while ( Boolean expression )
one-statement
|
The statements in the while body MUST affect the boolean condition (or else, the while loop will never end - infinite loop....)
for ( initialization; boolean expression; update )
one-statement
|
for ( initialization; boolean expression; update )
statement
|
A is an integer array of 10 elements |
do
one-statement
while ( boolean expression )
|
do
statement
while ( boolean expression )
|
| Given 2 integer numbers a and b , find their greatest common divisor GCD |
As long as the search space is limited , the brute force search is often the best way to solve a problem with a computer.
The GCD is a number between 1 and a - test every number between 1 and a !!!
Given: a and b
for (i = 1; i <= a; i = i + 1)
if ( a divisible by i AND b divisble by i )
GCD = i;
|
#include <iostream.h>
int main()
{
int a, b, i, GCD;
a = 96;
b = 256;
GCD = 1;
for ( i = 1; i < a; i = i + 1)
{
if ( (a % i == 0) && (b % i == 0) )
{
GCD = i;
}
}
cout << GCD << endl;
}
|
How to compile and run:
Compile: CC -o GCD GCD.C Run: GCD |
| Given 2 integer numbers a and b , find their least common multiple LCM |
The LCM is a number between a and a*b - but you can exit as soon as you find the first one.
Given: a and b i = a; while ( i not divisible by a OR i not divisible by b ) i = i + 1; // Try next number LCM = i; |
#include <iostream.h>
int main()
{
int a, b, i, LCM;
a = 96;
b = 256;
i = a; // First number to try
while ( (i % a != 0) || (i % b != 0) )
{
i = i + 1; // Try next number...
}
LCM = i;
cout << LCM << endl;
}
|
How to compile and run:
Compile: CC -o LCM LCM.C Run: LCM |