For Loop

C++BasicsInputArithmeticConditionsLoops → 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 <iostream>
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 <iostream>
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 <iostream>
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 <iostream>
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 <iostream>
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 <iostream>
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 <iostream>
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 <iostream>
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 <iostream>
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;
}

NEXT: The while loop