Home

How to Use while Loops in C Programming

|
|  Updated:  
2021-04-06 20:00:07
|   From The Book:  
No items found.
C All-in-One Desk Reference For Dummies
Explore Book
Buy On Amazon
Another popular looping keyword in C programming is while. It has a companion, do, so programmers refer to this type of loop as either while or do-while. The C language is missing the do-whacka-do type of loop.

How to structure a while loop in C programming

The C language while loop is a lot easier to look at than a for loop, but it involves more careful setup and preparation. Basically, it goes like this:
while(<i>condition</i>)
{
  statement(s);
}
The condition is a true/false comparison, just like you’d find in an if statement. The condition is checked every time the loop repeats. As long as it’s true, the loop spins and the statement (or statements) between the curly brackets continues to execute.

Because the evaluation (condition) happens at the start of the loop, the loop must be initialized before the while statement, as shown in Write That Down Ten Times!

So how does a while loop end? The termination happens within the loop’s statements. Usually, one of the statements affects the evaluation, causing it to turn false.

After the while loop is done, program execution continues with the next statement after the final curly bracket.

A while loop can also forgo the curly brackets when it has only one statement:

while(<i>condition</i>)
  statement;
WRITE THAT DOWN TEN TIMES!
#include <stdio.h>
int main()
{
  int x;
  x=0;
  while(x<10)
  {
    puts("Sore shoulder surgery");
    x=x+1;
  }
  return(0);
}
The while loop demonstrated has three parts:
  • The initialization takes place on Line 7, where variable x is set equal to 0.

  • The loop’s exit condition is contained within the while statement’s parentheses, as shown in Line 8.

  • The item that iterates the loop is found on Line 11, where variable x is increased in value. Or, as programmers would say, “Variable x is incremented.”

Exercise 1: Create a new project, ex0913, using the source code from Write That Down Ten Times!. Build and run.

Exercise 2: Change Line 7 in the source code so that variable x is assigned the value 13. Build and run. Can you explain the output?

Exercise 3: Write a program that uses a while loop to display values from –5 through 5, using an increment of 0.5.

How to use the do-while loop in C programming

The do-while loop can be described as an upside-down while loop. That’s true, especially when you look at the thing’s structure:
do
{
  statement(s);
} while (<i>condition</i>);
As with a while loop, the initialization must take place before entering the loop, and one of the loop’s statements should affect the condition so that the loop exits. The while statement, however, appears after the last curly bracket. The do statement begins the structure.

Because of its inverse structure, the major difference between a while loop and a do-while loop is that the do-while loop is always executed at least one time. So you can best employ this type of loop when you need to ensure that the statements spin once. Likewise, avoid do-while when you don’t want the statements to iterate unless the condition is true.

A FIBONACCI SEQUENCE

#include <stdio.h>
int main()
{
  int fibo,nacci;
  fibo=0;
  nacci=1;
  do
  {
    printf("%d ",fibo);
    fibo=fibo+nacci;
    printf("%d ",nacci);
    nacci=nacci+fibo;
  } while( nacci < 300 );
  putchar('n');
  return(0);
}
Exercise 4: Type the source code from A Fibonacci Sequence into a new project, ex0916. Mind your typing! The final while statement (refer to Line 16) must end with a semicolon, or else the compiler gets all huffy on you.

Here’s the output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233
The loop begins at Lines 7 and 8, where the variables are initialized.

Lines 12 through 15 calculate the Fibonacci values. Two printf() functions display the values.

The loop ends on Line 16, where the while statement makes its evaluation. As long as variable nacci is less than 300, the loop repeats. You can adjust this value higher to direct the program to output more Fibonacci numbers.

On Line 18, the putchar() statement cleans up the output by adding a newline character.

Exercise 5: Repeat Exercise 2 as a do-while loop.

About This Article

This article is from the book: 

No items found.

About the book author:

Dan Gookin has been writing about technology for 20 years. He has contributed articles to numerous high-tech magazines and written more than 90 books about personal computing technology, many of them accurate.
He combines his love of writing with his interest in technology to create books that are informative and entertaining, but not boring. Having sold more than 14 million titles translated into more than 30 languages, Dan can attest that his method of crafting computer tomes does seem to work.
Perhaps Dan’s most famous title is the original DOS For Dummies, published in 1991. It became the world’s fastest-selling computer book, at one time moving more copies per week than the New York Times number-one best seller (although, because it’s a reference book, it could not be listed on the NYT best seller list). That book spawned the entire line of For Dummies books, which remains a publishing phenomenon to this day.
Dan’s most recent titles include PCs For Dummies, 9th Edition; Buying a Computer For Dummies, 2005 Edition; Troubleshooting Your PC For Dummies; Dan Gookin’s Naked Windows XP; and Dan Gookin’s Naked Office. He publishes a free weekly computer newsletter, “Weekly Wambooli Salad,” and also maintains the vast and helpful Web site www.wambooli.com.