Sunday, March 31, 2019

Basics of Programming in C (part-5)


Hello Everyone!


Welcome to my 6th post. First of all, I should thank my parents, sister and my friends for supporting me and encouraging me.

In the previous post we have discussed about switch case statements.
Basics of Programming in C (part-4):

In this post we are going to discuss for loops and while loops. This post will take less than 5 minutes to completely read and to understand it.

Loop statements

Loop statements are used when we want to execute some line of code repeatedly. 
For loops are used when we know the number of times we run the loop. 
while loops are used when we are not sure about the number of times we run the loop.

Syntax:

FOR loop:

for(counter_variable initialization; for_condition; counter_variable increment/decrement )
{
        statements;
}


WHILE loop:

while(while_condition)
{
      statements;
}

Do WHILE loop:

do
{
      statements;
}while(while_condition);


In For loop parenthesis we have three parts. First is for initialization, Second is for condition and third is to increment or decrement  the counter variable.

First the variable is initialized. Then the condition is checked. If the condition evaluates to be true then compiler will execute the statements inside the loop block. after execution, it will increment/decrement the counter variable and will check the condition again. if condition is true then executes the block statements, otherwise the flow of control comes out of the loop and continues to execute the statements outside the loop.

Similarly in WHILE loop also, first the condition is evaluated. If it is true then statement inside the block are executed else loop is terminated. After executing the statements inside the loop compiler will check for the while condition.

In DO WHILE loops, the while condition is evaluated after executing the statements for the first time. Therefore, in Do while loops even if the condition evaluates to be false the statements are executed once.

Note: In both types of loops we need to take care of termination condition. Otherwise, the loop runs infinitely many times(😈).

Example:
Code:


Output:



That’s all for this post. In the next post we’ll discuss about  Functions.

Share it with your co-geeks and help me to improve by giving feedback in the comments section below.

Thank you.

 ABOUT ME






















MYSELF SUJITH SAGAR. I AM A B.tech SECOND YEAR  COMPUTER SCIENCE AND ENGINEERING STUDENT AT NATIONAL INSTITUTE OF TECHNOLOGY DELHI.

No comments:

Post a Comment

How Can You Test and Revert a Failover in Azure Cache for Redis Premium with Geo-Replication?

If you're using Azure Cache for Redis Premium with geo-replication across different regions, knowing how to test failover and revert it ...