نشرت - خميس, 03 نوفمبر 2022
You’re building a C program. You want to iterate through the code multiple times, but you don’t want to just copy and paste it. What can you do to keep your code as condensed and maintainable as possible while still running it multiple times?
C has several functions intended to iterate through code. They’re called “looping” statements. The most popular of these loops are the for() loop and the while() loop.
A for() loop is a chunk of code that will run as long as its parameters are still true. The design of a for() loop is such that it begins with a single proposition (such as count = 1) and then continues to loop until a condition is met (such as count = 25). While the loop continues, a certain action is taken (such as incrementing the count by 1).
Every programmer needs to understand the logic between a for() loop — and a for() loop operates almost identically in nearly every language. For() loops are one of the most basic and essential forms of programming logic, perhaps second only to the if/then syntax.
For() loops are a staple of any complex coding language. Rather than having to repeat your code over and over, you can instead use a loop. When it comes to programming, there’s always an advantage to being able to simplify code. When you have a single for() loop, you only need to edit the code within the loop rather than edit multiple copies of code.
You can use a for() loop to:
But you don’t always need a for() loop for this. You can also use different types of loop, such as while() or do() while(). There are also functions — such as switch() — that you can use to create something similar to a for() loop.
for ([expression]) {
[statement]
}
The best way to understand a for() loop is to dissect it. At first, a for() loop looks very complicated — but that’s just because it’s structurally abstract and dense. In reality, a for() loop is extremely simple.
Let’s start with an example. This example is meant to iterate through a variable num, executing a single chunk of code a certain number of times.
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i) {
printf(“%d \n“, i);
}
}
In the loop statement, we declare an int i. We then call the for() loop with the following:
i = 1; | This clause sets the int i to equal one when the loop first starts. |
i < 11; | This clause tells the for loop to continue running until int i is no longer less than 11. |
++i; | This clause tells the for loop to increase int i by one each loop. |
In the body of the loop, it tells the program to print the integer using the printf() command. %d refers to one of many C data types.
In short, the loop will execute 10 times, printing the numbers 1 through 10. The loop terminates once the int num is no longer less than 11 (is 11 or greater). And as long as that is true, the loop will continue to execute the entire block of code inside of it.
Fri, 03 فبراير 2023
خميس, 03 نوفمبر 2022
قعد, 24 سبتمبر 2022
اكتب مراجعة عامة