Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - while

Node:while, Next:, Previous:Loops, Up:Loops



while

The simplest of the three is the while loop. It looks like this:

while (condition)
{
  do something
}

The condition (for example, (a > b)) is evaluated every time the loop is executed. If the condition is true, then statements in the curly brackets are executed. If the condition is false, then those statements are ignored, and the while loop ends. The program then executes the next statement in the program.

The condition comes at the start of the loop, so it is tested at the start of every pass, or time through the loop. If the condition is false before the loop has been executed even once, then the statements inside the curly brackets will never be executed. (See do...while, for an example of a loop construction where this is not true.)

The following example prompts the user to type in a line of text, and then counts all the spaces in the line. The loop terminates when the user hits the <RET> key and then prints out the number of spaces. (See getchar, for more information on the standard library getchar function.)

#include <stdio.h>

int main()
{
  char ch;
  int count = 0;

  printf ("Type in a line of text.\n");

  while ((ch = getchar()) != '\n')
  {
    if (ch == ' ')
    {
      count++;
    }
  }

  printf ("Number of spaces = %d.\n\n", count);
  return 0;
}

 
 
  Published under free license. Design by Interspire