Guru99

Loops in C: For, While, Do While looping Statements [Examples]

Barbara Thompson

What is Loop in C?

Looping Statements in C execute the sequence of statements many times until the stated condition becomes false. A loop in C consists of two parts, a body of a loop and a control statement. The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false. The purpose of the C loop is to repeat the same code a number of times.

Types of Loops in C

Depending upon the position of a control statement in a program, looping statement in C is classified into two types:

1. Entry controlled loop

2. Exit controlled loop

In an entry control loop in C, a condition is checked before executing the body of a loop. It is also called as a pre-checking loop.

In an exit controlled loop , a condition is checked after executing the body of a loop. It is also called as a post-checking loop.

Types of Loops in C

The control conditions must be well defined and specified otherwise the loop will execute an infinite number of times. The loop that does not stop executing and processes the statements number of times is called as an infinite loop . An infinite loop is also called as an “ Endless loop .” Following are some characteristics of an infinite loop:

1. No termination condition is specified.

2. The specified conditions never meet.

The specified condition determines whether to execute the loop body or not.

‘C’ programming language provides us with three types of loop constructs:

1. The while loop

2. The do-while loop

3. The for loop

While Loop in C

A while loop is the most straightforward looping structure. While loop syntax in C programming language is as follows:

Syntax of While Loop in C

It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false. Once the condition becomes false, the control goes out of the loop.

After exiting the loop, the control goes to the statements which are immediately after the loop. The body of a loop can contain more than one statement. If it contains only one statement, then the curly braces are not compulsory. It is a good practice though to use the curly braces even we have a single statement in the body.

In while loop, if the condition is not true, then the body of a loop will not be executed, not even once. It is different in do while loop which we will see shortly.

Following program illustrates while loop in C programming example:

The above program illustrates the use of while loop. In the above program, we have printed series of numbers from 1 to 10 using a while loop.

While Loop in C

  • We have initialized a variable called num with value 1. We are going to print from 1 to 10 hence the variable is initialized with value 1. If you want to print from 0, then assign the value 0 during initialization.
  • In a while loop, we have provided a condition (num<=10), which means the loop will execute the body until the value of num becomes 10. After that, the loop will be terminated, and control will fall outside the loop.
  • In the body of a loop, we have a print function to print our number and an increment operation to increment the value per execution of a loop. An initial value of num is 1, after the execution, it will become 2, and during the next execution, it will become 3. This process will continue until the value becomes 10 and then it will print the series on console and terminate the loop.

Do-While loop in C

A do…while loop in C is similar to the while loop except that the condition is always executed after the body of a loop. It is also called an exit-controlled loop.

Syntax of do while loop in C programming language is as follows:

Syntax of Do-While Loop in C

As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to execute a body of the loop at least once even if the condition is false. This type of operation can be achieved by using a do-while loop.

In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.

Similar to the while loop, once the control goes out of the loop the statements which are immediately after the loop is executed.

The critical difference between the while and do-while loop is that in while loop the while is written at the beginning. In do-while loop, the while condition is written at the end and terminates with a semi-colon (;)

The following loop program in C illustrates the working of a do-while loop:

Below is a do-while loop in C example to print a table of number 2:

In the above example, we have printed multiplication table of 2 using a do-while loop. Let’s see how the program was able to print the series.

Do-While loop in C

  • First, we have initialized a variable ‘num’ with value 1. Then we have written a do-while loop.
  • In a loop, we have a print function that will print the series by multiplying the value of num with 2.
  • After each increment, the value of num will increase by 1, and it will be printed on the screen.
  • Initially, the value of num is 1. In a body of a loop, the print function will be executed in this way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on until the value of num becomes 10. After that loop will be terminated and a statement which is immediately after the loop will be executed. In this case return 0.

For loop in C

A for loop is a more efficient loop structure in ‘C’ programming. The general structure of for loop syntax in C is as follows:

Syntax of For Loop in C

  • The initial value of the for loop is performed only once.
  • The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.
  • The incrementation/decrementation increases (or decreases) the counter by a set value.

Following program illustrates the for loop in C programming example:

The above program prints the number series from 1-10 using for loop.

For loop in C

  • We have declared a variable of an int data type to store values.
  • In for loop, in the initialization part, we have assigned value 1 to the variable number. In the condition part, we have specified our condition and then the increment part.
  • In the body of a loop, we have a print function to print the numbers on a new line in the console. We have the value one stored in number, after the first iteration the value will be incremented, and it will become 2. Now the variable number has the value 2. The condition will be rechecked and since the condition is true loop will be executed, and it will print two on the screen. This loop will keep on executing until the value of the variable becomes 10. After that, the loop will be terminated, and a series of 1-10 will be printed on the screen.

In C, the for loop can have multiple expressions separated by commas in each part.

For example:

Also, we can skip the initial value expression, condition and/or increment by adding a semicolon.

Notice that loops can also be nested where there is an outer loop and an inner loop. For each iteration of the outer loop, the inner loop repeats its entire cycle.

Consider the following example with multiple conditions in for loop, that uses nested for loop in C programming to output a multiplication table:

The nesting of for loops can be done up-to any level. The nested loops should be adequately indented to make code readable. In some versions of ‘C,’ the nesting is limited up to 15 loops, but some provide more.

The nested loops are mostly used in array applications which we will see in further tutorials.

Break Statement in C

The break statement is used mainly in the switch statement . It is also useful for immediately stopping a loop.

We consider the following program which introduces a break to exit a while loop:

Continue Statement in C

When you want to skip to the next iteration but remain in the loop, you should use the continue statement.

So, the value 5 is skipped.

Which loop to Select?

Selection of a loop is always a tough task for a programmer, to select a loop do the following steps:

  • Analyze the problem and check whether it requires a pre-test or a post-test loop.
  • If pre-test is required, use a while or for a loop.
  • If post-test is required, use a do-while loop.
  • Define loop in C: A Loop is one of the key concepts on any Programming language . Loops in C language are implemented using conditional statements.
  • A block of loop control statements in C are executed for number of times until the condition becomes false.
  • Loops in C programming are of 2 types: entry-controlled and exit-controlled.
  • List various loop control instructions in C: C programming provides us 1) while 2) do-while and 3) for loop control instructions.
  • For and while loop C programming are entry-controlled loops in C language.
  • Do-while is an exit control loop in C.
  • Dynamic Memory Allocation in C using malloc(), calloc() Functions
  • Type Casting in C: Type Conversion, Implicit, Explicit with Example
  • C Programming Tutorial PDF for Beginners
  • 13 BEST C Programming Books for Beginners (2024 Update)
  • Difference Between C and Java
  • Difference Between Structure and Union in C
  • Top 100 C Programming Interview Questions and Answers (PDF)
  • calloc() Function in C Library with Program EXAMPLE

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop

C break and continue

  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples
  • Count Number of Digits in an Integer
  • Reverse a Number
  • Find GCD of two Numbers
  • Calculate Average Using Arrays

C while and do...while Loop

In programming, loops are used to repeat a block of code until a specified condition is met.

C programming has three types of loops.

do...while loop

In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and do..while loop.

The syntax of the while loop is:

How while loop works?

  • The while loop evaluates the testExpression inside the parentheses () .
  • If  testExpression is true , statements inside the body of while loop are executed. Then, testExpression is evaluated again.
  • The process goes on until testExpression is evaluated to false .
  • If  testExpression is false , the loop terminates (ends).

To learn more about test expressions (when  testExpression is evaluated to true and false ), check out relational and logical operators .

Flowchart of while loop

flowchart of while loop in C programming

Example 1: while loop

Here, we have initialized i to 1.

  • When i = 1 , the test expression i <= 5 is true . Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2 .
  • Now, i = 2 , the test expression i <= 5 is again true . The body of the while loop is executed again. This prints 2 on the screen and the value of i is increased to 3 .
  • This process goes on until i becomes 6. Then, the test expression i <= 5 will be false and the loop terminates.

The do..while loop is similar to the while loop with one important difference. The body of do...while loop is executed at least once. Only then, the test expression is evaluated.

The syntax of the do...while loop is:

How do...while loop works?

  • The body of do...while loop is executed once. Only then, the testExpression is evaluated.
  • If testExpression is true , the body of the loop is executed again and testExpression is evaluated once more.
  • This process goes on until testExpression becomes false .
  • If testExpression is false , the loop ends.

Flowchart of do...while Loop

do while loop flowchart in C programming

Example 2: do...while loop

Here, we have used a do...while loop to prompt the user to enter a number. The loop works as long as the input number is not 0 .

The  do...while loop executes at least once i.e. the first iteration runs without checking the condition. The condition is checked only after the first iteration has been executed.

So, if the first input is a non-zero number, that number is added to the sum variable and the loop continues to the next iteration. This process is repeated until the user enters  0 .

But if the first input is 0, there will be no second iteration of the loop and  sum  becomes 0.0 .

Outside the loop, we print the value of sum .

Table of Contents

  • Example: while Loop
  • do...while Loop
  • Example: do...while Loop

Video: C while Loop

Sorry about that.

Related Tutorials

C if...else Statement

C Multidimensional Arrays

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Environment Setup
  • C - Program Structure
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Constants
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - Functions
  • C - Scope Rules
  • C - Pointers
  • C - Strings
  • C - Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming useful Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

while loop in C

A while loop in C programming repeatedly executes a target statement as long as a given condition is true.

The syntax of a while loop in C programming language is −

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.

When the condition becomes false, the program control passes to the line immediately following the loop.

Flow Diagram

while loop in C

Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

When the above code is compiled and executed, it produces the following result −

Get certified by completing the course

Home » Learn C Programming from Scratch » C while Loop

C while Loop

Summary : in this tutorial, you will learn how to use the C while loop statement to execute a code block repeatedly based on a condition.

Introduction C while loop statement

The C while loop statement allows you to execute a code block repeatedly based on a condition that is checked at the beginning of each iteration.

Here’s the syntax of the while loop statement:

How it works:

The while statement first evaluates the expression . If the result is non-zero ( true ), the while statement executes the statement within its body. This cycle continues until the expression becomes zero (or false ).

The while statement re-checks the expression at the beginning of each iteration before executing the statement . Therefore, at some point, the expression needs to become zero (or false ) to end the loop. Otherwise, you’ll have an indefinite loop.

When the while statment is first encountered and the expression is zero (or false ), the while statement won’t execute the statement at all. The program pass the control to the statement that follows the while statement.

The following flowchart illustrates how while loop works:

c while loop

C while loop examples

Let’s take some examples of using the while loop statement

1) Simple C while loop statement

The following example uses the while loop statement to display five numbers from 0 to 4:

How it works.

  • First, declare the n variable and initialize it to 0 .
  • Second, check if n is less than 5 before entering the loop.
  • Third, display n and add 1 to it in each iteration. Repeat this cycle until n is not less than 5 .

Since n starts with zero, the while statement executes 5 iterations.

2) Using the C while loop to develop a number guessing game

The following example illustrates how to use the while loop statement to create the number guessing game:

First, define the maximum of guesses:

Second, generate a random number between 0 and 10:

Third, allow users to prompt a number until the number of guesses reaches MAX_GUESS or the number equals the secret_number:

Fourth, increase the guess and prompt for an input:

Fifth, display a success message if the input number matches the secret number:

Sixth, show a message to the users if the number is lower or higher:

Seventh, display the remaining guesses or a failed message if the guesses have been used:

  • Use the C while loop statement to repeatedly execute a code based on a condition checked at the beginning of each iteration.

HPlus Academy

The Ultimate Guide to the While Loop in C

Introduction.

In the world of programming, loops play a crucial role in executing a set of instructions repeatedly. One such loop that is widely used is the “while loop” in the C programming language.

Understanding how to effectively use the while loop in C can greatly enhance your coding skills and allow you to solve complex problems efficiently.

In this comprehensive guide, we will delve deep into the while loop in C, covering its syntax, working principles, best practices, and common pitfalls to avoid.

Also Read: 25 Interview Questions On C: A Comprehensive Guide for Success

What is a While Loop?

A while loop is a control flow statement in C that allows a block of code to be repeatedly executed as long as a certain condition is true.

It provides a way to automate repetitive tasks and iterate over a set of instructions until a specific condition is met.

The while loop is known for its versatility and is widely used in various programming scenarios.

Syntax of the While Loop in C

The syntax of the while loop in C is as follows:

In the above syntax, the condition is an expression that is evaluated before each iteration of the loop.

If the condition evaluates to true, the code block inside the loop is executed. If the condition evaluates to false, the loop is terminated, and the program continues with the next line of code after the loop.

Also Read: Boost Python Code Efficiency: Eliminating Loops for Enhanced Performance

Using the While Loop in C

To better understand how the while loop works in C, let’s consider a simple example. Suppose we want to print the numbers from 1 to 5 using a while loop:

In the above code, we initialize the variable i with the value 1. The while loop continues to execute as long as i is less than or equal to 5.

Inside the loop, we print the value of i and then increment it by 1 using the i++ statement. This process continues until i becomes 6, at which point the condition becomes false, and the loop terminates.

Also Read: C Program to Find the Sum of Cubes of Elements in an Array

Common Mistakes to Avoid

While working with while loops in C, it’s important to be aware of certain common mistakes that programmers often make.

Here are some of the common pitfalls and how to avoid them:

  • Forgetting to update loop control variable : It’s crucial to update the loop control variable inside the loop body; otherwise, the loop might become an infinite loop, leading to an application freeze or crash.
  • Missing proper termination condition : Failing to provide a proper termination condition can result in an infinite loop. Always ensure that the condition is appropriately defined and will eventually become false.
  • Inadequate initialization : Ensure that the loop control variable is properly initialized before entering the while loop. Failure to initialize it may lead to unexpected behavior and incorrect results.
  • Not using curly braces for single-line code blocks : Although not mandatory, it’s considered good practice to enclose the code block inside curly braces, even if it consists of a single line. This improves code readability and reduces the chances of introducing bugs in the future.

By being mindful of these common mistakes, you can avoid unnecessary errors and ensure the smooth execution of your while loops.

Also Read: C Program to Display a String in Capital Letters

Examples of While Loops in C

Let’s explore a few more examples to showcase the versatility of the while loop in C:

Example 1: Calculating Factorial

In this example, we calculate the factorial of a given positive integer using a while loop.

The loop iterates from the given number down to 1, continuously multiplying the factorial variable with the current value of num .

Example 2: User Input Validation

This example demonstrates the use of a while loop for user input validation.

The loop repeatedly prompts the user to enter their age until a valid age within the range of 0 to 120 is provided.

Also Read: C Language Program to Count the Number of Lowercase Letters in a Text File

Advantages of Using While Loops

The while loop in C offers several advantages that make it a powerful tool in programming:

  • Flexibility : While loops can handle a wide range of scenarios, allowing developers to iterate over data structures, validate user input, perform calculations, and much more.
  • Simplicity : The syntax of the while loop is straightforward and easy to understand, making it accessible for both beginners and experienced programmers.
  • Efficiency : While loops are efficient in terms of memory usage and execution time, making them suitable for handling large datasets and time-critical operations.
  • Control : With the while loop, developers have precise control over the loop condition, allowing them to create custom iterations based on specific requirements.

The main difference between a while loop and a do-while loop in C is that the while loop checks the condition before executing the loop body, while the do-while loop checks the condition after executing the loop body. This means that a do-while loop will always execute the loop body at least once, regardless of the condition.

Yes, you can use multiple conditions in a while loop by combining them using logical operators such as && (logical AND) and || (logical OR). This allows you to create complex conditions to control the loop execution.

Yes, you can use the break statement inside a while loop to prematurely exit the loop before the condition becomes false. This is useful when a specific condition is met, and you want to terminate the loop immediately.

Yes, it is possible to nest while loops within each other. This means you can have a while loop inside another while loop. However, it’s important to ensure that the loop termination conditions are correctly defined to avoid infinite looping.

No, C provides other types of loops, such as the for loop and the do-while loop, each with its own advantages and use cases. It’s essential to choose the appropriate loop construct based on the specific requirements of your program.

No, a while loop requires a condition to be specified. The loop will execute as long as the condition evaluates to true. If you omit the condition, it will result in a syntax error.

The while loop in C is a powerful construct that allows developers to iterate over code blocks as long as a specific condition remains true.

By mastering the while loop, you gain the ability to automate repetitive tasks, validate user input, and perform complex calculations.

In this guide, we covered the syntax of the while loop, provided examples of its usage, highlighted common mistakes to avoid, and explored its advantages.

Remember to practice writing while loops in various scenarios to strengthen your understanding and proficiency.

With dedication and hands-on experience, you’ll become proficient in leveraging the while loop to solve problems and create efficient programs.

Codeforwin

Loop programming exercises and solutions in C

In programming, there exists situations when you need to repeat single or a group of statements till some condition is met. Such as – read all files of a directory, send mail to all employees one after another etc. These task in C programming is handled by looping statements .

Looping statement defines a set of repetitive statements. These statements are repeated with same or different parameters for a number of times. Looping statement is also known as iterative or repetitive statement .

C supports three looping statements.

  • do…while loop

In this exercise we will practice lots of looping problems to get a strong grip on loop. This is most recommended C programming exercise for beginners.

Always feel free to drop your queries, suggestions, hugs or bugs down below in the comments section . I always look forward to hear from you.

Required knowledge

Basic C programming , Relational operators , Logical operators , If else , For loop

List of loop programming exercises

  • Write a C program to print all natural numbers from 1 to n.  – using  while loop
  • Write a C program to print all natural numbers in reverse (from n to 1) . – using  while loop
  • Write a C program to print all alphabets from a to z.  – using  while loop
  • Write a C program to print all even numbers between 1 to 100.  – using  while loop
  • Write a C program to print all odd number between 1 to 100.
  • Write a C program to find sum of all natural numbers between 1 to n.
  • Write a C program to find sum of all even numbers between 1 to n .
  • Write a C program to find sum of all odd numbers between 1 to n .
  • Write a C program to print multiplication table of any number .
  • Write a C program to count number of digits in a number .
  • Write a C program to find first and last digit of a number .
  • Write a C program to find sum of first and last digit of a number.
  • Write a C program to swap first and last digits of a number .
  • Write a C program to calculate sum of digits of a number .
  • Write a C program to calculate product of digits of a number .
  • Write a C program to enter a number and print its reverse .
  • Write a C program to check whether a number is palindrome or not.
  • Write a C program to find frequency of each digit in a given integer .
  • Write a C program to enter a number and print it in words.
  • Write a C program to print all ASCII character with their values .
  • Write a C program to find power of a number using for loop .
  • Write a C program to find all factors of a number .
  • Write a C program to calculate factorial of a number .
  • Write a C program to find HCF (GCD) of two numbers .
  • Write a C program to find LCM of two numbers .
  • Write a C program to check whether a number is Prime number or not.
  • Write a C program to print all Prime numbers between 1 to n.
  • Write a C program to find sum of all prime numbers between 1 to n .
  • Write a C program to find all prime factors of a number .
  • Write a C program to check whether a number is Armstrong number or not.
  • Write a C program to print all Armstrong numbers between 1 to n.
  • Write a C program to check whether a number is Perfect number or not .
  • Write a C program to print all Perfect numbers between 1 to n .
  • Write a C program to check whether a number is Strong number or not .
  • Write a C program to print all Strong numbers between 1 to n .
  • Write a C program to print Fibonacci series up to n terms .
  • Write a C program to find one’s complement of a binary number .
  • Write a C program to find two’s complement of a binary number .
  • Write a C program to convert Binary to Octal number system .
  • Write a C program to convert Binary to Decimal number system .
  • Write a C program to convert Binary to Hexadecimal number system .
  • Write a C program to convert Octal to Binary number system .
  • Write a C program to convert Octal to Decimal number system .
  • Write a C program to convert Octal to Hexadecimal number system .
  • Write a C program to convert Decimal to Binary number system .
  • Write a C program to convert Decimal to Octal number system .
  • Write a C program to convert Decimal to Hexadecimal number system .
  • Write a C program to convert Hexadecimal to Binary number system .
  • Write a C program to convert Hexadecimal to Octal number system .
  • Write a C program to convert Hexadecimal to Decimal number system .
  • Write a C program to print Pascal triangle upto n rows .
  • Star pattern programs – Write a C program to print the given star patterns.
  • Number pattern programs – Write a C program to print the given number patterns .

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

While loop program in c.

' src=

Last Updated on August 18, 2023 by Mayank Dham

c assignment in while loop

In this upcoming article, we will comprehensively explore the concept of the While Loop in C programming language. We will delve into its definitions, syntax, visualization through flowcharts, and provide illustrative examples. If you haven’t already, we encourage you to refer to our previous articles, which extensively covered C Language problem-solving. The adept utilization of loop control statements holds immense significance in logical programming. Often referred to as Iteration Statements, these constructs are fundamental to achieving repetitive operations. Hence, the terms "looping" and "iteration" are interchangeable in this context. To embark on our journey, let’s begin by grasping the essence of loops, their essentiality, and the diverse array of loops at our disposal within a C program. This foundational understanding will seamlessly pave the way for a comprehensive exploration of the while loop and its practical implementation.

What is looping?

Looping involves the continuous execution of a statement or group of statements until a specified condition is satisfied. In this scenario, the loop’s execution concludes when the condition evaluates to false. These constructs are referred to as iteration statements because of their ability to cyclically repeat the execution of statements, forming a loop-like pattern.

Why do we need looping?

Code repetition is the loop’s primary goal. When repeats are necessary during implementation, looping should be used instead of repeatedly writing the same statements. Looping or iterating Statements: Loops are produced by iteration statements in a program. Iteration is the process of repeatedly running the same piece of code until a predetermined condition is met. The same instructions are carried out by iteration statements up until a termination condition is satisfied. The iteration statements loop in C is as follows:

  • do-while loop

What is While Loop in C Language:

A loop iterates a block of instructions repeatedly as long as the given condition remains true. It continues to repeat the instructions as many times as required by the condition’s truth value. The loop’s execution halts when the specified condition is satisfied. While loops are employed to continually execute statements up until a specified condition returns false. A single remark or a group of statements are both acceptable in this context. Any expression that meets the criterion is true, and a nonzero value does too. While the condition is true, the loop iterates. You can understand the while loop more clearly if you view the syntax and flowchart side by side.

While Loop Syntax in C Language:

c assignment in while loop

When using a while loop, we must first verify the condition. If the condition is true, control will move inside the body of the loop, if the condition is false, the control will move outside the loop.

When using an iteration statement, the control is returned to the condition after the body has been executed until the condition becomes false. An endless loop will result if the condition is true.

The flow is distinct from the if condition, although it is comparable to the if condition, just condition, and statements. The flowchart enables us to comprehend how it differs.

c assignment in while loop

The flowchart will begin. The oval sign denotes the beginning. The condition will then be checked. Every condition, as was previously explained, has two outputs: true and false. We must determine if the predictions of what will occur are correct or untrue.

All statements defined inside the block (inside the while loop block) will be executed if the condition is true. Will it come to an end when the statements are executed? It won’t end, no. Following the execution of the statements, it will once again go and verify the condition. As long as the specified condition is true, the identical procedure will be repeated. If the assumption is incorrect, the sentence will come to an end. This is how a while loop might operate.

Program to understand While loop in C Language:

The variable an is given a value of 1 during initialization, and the condition is then verified. If the condition returns true, the statements included in the while loop’s body are carried out; otherwise, control is transferred outside of the loop. The ++ operator is used to increase the value of a before it is once again examined for the loop condition.

Example to Print no 1 to 5 using a while loop in C Language

Conclusion In conclusion, the "while loop" is a fundamental construct in the C programming language that enables efficient and controlled repetition of a set of instructions. By evaluating a condition before each iteration, the while loop ensures that the instructions are executed repeatedly as long as the condition remains true. This powerful mechanism empowers programmers to create dynamic and flexible code structures, enabling the automation of tasks and the processing of data efficiently. A solid grasp of the while loop is essential for mastering the art of logical programming and building robust software solutions.

FAQs related to While Loop Program in C

Below are some Frequently Asked Questions related to the While Loop Program in C:

1. How does a while loop work? A while loop evaluates the condition before each iteration. If the condition is true, the statements within the loop are executed. The loop continues to execute as long as the condition remains true. Once the condition becomes false, the loop terminates, and control passes to the next statement after the loop.

2. What is the role of the loop condition? The loop condition determines whether the loop should continue executing or terminate. If the condition is initially false, the loop may not execute at all.

3. Can a while loop run indefinitely? Yes, a while loop can potentially run indefinitely if the loop condition always remains true and there is no mechanism to break out of the loop. This is known as an infinite loop.

4. How do you prevent an infinite loop? To prevent an infinite loop, ensure that the loop condition eventually evaluates to false. You can incorporate statements within the loop to modify variables and alter the condition, allowing the loop to exit.

5. Can a while loop execute zero times? Yes, if the loop condition is initially false, the statements within the loop may not execute at all, resulting in zero iterations.

6. How does a while loop differ from a for loop? While both loops repeat code based on a condition, a while loop evaluates the condition before each iteration, while a for loop incorporates initialization, condition, and increment/decrement expressions within its syntax.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Null character in c, assignment operator in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c.

cppreference.com

Executes a statement repeatedly, until the value of condition becomes false . The test takes place before each iteration.

[ edit ] Syntax

[ edit ] explanation.

Whether statement is a compound statement or not, it always introduces a block scope . Variables declared in it are only visible in the loop body, in other words,

is the same as

If condition is a declaration such as T t = x , the declared variable is only in scope in the body of the loop, and is destroyed and recreated on every iteration, in other words, such while loop is equivalent to

If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.

If the execution of the loop needs to be continued at the end of the loop body, continue statement can be used as shortcut.

[ edit ] Notes

As part of the C++ forward progress guarantee , the behavior is undefined if a loop that has no observable behavior (does not make calls to I/O functions, access volatile objects, or perform atomic or synchronization operations) does not terminate. Compilers are permitted to remove such loops.

[ edit ] Keywords

[ edit ] example, [ edit ] see also.

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 February 2023, at 02:31.
  • This page has been accessed 233,673 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Javatpoint Logo

  • Design Pattern
  • Interview Q

C Control Statements

C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • Graphic Designing
  • Digital Marketing
  • On Page and Off Page SEO
  • Content Development
  • Corporate Training
  • Classroom and Online Training

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week

RSS Feed

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

c assignment in while loop

  • Explore Our Geeks Community
  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Operators in C | Set 2 (Relational and Logical Operators)
  • Bitwise Operators in C/C++
  • C Logical Operators
  • Assignment Operators in C
  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C / C++ (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C/C++
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of a multidimensional arrays in C/C++
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C/C++ Preprocessors
  • C/C++ Preprocessor directives | Set 2
  • How a Preprocessor works in C?
  • Header Files in C/C++ and its uses
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C/C++
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C/C++
  • _Generics Keyword in C
  • Multithreading in C
  • Top 50 C Programming Interview Questions and Answers
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

C – Loops

Loops in programming are used to repeat a block of code until the specified condition is met. A loop statement allows programmers to execute a statement or group of statements multiple times without repetition of code.

There are mainly two types of loops in C Programming:

  • Entry Controlled loops: In Entry controlled loops the test condition is checked before entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.
  • Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the loop body. The loop body will execute at least once, irrespective of whether the condition is true or false. do-while Loop is Exit Controlled loop.

loops in c

for Loop 

for loop in C programming is a  repetition control structure that allows programmers to write a loop that will be executed a specific number of times. for loop enables programmers to perform n number of steps together in a single line.

In for loop, a loop variable is used to control the loop. Firstly we initialize the loop variable with some value, then check its test condition. If the statement is true then control will move to the body and the body of for loop will be executed. Steps will be repeated till the exit condition becomes true. If the test condition will be false then it will stop.

  • Initialization Expression: In this expression, we assign a loop variable or loop counter to some value. for example: int i=1;
  • Test Expression: In this expression, test conditions are performed. If the condition evaluates to true then the loop body will be executed and then an update of the loop variable is done. If the test expression becomes false then the control will exit from the loop. for example, i<=9;
  • Update Expression: After execution of the loop body loop variable is updated by some value it could be incremented, decremented, multiplied, or divided by any value.

for loop Equivalent Flow Diagram:

for loop in c

While loop does not depend upon the number of iterations. In for loop the number of iterations was previously known to us but in the While loop, the execution is terminated on the basis of the test condition. If the test condition will become false then it will break from the while loop else body will be executed.

Flow Diagram for while loop:

while loop in C

do-while Loop

The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition which is tested at the end of the body. In the do-while loop, the loop body will execute at least once irrespective of the test condition.

do while loop in C

Above program will evaluate (i<1) as false since i = 2. But still, as it is a do-while loop the body will be executed once.

Loop Control Statements 

Loop control statements in C programming are used to change execution from its normal sequence.

Infinite Loop

An infinite loop is executed when the test expression never becomes false and the body of the loop is executed repeatedly. A program is stuck in an Infinite loop when the condition is always true. Mostly this is an error that can be resolved by using Loop Control statements. 

Using for loop:

Using While loop:

Using the do-while loop:

Please Login to comment...

author

  • avtarkumar719
  • How to Allocate RAM to Minecraft
  • How To Download Instagram Stories [Multiple Ways]
  • How To Check IMEI Number
  • Top 10 best Low-Code and No-Code AI Platforms Examples
  • 10 Best Free AI Art Generators to Create Image From Text [Free & Paid]
  • 10 Best Free Reverse Phone Number Lookup

Improve your Coding Skills with Practice

 alt=

C++ Tutorial

C++ functions, c++ classes, c++ examples, c++ while loop.

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

The while loop loops through a block of code as long as a specified condition is true :

In the example below, the code in the loop will run, over and over again, as long as a variable ( i ) is less than 5:

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C++ Exercises

Test yourself with exercises.

Print i as long as i is less than 6.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

COMMENTS

  1. c

    5 Answers Sorted by: 23 The comma operator is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value. It is also a "sequence point", which means that all side effects will be calculated before the next part of the code is executed. Share Follow

  2. C Programming While Loop Assignment

    C Programming While Loop Assignment Ask Question Asked 8 years, 9 months ago Modified 8 years, 1 month ago Viewed 993 times 1 Question: Take n as input. Then take n numbers as input and print the summation of those n numbers. But this time output as the format below. Example: Input: 4 1 5 3 -4 output 1 + 5 + 3 - 4 = 5

  3. Combined assignment operator in a while loop condition in C

    Combined assignment operator in a while loop condition in C Asked 1 year, 10 months ago Modified 1 year, 10 months ago Viewed 277 times 0 I really have a hard time understanding how the following piece of code works: int x = -2; while ( --x > -10 && (x -= 2)) { printf ( " %d," , x ) ; } printf ( " %d" , x ) ; output: -5, -8, -11, -12

  4. while loop in C

    while loop in C Read Courses Practice The while Loop is an entry-controlled loop in C programming language. This loop can be used to iterate a part of code while the given condition remains true. Syntax The while loop syntax is as follows: while (test expression) { } Example The below example shows how to use a while loop in a C program C

  5. Loops in C: For, While, Do While looping Statements [Examples]

    1. No termination condition is specified. 2. The specified conditions never meet. The specified condition determines whether to execute the loop body or not. 'C' programming language provides us with three types of loop constructs:

  6. C

    Example of while loop. step1: The variable count is initialized with value 1 and then it has been tested for the condition. step2: If the condition returns true then the statements inside the body of while loop are executed else control comes out of the loop. step3: The value of count is incremented using ++ operator then it has been tested ...

  7. C while and do...while Loop

    C programming has three types of loops. for loop while loop do...while loop In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and do..while loop. while loop The syntax of the while loop is: while (testExpression) { // the body of the loop } How while loop works?

  8. C While Loop

    Syntax while (condition) { // code block to be executed } In the example below, the code in the loop will run, over and over again, as long as a variable ( i) is less than 5: Example int i = 0; while (i < 5) { printf ("%d\n", i); i++; } Try it Yourself »

  9. while loop in C

    The syntax of a while loop in C programming language is −. while (condition) { statement (s); } Here, statement (s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes ...

  10. C while Loop

    Code language: C++ (cpp) How it works: The while statement first evaluates the expression.If the result is non-zero (true), the while statement executes the statement within its body.This cycle continues until the expression becomes zero (or false).. The while statement re-checks the expression at the beginning of each iteration before executing the statement.

  11. Is doing an assignment inside a condition considered a code smell?

    One option is to add the assignment to the condition as follows: List<String> currentStrings; while ( (currentStrings = getCurrentStrings ()).size () > 0) { doThingsThatCanAlterCurrentStrings (); } But while I now have less duplication and less code, i feel that my code is now harder to read.

  12. While loop in C programming

    Looping statements whose condition is checked prior to the execution of its body is called as Entry controlled loop. Syntax of while loop. while (condition) { // Body of while loop } Parts of while loop. Unlike for loop, while does not contain initialization and update part. It contains only two parts - condition and body of loop.

  13. 7.5: While Loop

    This page titled 7.5: While Loop is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan. The concept of iteration is connected to possibly wanting to repeat an action. Like all control structures we ask a question to control the execution of the loop.

  14. The Ultimate Guide to the While Loop in C

    A while loop is a control flow statement in C that allows a block of code to be repeatedly executed as long as a certain condition is true. It provides a way to automate repetitive tasks and iterate over a set of instructions until a specific condition is met. The while loop is known for its versatility and is widely used in various programming ...

  15. c++

    Assignment Within the Check of a While Loop Ask Question Asked 10 years, 6 months ago Modified 7 years, 9 months ago Viewed 1k times 0 I was trying out the following basic summation program using while loops:

  16. Loop programming exercises and solutions in C

    Fundamentals C Programming Data Structures Articles Loop programming exercises and solutions in C In programming, there exists situations when you need to repeat single or a group of statements till some condition is met. Such as - read all files of a directory, send mail to all employees one after another etc.

  17. While Loop Program in C

    A while loop evaluates the condition before each iteration. If the condition is true, the statements within the loop are executed. The loop continues to execute as long as the condition remains true. Once the condition becomes false, the loop terminates, and control passes to the next statement after the loop. 2.

  18. while loop

    attr  (optional)while (condition) (since C++11) any number of. expression which is contextually convertible to bool or a declaration of a single variable with a brace-or-equals initializer. This expression is evaluated before each iteration, and if it yields , the loop is exited. If this is a declaration, the initializer is evaluated before ...

  19. While loop in C

    Properties of while loop. A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails. The condition will be true if it returns 0. The condition will be false if it returns any non-zero number. In while loop, the condition expression is compulsory.

  20. Ryan Van Duzer on Instagram: "New Year's Day, new adventure. I'm at the

    267 likes, 17 comments - duzer on January 1, 2024: "New Year's Day, new adventure. I'm at the Denver International Airport heading to Mexico for ..."

  21. C

    for loop in C programming is a repetition control structure that allows programmers to write a loop that will be executed a specific number of times. for loop enables programmers to perform n number of steps together in a single line. Syntax: for (initialize expression; test expression; update expression) { // // body of for loop // } Example:

  22. C++ While Loop

    Syntax while (condition) { // code block to be executed } In the example below, the code in the loop will run, over and over again, as long as a variable ( i) is less than 5: Example int i = 0; while (i < 5) { cout << i << "\n"; i++; } Try it Yourself »