Strutture di controllo
Il ciclo while
Il ciclo while
ripete un statement piu' volte, ma solo finché la condizione specificata rimane vera (true). Il ciclo while
ha questa forma:
while(<boolean-expression>)
<statement>
Siccome lo statement può essere un blocco, la maggior parte dei cicli while
hanno la forma:
while(<boolean-expression>) {
statements
}
Qui un semplice esempio di ciclo while
che stampa i numeri 1, 2, 3, 4, 5:
int number; // The number to be printed.
number = 1; // Start with 1.
while ( number < 6 ) { // Keep going as long as number is < 6.
out << number << endl;
number = number + 1; // Go on to the next number.
}
out << "Done!" << endl;
<METTI ESEPIO SU CALCOLO INTERESSI>
If statement
Un if
statement dice al computer di prendere una delle due alternative, in base al valore di una true o false di una certa condizione. Un if
statement ha la forma:
if ( boolean-expression )
statement1
else
statement2
Molte volte noi vogliamo che il computer scelga tra fare una cosa o non farla. Si può fare così, con un if
statement che omette la parte else:
if ( boolean-expression )
statement
Alcune volte, i nuovi programmatori confondono il ciclo while
con il semplice if
, sebbene il loro significato è piuttosto differente. l'if statement è eseguito al piu' una volte, mentre lo statement while
può essere eseguito anche molte volte.
Può essere utile vedere il diagramma del flusso di esecuzione di un ciclo while
e di un if
:

Il flusso di controllo di un if ... else
statement rende chiaro che solo uno dei due statement innestati è eseguito:

Naturalmente, uno o entrambi gli statement nell'if
possono essere dei blocchi. Così un if
statement spesso è così:
if ( boolean-expression ) {
statements
}
else {
statements
}
oppure:
if ( boolean-expression ) {
statements
}
Esempio:
if ( x > y ) {
int temp; // A temporary variable for use in this block.
temp = x; // Save a copy of the value of x in temp.
x = y; // Copy the value of y into x.
y = temp; // Copy the value of temp into y.
}
Last updated