/* April21.cpp */ /* CS 10051 example code, showing while and for loop equivalence */ /* Also showing the modulus function checking for odd /even values */ /* S. Steinfadt - 4/21/08 */ #include using namespace std; // Main function int main() { /*************************************************************** WHILE loop construction ***************************************************************/ int x; // Variable declaration x = 5; // Loop control variable cout << "While loop using x:\n"; while (x >= 0) // while conditon { cout << x << "\n"; x--; //x = x - 1; // Updating loop control variable } /*************************************************************** Equivalent FOR loop ***************************************************************/ cout << "****************\n"; cout << "For loop using y:\n"; // Equivalent for loop -- does same thing as the while loop // for (loop_var; loop condition; loop_var update) for(int y = 5; y >=0; y--) { cout << y << "\n"; } /*************************************************************** Use of MODULUS (%) Operator ***************************************************************/ cout << "Check for even / odd value\n"; cout << "Please enter a number: "; cin >> x; // Modulus operator will return the WHOLE number that is // the remainder of an INT division int remainder = x % 2; if (remainder == 0) cout << "The number " << x << " is even.\n"; else // don't need an "else if" here since a number is only odd OR even cout << "The number " << x << " is odd.\n"; return 0; }