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 do-while loop.

🛠️ What You Need

  • Visual Studio Code or any C/C++ compiler
  • Knowledge of do-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 do-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_dowhile.c.
  3. Write the following code:
/* Practical 47: Program to find factorial using do-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 do-while loop to calculate factorial ============================================ */ do { factorial = factorial * i; i++; } while (i <= num); // 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. do — Starts the do-while loop.
  7. factorial = factorial * i; — Multiplies the current value of factorial by i.
  8. i++; — Increments the counter.
  9. while (i <= num); — Condition checked after the body. Runs until i <= num.

Step 3: Save, Compile, and Run

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

Run the program:

./factorial_dowhile

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

📊 Do-While Loop Execution for Factorial (n=5)

Iteration i Value Factorial Before Factorial After i++ Condition i <= 5
1 1 1 1 2 ✅ True
2 2 1 2 3 ✅ True
3 3 2 6 4 ✅ True
4 4 6 24 5 ✅ True
5 5 24 120 6 ❌ False

📊 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 while loop */ int i = 1; long long factorial = 1; while (i <= num) { factorial = factorial * i; i++; }
/* 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 do-while loop executes the body at least once before checking the condition.
  • The loop multiplies numbers from 1 to num.
  • 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 running once and multiplying 1).
  • 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 do-while loop. You have learned how to use the do-while loop to perform repetitive multiplication.

📌 Important: The do-while loop always executes the loop body at least once. This is useful when you need to ensure the loop runs at least once, even if the condition is false initially.
💡 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++ پروگرام لکھنا جو صارف سے ایک عدد ان پٹ کے طور پر لے اور do-while لوپ کا استعمال کرتے ہوئے اس کا فیکٹوریل حساب کرے۔

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

  • Visual Studio Code یا کوئی بھی C/C++ کمپائلر
  • do-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_dowhile.c نام کی ایک نئی فائل بنائیں۔
  3. نیچے دیا گیا کوڈ لکھیں:
/* Practical 47: Program to find factorial using do-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 do-while loop to calculate factorial ============================================ */ do { factorial = factorial * i; i++; } while (i <= num); // 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. do — do-while لوپ شروع کرتا ہے۔
  7. factorial = factorial * i; — factorial کی موجودہ قیمت کو i سے ضرب کرتا ہے۔
  8. i++; — کاؤنٹر کو بڑھاتا ہے۔
  9. while (i <= num); — شرط باڈی کے بعد چیک ہوتی ہے۔ جب تک i <= num ہے چلتا ہے۔

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

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

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

./factorial_dowhile

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

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

📊 مشاہدات

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

✅ نتیجہ

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

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