100 likes | 298 Views
LOOP & Type Conversion. do – while Loop. In the while loop, the test expression is evaluated at the beginning of the loop. If the test condition is false when the loop is entered, the loop body won’t be executed at all.
E N D
do – while Loop • In the while loop, the test expression is evaluated at the beginning of the loop. If the test condition is false when the loop is entered, the loop body won’t be executed at all. • Sometime we want that loop body should execute at least once, no matter what the initial state of the test expression. • In this case, you should use the do-while loop, which places the test expression at the end of the loop.
do – while Loop do { statement 1; statement 2; . . . statement n; }while ( test expression );
do – while Loop Example void main ( ) { long dividend, divisor; char ch; do { cout <<“Enter dividend:”; cin>> dividend; cout<<“Enter divisor:” ; cin>> divisor; cout<<“Qoutient is”<<dividend / divisor; cout<<“Remainder = ”<<dividend % divisor; cout<<“Do another? (y/n):”; cin>>ch; }while ( ch != ‘n’ ) ; }
Integer and Float Conversion • In order to effectively develop C++ Program, it is necessary to understand the rules that are used for implicit conversion of floating point and integer values in C++. • These three rules are • An arithmetic operation between an integer and integer always yields an integer result. • Operation between a real and real always yields a real result • Operation between an integer and real always yields a real result.
Type Conversion In Assignment • In some Cases, it may happen that the type of the expression on the right hand side and the type of the variable on the left hand side of the assignment operator may not be same. • In that case the value of the expression is promoted or demoted depending on the type of the variable on left hand side of assignment operator.
Type Conversion in Assignments • Example int i; float y; i = 35.9; y = 10; • As 35.9 is of float type it cannot be stored in i of int type. In this case float is demoted to an int and then value is stored in i. So the value of i will be 35. • Same will happen in y i.e. 10 will be promoted to 10.00 and then will be stored in y.
Type Conversion in Assignment float a=1.0, b = 2.0, c = 10.0; int s; s = a * b * c / 100 + 32 / 4 – 3 * 1.1; • In the above example, some of the operands are of type int and some of them are of type float. As we know during evaluation of the expression int will be promoted to float and result would be of type float. But when this float value is assigned to s, it is again demoted to an int and then stored in s.