Some problems require that a set of statements be executed a number of times each time changing the values of one or more variables so that every new execution in is different from the previous one this kind of repetitive execution of a set of the statement in a program is known as loop
we can categorize loop structure into two categories
- non-deterministic loops
- deterministic loop
when the number of times the loaf is to be executed is not known then the loop is called a non-deterministic loop otherwise it is called a deterministic loop
C++ force while do-while and for loop constructs to help operative executions of a compound statement in a program the while and do-while loops are not deterministic groups and the following is a deterministic loop
The while loop
it is the fundamental conditional repetitive control structure in C and C++.The general fform of this construct is given below:
while<cond> statement;
Where while is a reserved word of c++ ; <cond>is a boolean expression ; statement can be a simple or compount statment;
The sequence of operation in a while loop is as follows:
- Test the Statement.
- If the condition is true than execute the statement and repeat step 1
- if the condition is false leave the loop and go on with the rest of the program
- it performs a pre test before the body of the loop is allowed to execute
Example
Write a program that computes the factorial of a number N
solution
using namespace std;
int main()
{
int N;
int fact;
cout<<"Enter the number";
cin>>N;
fact = N;
while(N>1)
{
N=N-1;
fact = fact *1;
}
cout<<"The factorial of"<<N<<"is=<<fact;
}
0 Comments