loops (Iteration ) in C (Part 2)

 Example :- Program to check whether a input number is prime or not.

Prime number is a number which is divisible by only 1 and itself. So here we take a loop which will execute from 2 to (n-1) . if the number is divisible by any number in this range then it is not a prime number. and if not divisible by any number then loop will fully executed and loop variable will be equal to that number (i.e i=n) and in this condition number is a prime number.

#include<stdio.h>
int main()
{
int n,i;
printf(“Enter a numbern”);
scanf(“%d”,&n);
for(i=2;i<n;i++)
{
// if number is divisible by and
// other number
if(n%i==0)
{
printf(“%d is not a prime numbern”,n);
break;
}

}
// if loop will be fully executed
if(i==n)
printf(“%d is a prime numbern”,n);
return 0;
}

Output:-

Enter a number
5
5 is a prime number

Know more about break and continue :-     Click here

Nested loop:-

                      Whenever a looping construct written inside the body of another looping construct then this is called nesting of loop. Here the loop which is written inside is called the inner loop and the loop in which it is written is called outer loop .In other words we can say that inner loop is nested inside outer loop.

Example:-

#include<stdio.h>
int main()
{
int i,j;
//outer loop
for(i=0;i<2;i++)
{
// inner loop
for(j=0;j<2;j++)
{
}
}
return 0;
}

Explanation:-  For i=0 inner loop will execute for j=0 and 1 and again for i=1 inner loop will execute for j=0 and 1. so output is 

Outer loop
inner loop
inner loop
outer loop
inner loop
inner loop

Practice set of loop (Question for practice ) :-   Click here

<<Pre – Loops in C part-1                                            Next – Break and Continue in C>>

Recommended Post:

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

Key points:-

 MCQs:-

Leave a Reply

Your email address will not be published.