Hello friends how are you, today in this blog i will teach you what is for loop statement, syntax of for loop , how for loop statement works and many programs using for loop statement in a very simple way.
Let's start
To run the particular block of code continuously until a required condition is fulfill is called looping. It is used to perform looping operation. When the condition will become false the execution of loop will be stopped.
👉Syntax
1.In for loop there are three part initialization, condition and increment/decrement.
2.Initialization part executes only once.
3.All the three parts of for loop are optional
👉Example 1
#include<stdio.h> int main() { for(int i=1;i<=10;i++) { printf("%d\n",i); } } ### Output ### 1 2 3 4 5 6 7 8 9 10
👉Example 2
#include<stdio.h> int main() { for( ; ; ) { printf("Hello "); } } /* ### output ### Hello Hello Hello .....Infinite times */
👉Example 3: Check given number is prime or not
Prime number is a whole number that have only two factors 1 and the number itself. Here in this program we will take two variable one for number and other for counting factors. After taking user input of number we will count number of factors by dividing number form 1 to number itself, After counting factors we will check if factors count is 2 means number is prime otherwise not prime.
#include<stdio.h>int main(){//variables declarationint no,factor_count=0;//taking user inputprintf("Enter any number\n");scanf("%d",&no);//loop for counting factorsfor(int i=1;i<=no;i++){if(no%i==0)//incrementing factor countfactor_count++;}//checking conditionif(factor_count==2)printf("Prime");elseprintf("Not Prime");}/*###Output###Run 1Enter any number94Not PrimeRun 2Enter any number53Prime*/
Request:-If you found this post helpful then let me know by your comment and share it with your friend.
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all.
If you have not subscribed my website then please subscribe my website.
Try to learn something new and teach something new to other.
Thanks.
0 Comments