Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++: In the following code there is no condition in the for loop. Upto when, the

ID: 3863332 • Letter: C

Question

C++: In the following code there is no condition in the for loop. Upto when, the loop will be running? Also, if there is no else and break statement then how the code is not going to work? Explain please!

#include<iostream>

using namespace std;

int main()
{
   int sum;
   int sum1=0;
   int sum2=0;
   int multiple3, multiple5;
   for(int i=1;;i++)
   {
       multiple3=3*i;
       if(multiple3<1000)
       sum1+=multiple3;
       else
       break;
       multiple5=5*i;
       if(multiple5<1000 && multiple5%3!=0)
       sum2+=multiple5;
   }
   sum=sum1+sum2;
   cout<<sum<<endl;
   return 0;
}

Explanation / Answer

There is this condition given right ?

if(multiple3<1000)

the program is calculating the multiple of 3 and 5 from 1 to 999 except common multiples, and sum of them is stored in a variable named sum.

So above given condition is terminating the program because when i becomes 1000 in the loop the control of the program will go to else statement where break is present to terminate the loop.

if else and break statement should not have been there loop will not stop (It will run for infinite times) because then there is no terminating condition is available to terminate the loop.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote