Page 279 - Computer_Science_F5
P. 279
Computer Science The following C++ Program Example 4.24 finds Greatest Common Factor (GCF) of
two numbers. The output is shown in Figure 4.47.
Program Example 4.24:
FOR ONLINE READING ONLY
Finding the Greatest Common Factor (GCF) of two numbers
#include<iostream>
using namespace std;
int main()
{
int n1, n2;
cout<<”Enter first number: “;
cin>>n1;
cout<<”Enter second number: “;
cin>>n2;
int gcf=1, x=2;
while(x<=n1&&x<=n2)
{
if(n1%x==0&&n2%x==0)
gcf=x;
x++;
}
cout<<”The greatest common factor (GCF) for “<<n1<<” and
“<<n2<<” is “<<gcf;
return 0;
}
Output:
Figure 4.47: Output of the program
Do-while loop
The do-while loop allows the execution of the statement at least once, and then,
evaluates the loop. If the loop condition is true, the execution continues until the
condition becomes false. The do-while loop terminates when the loop condition
is not met. It is useful where the loop body needs to be executed before the loop
270
for Advanced Secondary Schools
Computer Science Form 5.indd 270 23/07/2024 12:34

