Loops make the code simple and it helps the coder by reducing the length of the code. Loops are used to repeat some parts of the program.They basically repeat a block of code n number of times. There are 3 types of loops, they are
for
while
do while
For loop Syntax
for( initialisation ; condition ; updation) {// a block of code}
For example a for loop to repeat a block of code 5 times
for( int i=0; i<5; i=i+1) { printf("\tThe Ocean is Blue\n" );}
Q1 Let's write a program to print a text multiple times in C and input the number of times the text is repeated by the user.
#include <stdio.h>
int main(){
int a;
printf("Enter the number of times you want to print the text\n");
scanf("%d",&a);
for (int i=0;i<a;i=i+1)
{printf("The Earth is our Home\n");}
}
//this code can also be written as
//for (char ch='a'; ch<='z';ch++)
//{printf("%c\n",ch);
Here you should not take t<=a because the compiler starts the count from 0 so the for loop will run once more if you take t<=a. Output
Q2 A program to print all the alphabet in the English language in caps and small caps in C. (To do this program you need to take ASCII numbers of a to z in small caps. The ascii value represents the character variable in numbers)
#include <stdio.h>
int main(){
{
int i=97, j=65;
int m;
for ( m=0;m<26;m=m+1)
{printf("%c , ",i+m);}
for(int n=0;n<26;n=n+1)
{printf("%c , ",j+n);}
return 0;
}
}
Output
Instead of typing i=i+1 you can type increment operator i++ decrement operator i-- this makes the code simpler.
While Loop
Syntax : while(condition){work;} Example : int i=1; while(i<=5) { print("\d,i); i++ }
Q3 Write a program to print hello 5 times using while in C.
#include <stdio.h>
int main(){
{
int i=1;
while(i<=5){printf("Hello\n");
i++;}
return 0;
}
}
Output
Q4 Write a program to print numbers from 0 to n if n is given by the user Same code can be done in for in C.
#include <stdio.h>
int main(){
{
int i;
int m=0;
printf("Enter\n");
scanf("%d",&i);
while(m<=i)
{printf("Hello\n");
m++;}
return 0;
}
}
Output
Do While Loop
Syntax
do{work} while condition
In this, the work is done once then the condition is observed by the compiler.
Q5 Write a program to print from 5 to 1 using do while in C.
#include <stdio.h>
int main()
{
int i=5;
do{
printf("\t%d\n",i);
i--;
} while(i>=1);
return 0;
}
Output
Q6 Print the sum of the first n natural numbers also print them in reverse.
#include <stdio.h>
int main()
{
int n;
printf("Enter a number=\n");
scanf("%d",& n);
int sum=0;
for(int i=1;i<=n;i++){
sum=sum+i;}
printf("sum is %d\n",sum);
for (int i=n;i<=1; i--)
{printf("%d\n", i++);}
return 0;
}
Hope you enjoyed learning Loops, this concept makes your programming journey very easy. Hope this blog was helpful.
Thank you...