Factorial of 1 to 7 Using For Loop


Explanation

A for loop can be used to calculate and display the factorial of numbers from 1 to 7. The factorial of a number is the product of all positive integers from 1 up to that number. In this program, the outer for loop selects each number from 1 to 7, while the inner for loop calculates its factorial. The result is displayed for every number.

How It Works?

  • Step 1: Declare the variables i, j, and fact.
  • Step 2: Use the outer for loop to generate numbers from 1 to 7.
  • Step 3: Before calculating each factorial, initialize fact = 1.
  • Step 4: Use the inner for loop to multiply fact by every number from 1 to the current value of i.
  • Step 5: Store the multiplication result in fact.
  • Step 6: After the inner loop finishes, display the current number and its factorial.
  • Step 7: Repeat the process until all numbers from 1 to 7 have been processed.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    int i, j;
    long int fact;

    clrscr();

    printf("Number\tFactorial\n\n");

    for(i = 1; i <= 7; i = i + 1)
    {

        fact = 1;

        for(j = 1; j <= i; j = j + 1)
        {

            fact = fact * j;

        }

        printf("%d\t%ld\n", i, fact);

    }

    getch();

}

Output

Number    Factorial

1    1
2    2
3    6
4    24
5    120
6    720
7    5040

Practice Exercises

Task 1: Write a C program using the for loop to display the factorial of numbers from 1 to 5.

Goal: Learn how to use nested for loops to calculate and display the factorial of multiple numbers.

💡 Hint: Use an outer for loop from 1 to 5. Before each calculation, initialize fact = 1. Use an inner for loop to multiply the numbers from 1 to the current value of i.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    int i, j;
    long int fact;

    clrscr();

    printf("Number\tFactorial\n\n");

    for(i = 1; i <= 5; i = i + 1)
    {

        fact = 1;

        for(j = 1; j <= i; j = j + 1)
        {

            fact = fact * j;

        }

        printf("%d\t%ld\n", i, fact);

    }

    getch();

}

Output
Number    Factorial

1    1
2    2
3    6
4    24
5    120
Explanation: The program uses an outer for loop to generate numbers from 1 to 5. For each number, the variable fact is initialized to 1. An inner for loop multiplies all numbers from 1 to the current value of i. After the factorial is calculated, the program displays the number along with its factorial.