Categories: C

while loop in c

The while loop in c is an entry controlled loop (Entry Controlled Loops are used when checking of a test condition is mandatory before executing the loop body). It is generally used where we don’t know the number of iterations.

Syntax of while loop in C:
initialization;
while(condition)
{
   //code to be executed
   updation;
}
Example:
 
#include <stdio.h>

int main() {
   int n,sum=0;
   scanf("\n%d",&n);
    int temp=n;
    while(temp>=1)
    {
       sum=sum+temp;
        temp--;
    }
     printf("%d",sum);
    return 0;
}
output:
5
15

Here, we are calculating the sum of n natural numbers using the while loop.

Infinite while loop in c:
while(1){  
//statement  
}

If the expression passed in the while loop results in any non-zero value, then the loop will run an infinite number of times.

key points about while loop:
  • The statements within the while loop would keep on getting executed till the condition being tested remains true.
  • The condition being tested may use relational or logical operators.
  • The statement within the loop may be a single line or a block of statements.
  • It is not necessary that a loop counter must only be an int. It can even be a float.
  • In a while loop, the condition expression is compulsory.
  • Running a while loop without a body is possible.
  • There can be more than one conditional expression in the while loop.

Note: also read about Loops in C & Loops and its examples

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

4 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

5 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

10 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

10 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

11 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

11 months ago