Adding Loops To Our C Programming Toolbox

Share This Post

Why Should We Use Loops?

Loops are great tools we use to iterate over a well-known range of numbers. For instance, if we wanted to count from 0 to 100, why should we type out each number when the operation is quite predictable?

Using a simple loop, we can do this operation in C like so:

int num_stop = 100;
int i = 0;

while (i < 100)
{
printf("%d\n", ++i);
}

Looping

There are 3 different style of loops we can use in C. While they all have slightly different syntax, they each have a looping condition, iterating variable and looping block. Let’s go over the simplest one, the while loop.

while()

#include <stdio.h>

int main(void)
{
   int counter = 0;
   while (counter < 10)
   {
      printf("counter: %d\n", counter);
      counter++;
   }

   return 0;
}

This program starts with a variable at 0 and will increment the counter until it is equal to 10. Once it does, we can break out of the loop. In this example, we see our looping block contains the printf() and counter++ statements. Our iterating variable is counter and our condition is (counter < 10) However, if we made a slight modification:

int main(void)
{
   int counter = 11;
   while (counter > 10)
   {
      counter++;
   }
   return 0;
}

our program would be stuck in an infinite loop. We could also stall our program by doing the following:

#include <stdio.h>

int main(void)
{
   int counter = 0;
   while (counter < 10)
   {
      printf("counter: %d\n", counter);
   }

   return 0;
}

Since we are not incrementing our incrementing variable, we won’t change our looping condition and will stay in the loop forever.

If this happens to you, use CTRL+C (Windows, Mac and Linux) to kill the program or close out of your terminal.

do while()

We can take the same logic from above and write a do while() loop like so:

#include <stdio.h>

int main(void)
{
   int counter = 0;
   do {
     printf("Hello World!\n");
     counter++;
   } while (counter < 0);

   return 0;
}

If we run this code, we should expect it to not print out anything since 0 is not less than 0. However, it will actually print out once. This is because do while loops will always execute whatever is inside the looping block at least once. This can be emulated using a regular loop like so:

#include <stdio.h>

int main(void)
{
   int counter = 0;
   int iterate_once = 1;
   
   while (iterate_once == 1 || counter < 0)
   {
      printf("Hello World!\n");
      counter++;
      iterate_once = 0;
   }

   return 0;
}

for ()

For loops are a great way of condensing your loops and ensuring you have every component necessary for your looping block. Let’s consider the following code and create an equivalent expression using a for loop.

#include <stdio.h>

int main(void)
{
   int counter = 0;
   
   while (counter < 10)
   {
      printf("Hello World!\n");
      counter++;
   }

   return 0;
}

#include <stdio.h>

int main(void)
{
   int counter;
   for (counter = 0; counter < 10; counter++)
   {
      printf("Hello World!\n");
   }

   return 0;
}

For loops have a unique property in that it takes three arguments: iterating variable instantiation, looping condition and incrementing term. NOTE: You can leave the first and third term blank, however, for loops require a looping condition at the very minimum.

for (iterating variable instantiation; looping condition; incrementing term)

You can declare and instantiate your looping variable in the first position, however, it is best practice in C to declare outside of the loop and instantiate in the first position of the for loop. The first term is only executed once, whereas the looping condition is checked at every iteration and the incrementing term will happen at the end of every iteration -just before the condition is checked in the next iteration.

Control Flow in Loops

#include <stdio.h>

int main(void)
{
   int i, j;   j = 0;
   for (i = 0; i < 10; i++)
   {
      if (i == 8)
      {
         break;
      }
      else if (i <= 4)
      {
         printf("\n ij in continue: %d%d\n", i, j);
         continue;
         break;
      }
      for (j = 0; j < 10; j++)
      {
         printf("%d%d\t", i, j);
         if (j == 5)
         {
            break;
         }
      }
   }
   return 0;
}

We have two keywords we can use to control the flow of loops: break and continue. Break will stop everything that is happening within the current loop and go back to the main program or parent loop. Continue will jump back to the top of the loop. Try out these keywords with the above example by modifying or adding new loops with new conditions.

Foreshadowing...

We learned how to reuse our code, but there is an issue that pops up with functions. Remember in our last post, we covered how to set up pieces of code that can be called in one line of code? What if we wanted to modify the values in our main code like so:

#include <stdio.h>

void changeNumber(int a)
{
 a = 1;
}

int main(void)
{
 int a = 5;
 changeNumber(a);

 printf("a = %d\n", a);
 return 0;
}

When you run this code, the value of a doesn’t change. Why is this? In the next post we’ll cover the difference between pass by value and pass by reference. We’ll also dive into one of the more challenging topics pointers.

That's weird... something went wrong. Please try again.
Welcome to the R U Coding Me Newsletter!

R U Coding Me Newsletter

Subscribe to our newsletter and stay updated.

We use Brevo as our marketing platform. By Clicking below to submit this form, you acknowledge that the information you provided will be transferred to Brevo for processing in accordance with their terms of use

Are You Coding?

If the answer is no, you’re probably missing out on a large opportunity here. And yes, I said the name!

Our FREE developer resources will help you start programming. Additionally, consider applying for mentorship to accelerate you to your career. Click on the Student button below to get started. It will take you to our available courses and any relevant materials to help get you started.

Ready to take your business to the next level? Creating a robust solution in a short amount of time is hard to do if you’ve never done it before. Plus, why should you juggle yet another project with your business? Click on the Business button below if you’re looking to scale your current business online but don’t want to spend a few years to learn how to do it. It will take you to our services so you can see what would best work for you.

More To Explore
Learn C Programming
Multidimensional Arrays in C With Example

FacebookTweetPinLinkedInEmail Wait, You Said There Wouldn’t Be Any More Pointers! No, if you recall from last time, I mentioned there could be pointers that point

Learn C Programming
Efficiently Debugging C Programs

FacebookTweetPinLinkedInEmail What is Debugging? Overview of Debugging Debugging is an art form, rather than a science. Debugging is the act of removing any issues that

R U Coding Me LLC