Monday 22 January 2018

Loops

Loop control statements in C are used to perform looping operations until the given condition is true. Control comes out of the loop statements once condition becomes false.
The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
TYPES OF LOOP CONTROL STATEMENTS IN C:

There are 3 types of loop control statements in C language. They are,

·         for loop

·         while loop


·         do-while loop



for Loop:


 The syntax of for loop is:
for (initializationStatement; testExpression; updateStatement)
{
       // codes
}

How for loop works?

The initialization statement is executed only once.
Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test expression is true (nonzero), codes inside the body of for loop is executed and the update expression is updated.
This process repeats until the test expression is false.
The for loop is commonly used when the number of iterations is known.
To learn more on test expression (when test expression is evaluated to nonzero (true) and 0 (false)), check out relational and logical operators.


For Loop Code:


#include <stdio.h>
int main()
{
  int i;
  for(i=0;i<10;i++)
  {
      printf("%d ",i);
  }    
}

while loop:


The syntax of a while loop is:
while (testExpression)
{
    //codes
}

How while loop works?

The while loop evaluates the test expression.
If the test expression is true (nonzero), codes inside the body of while loop is executed. The test expression is evaluated again. The process goes on until the test expression is false.

When the test expression is false, the while loop is terminated.

While loop Code:

#include <stdio.h>
int main()
{
  int i=3;
  while(i<10)
  {
     printf("%d\n",i);
     i++;
  }   
}


do...while loop Syntax:

do
{
   // codes
}
while (testExpression);

How do...while loop works?

The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.







do while loop code:


#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=3);
return 0;
}

⇒C Compiler to run the above codes:https://goo.gl/bzuHcQ



Note: They all are Case Sensitive



No comments:

Post a Comment