Showing posts with label Statements. Show all posts
Showing posts with label Statements. Show all posts

Sunday, January 8, 2012

Writing Conditional and Loop Statements

By default, statements are executed once in sequence, beginning with the first statement of main() . In the
preceding section, we had a peek at the if statement. The if statement allows us to execute conditionally
one or a sequence of statements based on the truth evaluation of an expression. An optional else clause
allows us to test multiple truth conditions. A looping st atement allows us to repeat one or a sequence of
statements based on the truth evaluation of an expression. The following pseudo-code program makes use
of two looping statements ( #1 and #2), one if statement ( #5), one if-else statement ( #3), and a
second conditional statement called a switch statement ( #4).

The condition expression of the if statement must be within parentheses. If it is true, the statement
immediately following the if statement is executed:

If multiple statements must be executed, they must be enclosed in curly braces following the if statement
(this is called a statement block):
Running Codes
// Pseudo code: General logic of our program
while the user wants to guess a sequence
{ #1
display the sequence
while the guess is not correct and
the user wants to guess again
{ #2
read guess
increment number-of-tries count
if the guess is correct
{ #3
increment correct-guess count
set got_it to true
} else {
express regret that the user has guessed wrong
generate a different response based on the
current number of guesses by the user // #4
ask the user if she wants to guess again
read response
if user says no // #5
set go_for_it to false
}
}
}


// #5
if (usr_rsp == 'N' || usr_rsp == 'n')
go_for_it = false;


//#3
if (usr_guess == next_elem)
{ // begins statement block
num_right++;
got_it = true;
} // ends statement block