Learning While LOOP
Submitted by moazkhan on Tuesday, July 15, 2014 - 08:42.
While LOOP
In this part you will learn: 1. While LOOP 2. C syntax 3. Showing output In this tutorial I will teach you how to use while loops in C. We have already covered for loops and now we know what are loops What is a WHILE LOOP ? First of all we will talk about what is while loop. For a loop we need three statement initialization, condition and increment. In a while loop we only write the condition within the round brackets and increment within the body of the loop. We initialize the variable outside the loop. Checking for a prime number Basic Step: Open Dev C++ then File > new > source file and start writing the code below.- #include<stdio.h>
- #include<conio.h>
- int main()
- {
- int num,i=2;
- while ( i<num){
- if (num %i==0 ){
- break;
- }
- i+=1;
- }
If the loop is finished without the condition becoming true and the incremented value becomes equal to the number then that number is a prime number. Otherwise not.
Execute > compile
then Execute > run
Output
SUM OF DIGITS
File > new source file
For calculating the sum of digits of number we need three variables number, temporary variable and sum. We take the input in number.
Now we write the loop condition that run until the number is greater than 0 because we will start separating the digits form Least significant to most significant. We take the remainder of number with 10 to separate the digit and simple store it in our temp variable and add that variable to sum until the number is greater than 0. In the end we simply print the sum and return.
Execute > compile
then Execute > run
Output:
Add new comment
- 94 views