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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…