In this part you will learn:
1. Do while LOOP
2. C syntax
3. Showing output
In this tutorial I will teach you how to use do while loops in C. We have already covered for loops and now we know what are loops.
In this tutorial I will teach you how to use a Do while loop in C. We have previously covered how to use a and now we know how loops work.
What is a DO WHILE LOOP?
A Do while loop is somewhat similar to a While loop. It has there necessary statements initialization, condition and increment. The initialization is done outside the body of the loop, the condition comes with the while part in round brackets and increment is done inside the body of the loop. In a do while loop the body of the loop is executed first and then afterwards the condition of the loop is tested. If it is true, the code executes the body of the loop again.
Open Dev C++ then File > new > source file and start writing the code below.
These are the header files that we need for coding. The main header is stdio.h which provides us with most of the functions for coding in C and the second header files is just for using a function which can pause the screen until the user hits any key.
- int main()
- int num,fact=1;
For finding the factorial of a number we take input of a number and Inside the loop, we multiply the counter times the accumulated number up to that point. In this case the accumulator is ‘fact’.
SUM OF ALL THE NUMBERS UNTIL USER ENTER ZERO
File > new source file
- int main()
- Int sum=0,num,totalnumbers=0;
Now we write the body of the loop which takes a number from user and adds it to the accumulator. Then the condition checks if the user has entered 0 it should stop taking any more numbers from the user and break out of the loop. Otherwise it should keep going on taking numbers from the user and adding them.
Lastly we printed the total number of numbers user entered except the 0 at the end. We should not count the 0 because its our exit condition. And we printed the sum.
Execute > compile
then Execute > run
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.