The for Loop

The for loop in C++. Construction and Examples. The for loop is used when we have to run a program for a certain number of times.

Construction: The for loop

for (initial point; ending point; increment)
{
   Statement(s)
}


Q 1. Write a program in C++ that generates numbers from 1 to 10.

#include
using namespace std;
int main()
{
   for (int a=1; a<11; a++)
   {
     cout << a;
   }
}


This program shows numbers 1 to 10 horizontally because we have not written the endl to change the line.

Q 2. Write a program in C++ that generates numbers from 1 to 10 vertically.

#include
using namespace std;
int main()
{
   for (int a=1; a<11; a++)
   {
     cout << a << endl;
   }
}


Q 3. Write a program in C++ that generates the table of 2.

#include
using namespace std;
int main()
{
   for (int a=1; a<11; a++)
   {
     int table=2*a;
     cout << table << endl;
   }
}


Q 4. Write a program in C++ that generates even numbers between 1 and 51.

#include
using namespace std;
int main()
{
   for (int a=1; a<51; a++)
   {
     if (a%2==0)
     {
       cout << a << endl;
     }
   }
}


NOTE: Here we use % sign for division and two = signs (==) for is equal to.

Q 5. Write a program in C++ that generates odd numbers between 1 and 50.

#include
using namespace std;
int main()
{
   for (int a=1; a<51; a++)
   {
     if (a%2!=0)
     {
       cout << a << endl;
     }
   }
}


NOTE: Here we use != sign for not equal to.

Q 6. Write a program in C++ using the for loop that takes a number from the user and write table of that number.

#include
using namespace std;
int main()
{
   int number;
   cout << "Enter a number: ";
   cin >> number;
   for (int a=1; a<11; a++)
   {
     int table=number*a;
     cout << table << endl;
   }
}



Q 7. Write a program using for loop that shows the factorial of 4.
Remember: 4! = 4*3*2*1

#include
using namespace std;
int main()
{
   int fact=1;
   for (int a=4; a>0; a--)
   {
     fact=fact*a;
   }
     cout << fact << endl;
}



Q 8. Write a program using for loop that shows the factorial of 7.
Remember: 7! = 7*6*5*4*3*2*1

#include
using namespace std;
int main()
{
   int fact=1;
   for (int a=7; a>0; a--)
   {
     fact=fact*a;
   }
     cout << fact << endl;
}



Q 9. Write a program using for loop in C++ that take a number from user and shows factorial of that number.

#include
using namespace std;
int main()
{
   int fact=1;
   int number;
   cout << "Enter a Number: ";
   cin >> number;
   for (int a=number; a>0; a--)
   {
     fact=fact*a;
   }
     cout << fact << endl;
}

RELATED PAGES
- The for loop
- The while loop
- The do-while loop


Basic Financial Terms
Basic Financial terms in Corporate and Mathematical Finance
Financial Portfolio Analysis
Selection of assets, risk and return, and portfolio analysis
Financial Mathematics Notes
View the online notes for Financial Mathematics (CT1)
Financial Computing with C++
Learn Financial Computing with C++ step by step