How to Choose Between do-while and while Loops in C Programming

«
»

This C Tutorial explains the difference between do-while and while loops in C Programming.

In do-while loop, condition is always tested after the the execution of the iteration and if condition fails, loop terminates. Therefore, do-while loop executes at least one iteration before termination if condition fails in first iteration! For example:

#include <stdio.h>
 
int main(void)
{
    int counter = 0;
 
    do {
        /* loop executes just once printing the value 0 */
 
        printf("counter is %d\n", counter);
    } while(counter++ != 0);
 
    return 0;
}

In while loop, condition is checked before execution of each iteration and as condition fails, loop terminates. For example:

advertisement
#include <stdio.h>
 
int main(void)
{		
    int counter = 0;
 
    /* loop terminates in the beginning of first iteration */
 
    while (counter++ != 0)
        printf("counter is %d\n", counter);
 
    /* here counter val is printed as 1 */
 
    printf("counter is %d\n", counter);
    return 0;      
}

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn