In: Computer Science
What are one advantage and one disadvantage of allowing the modification of loop variables in the loop body?
Advantage of allowing the modification of loop variables in the loop body:
To control the infinitely execution of certain loop statements.
Example:
#include <iostream>
using namespace std;
int main() {
int count=1; // Initially count is 1
while(count<=10) // Loop runs until count lessthan or equal to 10
{
cout<<count<<" "; // print count
count=count+1; // increment count everytime by 1
}
}
Output:
Dis advantage of allowing the modification of loop variables in the loop body:
Execution of certain loop statements infinitely.
Example:
#include <iostream>
using namespace std;
int main() {
int count=1; // Initially count is 1
while(count!=-1) // Loop runs until count lessthan or equal to 10
{
count=count*2; // multiply count everytime by 2
cout<<"The value of count ";
if(count%2==1) // check count is odd
{
cout<<"is odd"<<endl;
break;
}
}
}
Output:
Since the values of numbers after the count=count*2; statement are 2,4,6,8,......2n all are even numbers.
The break statement execute when the number is odd, so break statement not execute at all.
If we do not modify loop variables count in the loop body then it runs for 1 time.
Program and its output are given below
#include <iostream>
using namespace std;
int main() {
int count=1; // Initially count is 1
while(count!=-1) // Loop runs until count lessthan or equal to 10
{
count=count*2; // multiply count everytime by 2
cout<<"The value of count ";
if(count%2==1) // check count is odd
{
cout<<"is odd"<<endl;
break;
}
}
}
Output: