Thursday, 10 January 2019

What are the Loops in C?

Before knowing what are the loops in C? or how many types of loops available in the C programming language, it is important to know why we need loops in C? Suppose, 

printf ("Welcome to C Programming ");

I have to print above statement 100 times, it is easy to write above statement 100 times, Not at all,  this is a small example but when you design software, 1000 times or maybe more than that you need to write a statement or instructions which is not possible to write it is time-consuming that's why we need  loops in C.

           In computer programming, a loop instruction is a sequence i.e. continuously repeated until it reaches a certain position. Generally, a certain process is done, such as getting an item of data and changing it, and then some conditions are checked as if the counter has reached the specified number. If not, then the next instruction in the sequence is the instructions to return to the first instruction and repeat the instructions. 

What is the difference between a conditional statement and looping statement in C?

  • The conditional statement will execute only once if the situation is correct while the loop will execute repeatedly unless the situation is false.

For example

Conditional statement                                         Looping statement

int a = 10;                                                                int a= 5;
if (a = = 10)                                                             While (a <=5)
{                                                                               {
printf ("a is equal to 10");                                        printf ("executed ");
}                                                                                a--;
else                                                                           }
printf ("a is not equal to 10");

In a conditional statement, condition "a==10" is true then the output is "a is equal to 10" otherwise the output is "a is not equal to 10".
     In looping statement, we initialize a=5, check the condition in while loop if the value of a is less than or equal to 5 then print executed otherwise it terminates from the loop.

Types of Loops in C

1. Entry Controlled Loops in C: In this type of loop, the test condition is checked before entering into the loop body. If the test condition is not true, then the body of the loop will not be executed.

Loops in C
Entry Controlled Loops in C

For Example

FOR Loop and While Loop

2. Exit Controlled Loops in C: In this type of loop, the test condition is checked at the end of the loop of the body that means loop body will execute unconditionally at least once.

Loops in C
Exit Controlled Loops in C

For Example

Do-While Loop

  • Exit controlled loops and entry controlled loops in C is also known as post-test and pre-test loops in C.