C++ | Loops introduction

Introduction

This tutorial will give a introduction to loops in c++. There are 3 types of loops mainly, for loop, while loop and do-while loop. The first program prints 1 to 10 using for loop. The next one uses while loop. The last one uses do-while loop. You can extend the program by just replacing the 10 by the limit. So enjoy the program. Lets begin………………

Program to print 1 to 10 using for loop

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int i;
//loop statement
for(i=1;i<=10;i++)
{
cout<<i<<endl;
}

//get character
getch();
}

Output

1
2
3
4
5
6
7
8
9
10

Program to print 1 to 10 using while loop

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int i;
//loop statement
i=1;

while(i<=10)
{
cout<<i<<endl;
i++;
}

//get character
getch();
}

Output

1
2
3
4
5
6
7
8
9
10

Program to print 1 to 10 using do-while loop

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int i;
//loop statements

i=1;
do
{
cout<<i<<endl;
i++;
}while(i<=10);
//get character
getch();
}

Output

1
2
3
4
5
6
7
8
9
10

How does it work

The numbers are directly printed. no need to input.

Extending it

The program can be extended by replacing the 10 by the limit in the program. You can also let user enter the limit that can be saved in a variable and replaces 10 in the program. Go ahead and extend it…..

Explanation.

  1. Include ‘iostream.h’ and ‘conio.h’ files.
  2. Add void main.
  3. Start program by first clearing the screen.
  4. Declare the variable as int (name them as you want.)
  5. Add the loop.
  6. Print the number.

At the end

You learnt creating the c++ program of printing numbers from 1 to 10 using loops. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Advertisements

One thought on “C++ | Loops introduction

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s