You are here:

C++/logic question

Advertisement


Question
QUESTION: Hi,

I have a C++ Question to ask:

in the program   int next = 2, product =1;
   while (next <= 5)
{
   next++;
   product = product * next;
}

cout << "The product of 2 through 5 is " << product << endl;


there seems to be a logical error, but I can't find it?

The answer should be 120, but the output is 360?

ANSWER: With

int next = 2, product = 1 ;
while( next <= 5 )
{
       next++;
       product = product * next;
}

product will be 3*4*5*6 or 360.


With

int next = 2, product = 1 ;
while( next <= 5 )
{
       product = product * next;
       next++;
}

product will be 2*3*4*5 or 120.



---------- FOLLOW-UP ----------

QUESTION: Hi Mr. Vijayan,

I have to convert this 'for' loop into a 'while' loop and add any variable initialisations that would make it work:

for (int i = 1; i <= n; i++)

if (i < 5 && i != 2)
cout <<

   cout << 'X';

I am struggeling becuase of the 'if'

any help will be appreciated!

Answer
for loop:  for( initialization ; condition ; increment ) { body-of-for-loop }

equivalent while loop:  initialization ; while( condition ) { body-of-for-loop ; increment ; }


for( int i = 1 ; i < n ; ++i )
{
       if( i<5 && i != 2 ) cout << 'x' ;
}


int i = 1 ;

while( i < n )
{
       if( i<5 && i != 2 ) cout << 'x' ;
       ++i ;
}

See: http://en.wikipedia.org/wiki/For_loop#Equivalence_with_while_loops

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.