ch3-Guess (while, do-while statements)
Chapter_3 Exercise_3-1 Ifthen | Charlist Exercise_3-2 |
CONTENTS: Guess1.cpp Guess2.cpp
Guess1.cpp download
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int secret = 15;
int guess = 0; // initial value needed for the first test within while()
// "!=" is the "not-equal" conditional:
while(guess != secret) // Compound statement, no semicolon here
{
cout << "Guess the number: ";
cin >> guess; // type a number and press Enter, which goes to next line
}
cout << "You guessed it!" << endl; // newline added here
return 0;
}
/*
g++ Guess1.cpp -o Guess1
./Guess1
Guess the number: 0
Guess the number: 12
Guess the number: 15
You guessed it!
*/
Guess2.cpp download
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int secret = 15;
int guess; // No initialization needed here
do
{
cout << "Guess the number: ";
cin >> guess; // Initialization happens here (no newline, press Enter)
// the code is easier to read with this empty line here
} while (guess != secret); // semicolon required here
cout << "You guessed it!" << endl; // newline added here
return 0;
}
/*
g++ Guess2.cpp -o Guess2
./Guess2
Guess the number: 0
Guess the number: 12
Guess the number: 15
You guessed it!
*/
Chapter_3 Exercise_3-1 Ifthen | BACK_TO_TOP | Charlist Exercise_3-2 |
Comments
Post a Comment