Loop is doing something multiple times.
Syntax:
for( how many times )
{
//do something
}
it is pretty easy let's try to print hello world 10 times it should look like that:
for(10)
{
printf("hello world");
}
Hmmm that's right but not in syntax to tell the computer do something multiple times you should make a counter.
what is a counter?
a variable that counts as much as you want.
The for loop : consists of 4 main parts "for(i=0;i<10;i++)"
make a variable as a counter like i in our example.
- define your counter start "i=0"
- define your counter end "i<10" which means don't exceed 9.
- define your step "i++" which means let i increases by 1 each step.
- the code that will be repeated.
#include<stdio.h>
int main()
{
int i;
for(i=0;i<10;i++) // as mentioned before no need for {} if it was only one line
printf("Hello World\n");
return 0;
}output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
can i replace the start and end of the counter?
yes for sure you can put whatever end and whatever start to make it move 10 steps.
like i=1 and end will stop when i = 10 which mean that condition will be i<11.
but what is the sequence of implementing the for loop ?
for(1: i=0; 2: i<10 ; 4: i++)
3: printf("Hello World\n");
- define counter start i=0 //done only once
- check if counter exceed its limit or not i<10 //done 10 times
- code to be repeated.
- increment the counter by 1. //done 10 times
#include<stdio.h>
int main()
{
int i;
for(i=1;i<101;i++)
printf("%d\n",i);
return 0;
}
modify the previous program to ask the user to enter the end of the counter before counting.
#include<stdio.h>
int main()
{
int i,end;
printf("please enter a number\n");
scanf("%d",&end);
for(i=0;i<end+1;i++)
printf("%d\n",i);
return 0;
}
why we made the condition i<end+1 ?
because the counter stop counting when the condition went false which means when i equals to end that's means the last number won't be printed so we changed the end.
now modify the program to take the start and the end from the user
#include<stdio.h>
int main()
{
int i,end,start;
printf("please enter two number\n");
scanf("%d%d",&start,&end);
for(i=start;i<end+1;i++)
printf("%d\n",i);
return 0;
}
Practice :
write a program that takes two number from user and print the odd numbers in between.
input:
1 10
output:
1 3 5 7 9
thanks so much :) salamo3alikom :)
No comments:
Post a Comment