C Programming: How To Do A ‘For’ Loop

In the C programming language, a ‘for’ loop allows you to repeatedly execute the code you put inside it until a specified condition is met. For example: Printing ‘Hello world’ until the variable i = 10. This would print hello world ten times.

Here’s an example of a ‘for’ loop in C:

Structure of a ‘for’ loop in C:
for (initialize; condition; increment) { //Code you want to repeatedly execute goes here }
‘Initialize’ just initializes the variable you’re incrementing. For example, ‘i’ could be initialized to ‘0’ so that it starts from 0 and you can increment until it reaches 10 or whichever number you need, as shown below. You can also initialize it from (which makes it start incrementing from) 1, 2, or any other number.

for (i = 0; i < 10; i++) { }

How To Determine The Length Of An Array You’re Looping Through In C

To determine the length of an array you’re looping through so that you can stop the loop at the final element, you can use the following sizeof function as shown below, and the length of the array (number of members in the array) will be stored in ‘arrsize’. So instead of ‘i < 10;’, you could do something like this: ‘i < arrsize;’ if you don’t know what the length of the array will be.

size_t arrsize = sizeof(yourarray) / sizeof(yourarray[0]);