Welcome to our comprehensive guide on the continue statement in C programming! This statement is a powerful tool that helps you control the flow of your program. Let's dive in and learn together!
The continue statement is used in loops to skip the remaining code in the current iteration and move directly to the next iteration. It's a useful way to bypass certain conditions without exiting the loop entirely.
for(int i = 0; i < 10; i++) {
if(i == 5) continue;
// Skipped if i is 5, otherwise executed
printf("i is: %d\n", i);
}In the above example, when i equals 5, the printf statement is skipped, and we move directly to the next iteration.
for(int i = 0; i < MAX_LINE_LENGTH; i++) {
if(file[i] == '\n' || file[i] == '\0') continue;
// Process non-empty lines
}continue can help optimize your loops, making them more efficient by reducing unnecessary computations.What does the `continue` statement do in a loop?
Let's use the continue statement to create a simple program that removes duplicates from an array.
#include <stdio.h>
void removeDuplicates(int arr[], int size) {
for(int i = 0; i < size; i++) {
for(int j = i + 1; j < size; j++) {
if(arr[i] == arr[j]) continue;
// Skipped if duplicate found, otherwise executed
printf("arr[%d] = %d\n", i, arr[i]);
}
}
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
removeDuplicates(arr, size);
return 0;
}In this example, we define a function removeDuplicates that removes duplicates from an array. It does this by iterating through the array and using the continue statement to skip duplicates. The main function initializes an array with duplicates, calls the removeDuplicates function, and prints the resulting unique array.
That's all for now! Keep practicing, and remember to use the continue statement wisely to make your code cleaner and more efficient. Happy coding! 🚀