C Tutorial – for loop, while loop, break and continue
In every programming language, thus also in the C programming language, there are circumstances were you want to do the same thing many times. For instance you want to print the same words ten times. You could type ten printf function, but it is easier to use a loop. The only thing you have to do is to setup a loop that execute the same printf function ten times.
There are three basic types of loops which are:
- “for loop”
- “while loop”
- “do while loop”
The for loop
The “for loop” loops from one number to another number and increases by a specified value each time.
The “for loop” uses the following structure:
for (Start value; continue or end condition; increase value)
statement;
Look at the example below:
#include<stdio.h>
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf ("Hello\n");
printf ("World\n");
}
return 0;
}
Note: A single instruction can be placed behind the “for loop” without the curly brackets.
Note: For those who don’t know printf or need to know more about printf format specifiers, then first a look at our printf C language tutorial.
Let’s look at the “for loop” from the example: We first start by setting the variable i to 0. This isย where we start to count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must be increased by one (i++).
In the example we used i++ which is the same as using i = i + 1. This is called incrementing. The instruction i++ adds 1 to i. If you want to subtract 1 from i you can use i--
. It is also possible to use ++i or --
i. The difference is is that with ++i (prefix incrementing) the one is added before the “for loop” tests if i < 10. With i++ (postfix incrementing) the one is added after the test i < 10. In case of a for loop this make no difference, but in while loop test it makes a difference. But before we look at a postfix and prefix increment while loop example, we first look at the while loop.
The while loop
The while loop can be used if you don’t know how many times a loop must run. Here is an example:
#include<stdio.h>
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%d\n", counter);
}
return 0;
}
Let’s take a look at the example: First you must always initialize the counter before the while loop starts ( counter = 1). Then the while loop will run if the variable counter is smaller then the variable “howmuch”. If the input is ten, then 1 through 10 will be printed on the screen. A last thing you have to remember is to increment the counter inside the loop (counter++). If you forget this the loop becomes infinitive.
As said before (after the for loop example) it makes a difference if prefix incrementing (++i) or postfix incrementing (i++) is used with while loop. Take a look at the following postfix and prefix increment while loop example:
#include<stdio.h>
int main(void) {
int i;
i = 0;
while(i++ < 5) {
printf("%d\n", i);
}
printf("\n");
i = 0;
while(++i < 5) {
printf("%d\n", i);
}
return 0;
}
The output of the postfix and prefix increment example will look like this:
1
2
3
4
5
1
2
3
4
i++ will increment the value of i, but is using the pre-incremented value to test against < 5. That’s why we get 5 numbers.
++i will increment the value of i, but is using the incremented value to test against < 5. That’s why we get 4 numbers.
The do while loop
The “do while loop” is almost the same as the while loop. The “do while loop” has the following form:
do
{
do something;
}
while (expression);
Do something first and then test if we have to continue. The result is that the loop always runs once. (Because the expression test comes afterward). Take a look at an example:
#include<stdio.h>
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
do
{
counter++;
printf("%d\n", counter);
}
while ( counter < howmuch);
return 0;
}
Note: There is a semi-colon behind the while line.
Break and continue
To exit a loop you can use the break statement at any time. This can be very useful if you want to stop running a loop because a condition has been met other than the loop end condition. Take a look at the following example:
#include<stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
if ( i == 10)
break;
}
return 0;
}
In the example above, the while loop will run, as long i is smaller then twenty. In the while loop there is an if statement that states that if i equals ten the while loop must stop (break).
With “continue;” it is possible to skip the rest of the commands in the current loop and start from the top again. (the loop variable must still be incremented). Take a look at the example below:
#include<stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to see\n");
}
return 0;
}
In the example above, the printf function is never called because of the “continue;”.
That was all for now. Don’t forget to make some example programs of your own, just for practice!
Update: You can also take a look at one of the following example(s) that also use for loops and while loops:
@jack goh: I’m not exactly sure what you are asking, but I assume something like this piece of code –
#include<stdio.h>
#define TRUE 1
#define FALSE 0
int main() {
int year;
printf(“Please enter a year (example: 1999) : “);
scanf(“%d”, &year);
if(year% 4 == FALSE && year%100 != FALSE || year%400 == FALSE) {
printf(“%d is a Leapyear. \n”, year);
} else {
printf(“%d is NOT a Leapyear. \n”, year);
}
return 0;
}
Also see the tutorial: How to make a calendar in C language for additional information.
I hope that this helps!
(#include )
int main ()
{
float Kilogram;
scanf(“%f”, &Kilogram);
stdin;
float Pounds = Kilogram * 2.20046;
printf(“%f Kilograms = %f Pounds.\n”, Kilogram, Pounds);
float POUNDS;
scanf(“%f”, &POUNDS);
stdin;
float KILOGRAMS = POUNDS / 2.20046;
printf(“%f POUNDS = %f KILOGRAMS”, POUNDS, KILOGRAMS);
return 0;
}
Write a program to calculate the sum of all the numbers less than a given number n.
ex: output
Enter number : 3
6
Enter number : 5
15
really its so amazing for learn….
it was really helpfull ๐
nice
hey ..could any body write a function to solve simultaneous equations ..
in have great difficulties with this
Hello sir
Can you please help me to output the sum of numbers from 1 to 15 (inclusive) and sum of odd numbers from 15-45 (inclusive) ?
@Rakshith kumar:
#include
int main()
{
int i=1,j=10;
while(j>1)
{
if(i<11)
{
printf("%d ",i);
++i;
}
else
{
–j;
printf("%d ",j);
}
}
}
good job sir
While testing on continue; i discovered it could be used to skip a certain number too, like when using this:
i = 0;
while ( i++ < 20 )
{
if ( i == 16 ) continue;
printf("number %d\n", i );
}
it will skip the number 16 but will print every number in the range 1 to 20
sir this is very nice tutorial by you
thankyou
void main(void)
{
for(a=2;a<=400;a+2)
{
printf("%d",a);
}
i m not getting the series of even num help me???? output showing only 400 nd its blinking !! :S
#include
void main(void)
{
int a;
for(a=2;a<=400;a+2)
{
printf("%d",a);
}
}
your simple error is only on the declaration of ‘a’ that must be an integer.otherwise the compiler doesn’t know what variable ‘a’ is.
it was good n easy..
plzz tell the purpose of getch and also explain nested loops if possible..
thankyou
nice gather
#include
using namespace std;
int main()
{
int n,factorial=1;
cout<>n;
for(int i=n;i>0;i–){
factorial=i*factorial;
}
cout<<factorial<<endl;
return (0);
}
can all for loops be rewritten using a while loop?
Thanks so much for your tutorials! I’m doing a basic course in C Code, but it’s taught in Japanese so these are really saving my grade!
I have a question: I’m supposed to build a program where I enter an integer below a hundred, and all numbers smaller than said integer and containing the number “3” appear on the screen (etc, if I enter 14, the numbers “3, 13” should appear).
However, there’s something wrong with my code, please help! Thank you!
The code:
#include
int main(int argc, const char * argv [])
{
int wholenumber;
printf(“็พไปฅๅ ใฎๆดๆฐใๅ ฅๅใใฆใใ ใใ\n”);
scanf_s(“%d”, &wholenumber);
while(0 <wholenumber)
{
wholenumber–;
while(0 < wholenumber){
wholenumber = 3 %10;
wholenumber = 3 /10;
if (wholenumber == 3);
{printf("%3d",wholenumber);}
}
}
return 0;
}
piz clear these concept also…
while(n!=0)
{
n/=10
++count
}
#include
int main()
{
int i;
for (i=400;i>=1;i–)
{
printf(“%d\n”,i);
}
return 0;
}
y can’t i see 400, the output is starting from 298 and continues till printing 1
Thx for this! I understand loops clearly
Program for 12345678910987654321
#include
main()
{
int i,j;
for(i=1,j=9;i=1;i++){
if(i<=10)
printf("%d",i);
else{
printf("%d",j);
j–;
}
}
getch();
}
how to make 5 * diomond?
Excuse me!
How shall I program two integers then display the factors of the integers and then get their greatest common factors(GCF)…
May I ask anyone to help me?
Thank you so much! I had been looking so long for a proper C tutorial for beginners. Your explanations and examples make it so much easier to understand.
hi, sir i want a loop statement then are perform a working
that are i know you loop dry run
can we possibly write this way.
for(scanf(“%d”, &i)); i<10; i++)
printf("%d",i);
and also this way
for(i = 1; i<10; printf("%d",i++))
or if i’ll use
for(i=0;i++<10;)
printf("%d\n",i);
what will first done in for statement (i++<10) incrementation or comparison
IT WAS HELPFULL & EASIER TO UNDERSTAND….
#include
int main()
{
int num=3,i,a;
a=0;
for(i=1;i<=num;i++) {
a=a+2;
printf("%d ",a);
}
printf("\n");
for(i=1;i<=num;i++) {
a=a+4;
printf("%d ",a);
}
printf("\n");
for(i=1;i<=num;i++) {
a=a+6;
printf("%d ",a);
}
return 0;
}
/*the ans of M.Salman question*/
/*the series of even no.*/
#include
int main()
{
int num;
int n;
//printf(“enter ur number: “);
//scanf(“%d”,&num);
for(n=0;n<=100;n++){
if(n%2==0){
printf("%d ",n);
}
printf("\n");
}
return 0;
}
thanks for the codes i will study this codes
Any one tell me i cant understand the difference between ++i and i++.Please explain in the way of easy understanding.
@ Mr. J.Aravind Amuthuraj
i++ and ++i both are similar…
but it depends upon the situation… when you are using them,
lets take an example,
#include
int main()
{
int x = 10,y;
int v = 10,z;
y = ++x + x++;
z = ++v + ++v;
printf(“x = %d y = %d”,x,y);
printf(“\n\nv = %d z = %d”,v,z);
return 0;
}
OUTPUT – x = 12 y = 22
v = 12 z = 23
// here as you can see, the values of y and z are changed
because of the difference of position of ‘++’ increment operator…
if ++ operator is after the variable then it is executed later… and if ++ operator is before the operator then it is executed first..
so the value of x is first incremented to 11 and as x = 11 therefore the x++ will result as 11…
and addition of 2 eleven is 22 so y = 22,
but in z the value of v is ++v = 11 and then as v = 11 so again ++v = 12
therefore addition of ++v + ++v will be 23
hence z will result in 23.
i hope you understand the difference between ++x and x++. ๐
A B C D E D C B A
A B C D D C B A
A B C C B A
A B B A
A A
code for this one
#include
int main( )
{
int i,j,k=65,l;
for(i=5;i>0;i–)
{
for(l=5;l>i;l–)
{
printf(” “);
}
for(j=0;j<i;j++)
{
printf("%c",k+j);
}
for(j=0;j<i;j++)
{
printf("%c",k-j+i-1);
}
printf("\n");
}
getchar();
return 0;
}
dear Rakshith kumar:
i have the answer to your problem:
#include
#include
void main()
{
for(int i=1;i<=10;i++)
{
cout<=1;i–)
{
cout<<i;
}
getch();
}
are,
for(i=1;i<=5;i++)
and for(i=1;i++,<= operators because i tend to make mistakes when = are inserted in loops.
also,for(int i=0;i<10;i++) prints from 0 whereas for(i=1;i++<=5;) prints from 2 to 6.
i mean if i is initialized from 1 it should start from 1.
Really helpful sir
can we use the while loop for true or false function?
I just found this site, and well organized and useful, thank you!!!