You are here:

- Home
- Computing/Technology
- C/C++
- C++
- logic question

Advertisement

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!

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

- Add to this Answer
- Ask a Question

Rating(1-10) | Knowledgeability = 10 | Clarity of Response = 10 | Politeness = 10 |

Comment | You are great! |

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.

about 15 years or so**Education/Credentials**

post graduate engineer