C++ program to print the natural numbers using for loop
kw.cpp
#include <iostream>
using namespace std;
int main()
{
    int n, i;
    cout<<"How many numbers you want to print ";
    cin>>n;
    for (i = 1; i <= n; i++)
        cout<<i<<" ";
    cout<<"\n";
    return 0;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out How many numbers you want to print 10 1 2 3 4 5 6 7 8 9 10 kodingwindow@kw:~$
C++ program to print the natural numbers using while loop
kw.cpp
#include <iostream>
using namespace std;
int main()
{
    int n, i;
    cout<<"How many numbers you want to print ";
    cin>>n;
    i = 1;
    while (i <= n)
    {
        cout<<i<<" ";
        i++;
    }
    cout<<"\n";
    return 0;
}
Output
kodingwindow@kw:~$ g++ kw.cpp
kodingwindow@kw:~$ ./a.out How many numbers you want to print 10 1 2 3 4 5 6 7 8 9 10 kodingwindow@kw:~$
Advertisement