C continue Statement 🎯

beginner
9 min

C continue Statement 🎯

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!

Understanding the continue Statement 📝

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.

c
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.

When to use continue 💡

  1. Skipping iterations based on specific conditions: You might want to skip some iterations based on certain conditions. For example, if you're reading a file and want to skip empty lines.
c
for(int i = 0; i < MAX_LINE_LENGTH; i++) { if(file[i] == '\n' || file[i] == '\0') continue; // Process non-empty lines }
  1. Optimizing loops: Using continue can help optimize your loops, making them more efficient by reducing unnecessary computations.

Quiz 📝

Quick Quiz
Question 1 of 1

What does the `continue` statement do in a loop?

Practical Application 💡

Let's use the continue statement to create a simple program that removes duplicates from an array.

c
#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! 🚀

  • The CodeYourCraft Team 💬