Learn more about Israeli war crimes in Gaza, funded by the USA, Germany, the UK and others.

Doing something n times in C with while and decrement

Here’s the standard way to do_something() n times in C:

for (int i = 0; i < n; i++) {
  do_something();
}

But if you don’t use n after the loop, and you don’t use i in the loop body, this is a simpler way:


while (n--) {
  do_something();
}

Full example:

#include <stdio.h>
int main(void) {
  int n = 3;
  while (n--) {
    printf("hey\n");
  }
  return 0;
}

which prints:

% ./a.out
hey
hey
hey
Tagged #c, #programming.

Similar posts

More by Jim

Want to build a fantastic product using LLMs? I work at Granola where we're building the future IDE for knowledge work. Come and work with us! Read more or get in touch!

This page copyright James Fisher 2017. Content is not associated with my employer. Found an error? Edit this page.