Let us take a look at the various ways to use loops in c.
An infinite loop in c does not end, in other words, its condition never becomes true and keeps on updating forever. It is also known as an endless loop or indefinite loop.
#include <stdio.h>
int main() {
for(;;)
{
printf("\nCoderzpy!");
}
return 0;
}
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Coderzpy!
Here for(;;) is an infinite loop where there is no initialization, condition, or updating statement, therefore the loop becomes endless, and it continues forever.
Need for infinite loop:
Here we are calculating the sum of n natural numbers using for loop.
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Enter a positive integer: 10
Sum = 55
For checking prime numbers, calculate the number of factors of a number and check if it is greater than or equal to 2.
#include <stdio.h>
int main() {
int n,i,count=0;
scanf("\n%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
{
printf("%d is a prime number.",n);
}
else
{
printf("%d is not a prime number.",n);
}
return 0;
}
11
11 is a prime number.
Note: also read about Decision-Making in C & Loops in C
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…