Looping statements in C

Hello coders! Welcome back!

Today will look into looping statements used in C language.

WHY DO WE NEED LOOPING STATEMENTS? 
→ Imagine we humans doing a particular task repeated number of times. At some stage, we commit a mistake. Hence we command computers to a particular task repeatedly so that we humans won't make a mistake.

A looping statement repeats the set of instructions as mentioned by the programmer.

1] While loop- 

Let's look at the syntax- 

The expression mentioned along with while keyword, if it evaluates to 'True' the following statements are evaluated. If it evaluates to 'False' then it comes out of the loop. 

let's look into code- 

Here the value hold by 'n' is equal to 5. 
Any value other than zero is treated as true. 
In printf statement, we are trying to print the values of 'n'. And then we decrement the value of 'n'. 
When 'n' becomes zero, it comes out of the loop. And won't print the value '0' on command prompt.

2] for loop- 

Syntax- 

Here in for loop, we initialize the variable. 
The variable value gets compared with the condition. 
If it is 'true' then following statements are executed. 
Later the variable values get incremented or decremented depending on the signs mentioned.
Once the condition fails, it comes out of the loop.
I have shown the control flow with arrows. 

Next, let's jump into an example. Will take the same example as mentioned above

You can see that number of instructions are reduced and we get the same output. This is more efficient. 

3] do-while- 

Let's look into syntax- 

So what's the difference between do-while and while looping statements? And when to use while and do while statements? 
→ See, the syntax carefully. In while looping statements we are checking the condition first and then executing the statements. 
But, in do-while statements, we check the condition at last. 
So, when the user wants to execute the statement at least once then use do-while looping statements. 

let's look the difference with the help of code-   

You can see that do-while looping execute the statement at least once. Whereas while loop won't execute the statements if the condition fails. We know that zero is treated as false. 
Important note → In do-while loop place a semicolon at the end. 

This is it for this blog!
Hope so you got a clear idea about looping statements used in C.
If any doubts drop a comment.

Happy learning!



Comments

Popular post