codescracker


c

C while Loop



« Previous Tutorial Next Tutorial »


Here is the general form of the while loop in C.

while(condition)
{
	statements;
}

As you can see, when the condition is true, then the while loop's statements will be executed, otherwise not. Now go through the following example that illustrates the while loop.

C while Loop Example

Here is a while loop example program in C programming.

/* C while loop example program */

#include<stdio.h>
#include<conio.h>
void main()
{
	int num = 2;
	int i=1;
	clrscr();

	while(i<=10)
	{
		printf("%d * %d = %d\n", num, i, num*i);
		i++;
	}

	getch();
}

Here this program also prints the table of 2 but using the while loop, below is the sample output of this C program.

c while loop example

Here is one more example program that illustrates the concept of while loop in C programming.

/* C while Loop Example 
 * This program illustrates the concept
 * of while loop in C programming
 */

#include<stdio.h>
#include<string.h>
#include<conio.h>

void pad(char *str, int len);

void main()
{
	char str[80];
	clrscr();

	strcpy(str, "this is a test");
	pad(str, 50);
	printf("%d", strlen(str));

	getch();
}
/* adding spaces to the end of the string
 * to fill the string to a predefined length
 */
void pad(char *str, int len)
{
	int l;
	l=strlen(str);
	while(l<len)
	{
		str[l] = ' ';
		l++;
	}
	str[l] = '\0';
}

Below is the sample run of this program

while loop in c

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test