The syntax for a for loop is:
for (initialization; condition; increase) {
statement;
}
for example:
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << arr[i] << endl;
// you can do alot more in a for loop than just print to console
}
while loop syntax
while (condition) {
// statements
}
example:
int i = 0;
// the loop will end when i = 5
// unlike for loop you must increment variables yourself or
// use the break command to exit the loop
while (i != 5) {
cout << i << endl;
i++;
}
Chat with our AI personalities
Example in Java: int total = 0; int i = 1 while (i <= 10) { total += i; i++; } System.out.println("The sum of the first ten numbers is " + total);
The idea is to use a loop. To reduce the additional effort (and innacuracy) of power calculations, you can do repeated multiplication, as part of the loop. For example, in Java:double sum = 1;double xpower = 1.0;for (int i = 1; i
Plus, country code, area code, number For example: +1 555 1234567
Although both can achieve very similar loops, the one you use for a specific loop usually comes down to whichever seems more intuitive to you. In terms of performance, one method may be slightly more efficient than the other, however there are no general rules that can be applied; you must test each case by comparing the machine code or by physically timing the loops with a high performance event timer (HPET). In my experience, the performance difference is so negligible it is not worth the effort. Background activity has a far greater impact on performance.Describing the differences between every possible loop you might create would take me a lifetime, but there are a couple of subtle differences that are worth pointing out.Infinite Loopsfor(;;){} // infinite for loops do not require a condition.while( true ){} // infinite while loops MUST have a condition.To break out of an infinite loop you must test for one or more conditions within the loop itself, and call break to exit the loop when a condition is met. You can also call continue to start the next iteration before reaching the end of the current iteration.Stepping LoopsWhen stepping through a series of values, the for() loop is usually the better choice, especially if the step must occur AFTER each iteration. Consider the following similar loops:for( int x=0; x
Indenting is a good habit to inculcate while writing any type of code Although indentation is not mandatory and will never affect the working of your programme in C++ it makes the code more easy to read and debug especially for larger programmes. Most IDE's eg eclipse automatically indent the code as you type.