C++ program to print the natural numbers using for loop
codeaft.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
codeaft@codeaft:~$ g++ codeaft.cpp
codeaft@codeaft:~$ ./a.out How many numbers you want to print 10 1 2 3 4 5 6 7 8 9 10 codeaft@codeaft:~$
C++ program to print the natural numbers using while loop
codeaft.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
codeaft@codeaft:~$ g++ codeaft.cpp
codeaft@codeaft:~$ ./a.out How many numbers you want to print 10 1 2 3 4 5 6 7 8 9 10 codeaft@codeaft:~$
Comments and Reactions