EZ Notes Logo

EZNotes

🎯 Aim

To write a C/C++ program that takes a number as input from the user and calculates its factorial using the while loop.

🛠️ What You Need

  • Visual Studio Code or any C/C++ compiler
  • Knowledge of while loops and arithmetic operations

📖 Introduction

The factorial of a number (denoted by n!) is the product of all positive integers from 1 to n.

Formula: n! = n × (n-1) × (n-2) × ... × 1

For example:

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 4! = 4 × 3 × 2 × 1 = 24
  • 3! = 3 × 2 × 1 = 6
  • 0! = 1 (by definition)

You will use:

  • scanf() — to take the number from the user
  • A while loop — to multiply numbers from 1 to n
  • A factorial variable — to store the result
  • printf() — to display the result
💡 Tip: Factorial is used in many mathematical problems like permutations, combinations, and probability. The factorial of 0 is defined as 1.

📝 Steps

Step 1: Write the Program

  1. Open VS Code or any C compiler.
  2. Create a new file named factorial_while.c.
  3. Write the following code:
/* Practical 45: Program to find factorial using while loop */ #include <stdio.h> int main() { int num, i = 1; long long factorial = 1; // Use long long for large numbers // Take input from user printf("Enter a positive integer: "); scanf("%d", &num); // Check if the number is negative if (num < 0) { printf("❌ Factorial of a negative number does not exist.\n"); } else { /* ============================================ Using while loop to calculate factorial ============================================ */ while (i <= num) { factorial = factorial * i; i++; } // Display the result printf("\n========== FACTORIAL RESULT ==========\n"); printf("Number: %d\n", num); printf("Factorial: %d! = %lld\n", num, factorial); printf("=======================================\n"); } return 0; }

Step 2: Explanation of the Code

  1. #include <stdio.h> — Includes the standard input/output library.
  2. int num, i = 1; — Declares num for user input and initializes i to 1.
  3. long long factorial = 1; — Declares factorial as long long to handle large numbers, initialized to 1.
  4. scanf("%d", &num); — Reads the number from the user.
  5. if (num < 0) — Checks if the number is negative.
  6. while (i <= num) — The while loop multiplies numbers from 1 to num.
  7. factorial = factorial * i; — Multiplies the current value of factorial by i.
  8. i++; — Increments the counter.

Step 3: Save, Compile, and Run

  1. Save the file (Ctrl + S).
  2. Open the terminal and compile using the command:
gcc factorial_while.c -o factorial_while

Run the program:

./factorial_while

Sample Input & Output:

Enter a positive integer: 5 ========== FACTORIAL RESULT ========== Number: 5 Factorial: 5! = 120 =======================================
Enter a positive integer: 7 ========== FACTORIAL RESULT ========== Number: 7 Factorial: 7! = 5040 =======================================
Enter a positive integer: -3 ❌ Factorial of a negative number does not exist.

Step 4: Modify the Program

  1. Using while loop to display multiplication steps: Print the multiplication process.
  2. Calculate factorial of numbers up to 20: Test with larger numbers.
  3. Use do-while loop: Replace while with do-while.
/* Modified: Display multiplication steps */ while (i <= num) { factorial = factorial * i; printf("Step %d: %d! = %lld\n", i, i, factorial); i++; }

📊 While Loop Execution for Factorial

Iteration i Value Condition i <= 5 Factorial Before Factorial After
1 1 ✅ True 1 1
2 2 ✅ True 1 2
3 3 ✅ True 2 6
4 4 ✅ True 6 24
5 5 ✅ True 24 120
6 6 ❌ False - (Loop ends)

📊 Factorial Table

n n!
01
11
22
36
424
5120
6720
75040
840320
9362880
103628800
1139916800
12479001600
136227020800
1487178291200
151307674368000
1620922789888000
17355687428096000
186402373705728000
19121645100408832000
202432902008176640000

📊 Alternative Methods

/* Alternative 1: Using for loop */ long long factorial = 1; for (int i = 1; i <= num; i++) { factorial = factorial * i; }
/* Alternative 2: Using do-while loop */ int i = 1; long long factorial = 1; do { factorial = factorial * i; i++; } while (i <= num);
/* Alternative 3: Using recursion */ long long factorial(int n) { if (n == 0 || n == 1) return 1; else return n * factorial(n - 1); }

📊 Observations

  • The program successfully takes a number as input from the user.
  • The while loop iterates from 1 to num, multiplying each number.
  • The factorial variable is initialized to 1 because multiplying by 1 doesn't change the result.
  • The program handles negative numbers by displaying an error message.
  • The factorial of 0 is 1 (handled by the loop not running).
  • Using long long allows the program to handle large factorial values (up to 20!).

✅ Result

You have successfully written a C program that calculates the factorial of a number entered by the user using the while loop. You have learned how to use loops to perform repetitive multiplication.

📌 Important: The factorial of a number grows very quickly. For numbers greater than 20, the factorial exceeds the range of long long data type. For very large numbers, you would need to use libraries that support big integers.
💡 Tip: You can also calculate factorial using recursion. Recursion is a technique where a function calls itself. The factorial function can be written as factorial(n) = n * factorial(n-1) with factorial(0) = 1 as the base case.

🎯 مقصد

ایک C/C++ پروگرام لکھنا جو صارف سے ایک عدد ان پٹ کے طور پر لے اور while لوپ کا استعمال کرتے ہوئے اس کا فیکٹوریل حساب کرے۔

🛠️ آپ کو کیا چاہیے

  • Visual Studio Code یا کوئی بھی C/C++ کمپائلر
  • while لوپ اور ریاضی کے عمل کی معلومات

📖 تعارف

کسی عدد کا فیکٹوریل (جسے n! سے ظاہر کیا جاتا ہے) 1 سے n تک کے تمام مثبت اعداد کی ضرب ہے۔

فارمولا: n! = n × (n-1) × (n-2) × ... × 1

مثال کے طور پر:

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 4! = 4 × 3 × 2 × 1 = 24
  • 3! = 3 × 2 × 1 = 6
  • 0! = 1 (تعریف کے مطابق)
💡 مشورہ: فیکٹوریل ریاضی کے بہت سے مسائل میں استعمال ہوتا ہے جیسے ترتیب، مجموعہ، اور احتمال۔ 0 کا فیکٹوریل 1 ہے۔

📝 اقدامات

پہلا قدم: پروگرام لکھیں

  1. VS Code یا کوئی بھی C کمپائلر کھولیں۔
  2. factorial_while.c نام کی ایک نئی فائل بنائیں۔
  3. نیچے دیا گیا کوڈ لکھیں:
/* Practical 45: Program to find factorial using while loop */ #include <stdio.h> int main() { int num, i = 1; long long factorial = 1; // Use long long for large numbers // Take input from user printf("Enter a positive integer: "); scanf("%d", &num); // Check if the number is negative if (num < 0) { printf("❌ Factorial of a negative number does not exist.\n"); } else { /* ============================================ Using while loop to calculate factorial ============================================ */ while (i <= num) { factorial = factorial * i; i++; } // Display the result printf("\n========== FACTORIAL RESULT ==========\n"); printf("Number: %d\n", num); printf("Factorial: %d! = %lld\n", num, factorial); printf("=======================================\n"); } return 0; }

دوسرا قدم: کوڈ کی وضاحت

  1. #include <stdio.h> — معیاری ان پٹ/آؤٹ پٹ لائبریری شامل کرتا ہے۔
  2. int num, i = 1; — num صارف کے ان پٹ کے لیے اور i کو 1 سے شروع کرتا ہے۔
  3. long long factorial = 1; — بڑے اعداد کو ہینڈل کرنے کے لیے factorial کو long long کے طور پر اعلان کرتا ہے، 1 سے شروع کرتا ہے۔
  4. scanf("%d", &num); — صارف سے عدد پڑھتا ہے۔
  5. if (num < 0) — چیک کرتا ہے کہ آیا عدد منفی ہے۔
  6. while (i <= num) — while لوپ 1 سے num تک اعداد کو ضرب کرتا ہے۔
  7. factorial = factorial * i; — factorial کی موجودہ قیمت کو i سے ضرب کرتا ہے۔
  8. i++; — کاؤنٹر کو بڑھاتا ہے۔

تیسرا قدم: محفوظ کریں، کمپائل کریں اور چلائیں

  1. فائل کو محفوظ کریں (Ctrl + S)۔
  2. ٹرمینل کھولیں اور نیچے دی گئی کمانڈ استعمال کرتے ہوئے کمپائل کریں:
gcc factorial_while.c -o factorial_while

پروگرام چلائیں:

./factorial_while

نمونہ ان پٹ اور آؤٹ پٹ:

Enter a positive integer: 5 ========== FACTORIAL RESULT ========== Number: 5 Factorial: 5! = 120 =======================================

📊 فیکٹوریل جدول

n n!
01
11
22
36
424
5120
6720
75040
840320
9362880
103628800

📊 مشاہدات

  • پروگرام کامیابی سے صارف سے ایک عدد ان پٹ کے طور پر لیتا ہے۔
  • while لوپ 1 سے num تک تکرار کرتا ہے، ہر عدد کو ضرب کرتا ہے۔
  • factorial متغیر کو 1 سے شروع کیا گیا ہے کیونکہ 1 سے ضرب کرنے سے نتیجہ تبدیل نہیں ہوتا۔
  • پروگرام منفی اعداد کو غلطی کا پیغام دکھا کر ہینڈل کرتا ہے۔
  • 0 کا فیکٹوریل 1 ہے (لوپ کے نہ چلنے سے ہینڈل ہوتا ہے)۔
  • long long کا استعمال پروگرام کو بڑی فیکٹوریل ویلیوز (20 تک) کو ہینڈل کرنے کی اجازت دیتا ہے۔

✅ نتیجہ

آپ نے کامیابی سے ایک C پروگرام لکھا ہے جو صارف کے درج کردہ عدد کا while لوپ کا استعمال کرتے ہوئے فیکٹوریل حساب کرتا ہے۔ آپ نے بار بار ضرب کرنے کے لیے لوپ کا استعمال سیکھ لیا ہے۔

📌 اہم: کسی عدد کا فیکٹوریل بہت تیزی سے بڑھتا ہے۔ 20 سے بڑے اعداد کے لیے، فیکٹوریل long long ڈیٹا ٹائپ کی حد سے تجاوز کر جاتا ہے۔ بہت بڑے اعداد کے لیے، آپ کو بگ انٹیجرز کو سپورٹ کرنے والی لائبریریاں استعمال کرنی ہوں گی۔
💡 مشورہ: آپ ریکرسن کا استعمال کرتے ہوئے بھی فیکٹوریل حساب کر سکتے ہیں۔ ریکرسن ایک ایسی تکنیک ہے جہاں ایک فنکشن خود کو کال کرتا ہے۔ فیکٹوریل فنکشن کو factorial(n) = n * factorial(n-1) کے طور پر لکھا جا سکتا ہے جس میں factorial(0) = 1 بنیادی کیس ہے۔
⬅ Back to Practical Notebooks