![]() |
C/C++, KDEVELOP |
|---|
BasicsProgram FlowFunctionsClasses and ObjectsX WindowKDevelop----------------- © Alfred Nussbaumer Updated: 09 December 2021 ----------------- |
LoopsThe For-StatementThe for-statement is one of the most used statements in C++ (and in other languages ;-)). It is used, when a loop has a well known number of repetitions. The general form is: for (expression1; condition; expression2) {
statement1;
statement2;
...
}
Example: #include <iostream.h>
#define NUMBER 10
float values[NUMBER];
int input_numbers();
float output_average();
int main() {
input_numbers();
cout << endl << "Average: " << output_average() << endl;
}
int input_numbers() {
for (int i=0; i<NUMBER; i++) {
cout << "(" << i << ") number: ";
cin >> values[i];
}
return 0;
}
float output_average() {
float sum = 0;
for (int i=0; i<NUMBER; i++) {
sum += values[i];
cout << ".";
}
return sum/NUMBER;
}
toc
The While-StatementThe last example enables you to put in 10 numbers - exactly 10 numbers. When the number of inputs is unknown you would prefer to use a while-statement... The general form ist: while (condition) {
statement1;
statement2;
...
}
The following example shows how to calculate the average of input numbers. The "while"-loop terminates when the input is 0 or when the array is full (see "break"-statement). #include <iostream.h>
#define NUMBER 100
float values[NUMBER];
int input_numbers();
float output_average();
int main() {
input_numbers();
cout << endl << "Average: " << output_average() << endl;
}
int input_numbers() {
int i=0;
int n=1;
cout << "0 ... Exit" << endl;
while (n!=0) {
cout << "(" << i << ") value: ";
cin >> n;
values[i]=n;
i++;
if (i > NUMBER) break;
}
return 0;
}
float output_average() {
float sum = 0;
int i=0;
while (values[i]!=0) {
sum+=values[i];
cout << ".";
i++;
}
return sum/i;
}
Here is a sample run: 0 ... Exit (0) value: 3 (1) value: 3 (2) value: 2 (3) value: 1 (4) value: 0 .... Average: 2.25toc The Do-While-StatementThe statements will be executed while the condition is true - the condition evaluates after all statements have been executed (compare that with the "while"-statement). The general form is: do {
statement1;
statement2;
...
} while (condition);
toc
Break and ContinueThe "break"-statement is used to interrupt a "for"-, "while"- or "do-while"-loop (for example that would be necessary if an error inside the loop has been detected). The general form is: if (condition) break; The "continue"-statement forces the loop to start the next iteration. if (condition) continue;toc |