diff --git a/README.md b/README.md index 6f93903..758192e 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,6 @@ Welcome to the **WTC Coding Practice Repository**. This repository is a collaborative workspace where the **WTC team** solves programming problems, strengthens problem-solving skills, and builds a **strong personal and team coding brand** through consistent GitHub contributions. ---- - ## 🎯 Purpose of This Repository - Practice and master **Data Structures & Algorithms** @@ -13,8 +11,6 @@ This repository is a collaborative workspace where the **WTC team** solves progr - Maintain **clean code and standard conventions** - Track individual and team progress transparently ---- - ## 👥 Who Can Contribute? This repository is intended **only for WTC team members**. @@ -23,98 +19,11 @@ Every contributor is expected to: - Push solutions regularly - Follow the repository standards strictly ---- - -## 📁 File Naming Convention (Strictly Mandatory) - -Each solution file **must follow** the naming format below: - -``` -Name_Question_q.No.extension -``` - -### ✅ Correct Examples -``` -Divyansh_TwoSum_q1.py -Aarav_ReverseArray_q12.cpp -Sneha_BinarySearch_q7.java -``` - -### ❌ Incorrect Examples -``` -q1.py -solution.cpp -TwoSum.java -``` - **Rules:** - `Name` → Your name (use the same format every time) - `Question` → Short and meaningful problem name - `q.No.` → Question number as per the shared list ---- - -## 🧠 Problem Source - -All problems will be taken from the **official question list shared with the WTC team** -(e.g., Top 100 DSA sheet, daily practice sheet, or curated problem sets). - -Make sure: -- You solve the correct question number -- Your solution matches the problem statement -- No copied or plagiarized code is pushed - ---- - -## 🛠️ Allowed Programming Languages - -You may use: -- **C / C++** -- **Java** -- **Python** -- **JavaScript** - -Choose your preferred language, but ensure: -- Readable code -- Proper formatting -- Meaningful variable names - ---- - -## 📌 Contribution Guidelines - -1. Clone or fork the repository (as instructed) -2. Add your solution file following the naming convention -3. Write clean and well-structured code -4. Push your changes to the repository -5. Update the **progress tracking sheet** after every submission - ---- - -## 📊 Progress Tracking - -Each contributor must update the shared tracking sheet with: -- Name -- Question number solved -- Programming language used -- Date of submission - -This helps maintain **accountability and transparency**. - ---- - -## 🏆 Building the WTC Brand - -This repository represents the **technical identity of WTC**. -Your contributions should reflect: -- Consistency -- Professionalism -- Strong coding fundamentals - -Code as if a **recruiter or senior engineer** is reviewing it. - ---- - ## 📬 Support For any doubts related to: @@ -124,8 +33,6 @@ For any doubts related to: Please contact the **WTC core team**. ---- - ### 🔥 Code Daily. Improve Constantly. Build Your Brand. Happy Coding! 🚀 diff --git a/Shaivi_Abundant_Number.Q26.c b/Shaivi_Abundant_Number.Q26.c new file mode 100644 index 0000000..4ad0468 --- /dev/null +++ b/Shaivi_Abundant_Number.Q26.c @@ -0,0 +1,337 @@ +// Abundant Number or Not in C Program + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + for (int i = 1; i < num; i++) + if (num % i == 0) + sum += i; + + if (sum > num) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 1 - For Loop We add all proper divisors of num excluding num itself. If their sum is greater than num it is an abundant number. Example 12 has divisors 1+2+3+4+6=16 and 16>12 so 12 is abundant. + +// Method 2: Using while Loop +#include +int main() { + int num, sum = 0, i = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + while (i < num) { + if (num % i == 0) + sum += i; + i++; + } + + if (sum > num) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop. We initialize i before the loop and increment it inside. Good practice to write the same abundant number logic using different loop types. + +// Method 3: Using do-while Loop +#include +int main() { + int num, sum = 0, i = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + do { + if (num % i == 0) + sum += i; + i++; + } while (i < num); + + if (sum > num) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with divisor sum logic for abundant number check. + +// Method 4: Using Square Root Optimization +#include +#include +int main() { + int num, sum = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + // divisors come in pairs so check only up to sqrt + for (int i = 2; i <= sqrt(num); i++) { + if (num % i == 0) { + sum += i; + if (i != num / i) + sum += num / i; + } + } + + if (num > 1 && sum > num) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 4 - Square Root Divisors always come in pairs. If i divides num then num/i is also a divisor. We check only up to sqrt(num) and add both at once. Start sum at 1 since 1 is always a divisor. Much faster method. + +// Method 5: Using Function +#include +int divisorSum(int num) { + int sum = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) + sum += i; + return sum; +} +int isAbundant(int num) { + return divisorSum(num) > num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isAbundant(num)) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 5 - Function Logic is split into divisorSum() and isAbundant() functions. divisorSum() calculates the sum of all proper divisors. isAbundant() checks if sum exceeds num. Main just takes input and prints. Clean and reusable. + +// Method 6: Using Recursion +#include +int divisorSum(int num, int i) { + if (i == num) return 0; + if (num % i == 0) return i + divisorSum(num, i + 1); + return divisorSum(num, i + 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int sum = divisorSum(num, 1); + + if (sum > num) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 6 - Recursion divisorSum() checks if i divides num and adds it then calls itself with i+1. When i equals num it stops and returns 0. Good practice for understanding how recursion replaces a simple divisor sum loop. + +// Method 7: Using Array to Store Divisors +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + int divisors[num], count = 0; + + for (int i = 1; i < num; i++) { + if (num % i == 0) { + divisors[count++] = i; + sum += i; + } + } + + printf("Proper divisors of %d are: ", num); + for (int i = 0; i < count; i++) + printf("%d ", divisors[i]); + printf("\nSum of divisors = %d\n", sum); + + if (sum > num) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 7 - Array We store all proper divisors in an array and also calculate their sum. We print the divisors list and sum before the final verdict. More informative output showing exactly which divisors were found and their total. + +// Method 8: Using Ternary Operator +#include +int divisorSum(int n) { + int s = 0; + for (int i = 1; i < n; i++) + if (n % i == 0) s += i; + return s; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? true : false + (divisorSum(num) > num) + ? printf("%d is an Abundant Number\n", num) + : printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 8 - Ternary Operator We call divisorSum() inside the ternary condition directly. If sum exceeds num print yes else print no. All output handled in one clean single statement. Compact and concise version of the solution. + +// Method 9: Using switch Statement +#include +int isAbundant(int num) { + int s = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) s += i; + return s > num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isAbundant() returns 1 if true and 0 if false + switch (isAbundant(num)) { + case 1: + printf("%d is an Abundant Number\n", num); + break; + case 0: + printf("%d is Not an Abundant Number\n", num); + break; + } + + return 0; +} +// Method 9 - Switch Case isAbundant() returns 1 for abundant and 0 for not abundant. Switch works on these values. Case 1 means abundant number and case 0 means not. Good practice combining function with switch statement. + +// Method 10: Print Abundant Numbers in a Given Range +#include +int isAbundant(int num) { + int s = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) s += i; + return s > num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Abundant numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (isAbundant(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 10 - Range We check every number in the given range and print it if it is abundant. isAbundant() is reused cleanly for each number. Smallest abundant numbers are 12 18 20 24 30 36 40 42 48 54 56 60 66 70 72 78 80. + +// Method 11: Classify Number as Deficient Perfect or Abundant +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + for (int i = 1; i < num; i++) + if (num % i == 0) + sum += i; + + printf("Sum of proper divisors of %d = %d\n", num, sum); + + if (sum > num) + printf("%d is an Abundant Number (sum > number)\n", num); + else if (sum == num) + printf("%d is a Perfect Number (sum == number)\n", num); + else + printf("%d is a Deficient Number (sum < number)\n", num); + + return 0; +} +// Method 11 - Classify Every number falls into one of three categories. If divisor sum is greater than num it is abundant. If equal it is perfect. If less it is deficient. This classifies the number into all three categories at once. + +// Method 12: Using Array to Store Abundant Numbers in Range +#include +int isAbundant(int num) { + int s = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) s += i; + return s > num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int result[1000], count = 0; + + for (int i = start; i <= end; i++) + if (isAbundant(i)) + result[count++] = i; + + printf("Abundant numbers between %d and %d are: ", start, end); + for (int i = 0; i < count; i++) + printf("%d ", result[i]); + printf("\nTotal abundant numbers found: %d\n", count); + + return 0; +} +// Method 12 - Array with Count We store all abundant numbers found in the range in an array and print them with a total count at the end. Useful when you need to process or use the abundant numbers further in the program. + +// Method 13: Using Macro +#include + +int abundHelper(int n) { + int s = 0; + for (int i = 1; i < n; i++) + if (n % i == 0) s += i; + return s > n; +} + +#define IS_ABUNDANT(n) abundHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_ABUNDANT(num)) + printf("%d is an Abundant Number\n", num); + else + printf("%d is Not an Abundant Number\n", num); + + return 0; +} +// Method 13 - Macro We define IS_ABUNDANT as a macro that calls abundHelper(). Wherever IS_ABUNDANT(n) is written it gets replaced by abundHelper(n). Good to know how macros wrap function calls cleanly in C. diff --git a/Shaivi_Afriendly_pair.Q27.c b/Shaivi_Afriendly_pair.Q27.c new file mode 100644 index 0000000..eb7296f --- /dev/null +++ b/Shaivi_Afriendly_pair.Q27.c @@ -0,0 +1,431 @@ +```c +// C Program to Check if the Given Two Numbers are Friendly Pair or Not + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int a, b, sumA = 0, sumB = 0; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // find sum of proper divisors of a + for (int i = 1; i <= a; i++) + if (a % i == 0) + sumA += i; + + // find sum of proper divisors of b + for (int i = 1; i <= b; i++) + if (b % i == 0) + sumB += i; + + // friendly pair condition: sumA/a == sumB/b + // cross multiply to avoid division: sumA * b == sumB * a + if (sumA * b == sumB * a) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 1 - For Loop We find the sum of all divisors of both numbers including themselves. Two numbers form a friendly pair if their abundancy ratio is equal meaning sumA/a == sumB/b. We cross multiply to avoid float division. + +// Method 2: Using while Loop +#include +int main() { + int a, b, sumA = 0, sumB = 0; + int i = 1; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // sum of divisors of a + while (i <= a) { + if (a % i == 0) + sumA += i; + i++; + } + + i = 1; + + // sum of divisors of b + while (i <= b) { + if (b % i == 0) + sumB += i; + i++; + } + + if (sumA * b == sumB * a) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using while loops for both divisor sums. We reset i to 1 before the second loop. Good practice to write the same friendly pair logic using different loop types. + +// Method 3: Using do-while Loop +#include +int main() { + int a, b, sumA = 0, sumB = 0; + int i = 1; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // sum of divisors of a using do-while + do { + if (a % i == 0) + sumA += i; + i++; + } while (i <= a); + + i = 1; + + // sum of divisors of b using do-while + do { + if (b % i == 0) + sumB += i; + i++; + } while (i <= b); + + if (sumA * b == sumB * a) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with divisor sum calculation for both numbers. + +// Method 4: Using Square Root Optimization +#include +#include +int main() { + int a, b; + long long sumA = 0, sumB = 0; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // optimized divisor sum using sqrt + for (int i = 1; i <= sqrt(a); i++) { + if (a % i == 0) { + sumA += i; + if (i != a / i) + sumA += a / i; + } + } + + for (int i = 1; i <= sqrt(b); i++) { + if (b % i == 0) { + sumB += i; + if (i != b / i) + sumB += b / i; + } + } + + if (sumA * b == sumB * a) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 4 - Square Root Divisors come in pairs. If i divides n then n/i is also a divisor. We check only up to sqrt and add both at once. long long is used to prevent overflow in cross multiplication. Much faster method. + +// Method 5: Using Function +#include +long long divisorSum(int num) { + long long sum = 0; + for (int i = 1; i <= num; i++) + if (num % i == 0) + sum += i; + return sum; +} +int isFriendlyPair(int a, int b) { + return divisorSum(a) * b == divisorSum(b) * a; +} +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + if (isFriendlyPair(a, b)) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 5 - Function Logic is split into divisorSum() and isFriendlyPair() functions. divisorSum() finds total divisor sum. isFriendlyPair() checks the abundancy ratio equality. Main just takes input and prints. Clean and reusable. + +// Method 6: Using Recursion +#include +long long divisorSum(int num, int i) { + if (i > num) return 0; + if (num % i == 0) return i + divisorSum(num, i + 1); + return divisorSum(num, i + 1); +} +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + long long sumA = divisorSum(a, 1); + long long sumB = divisorSum(b, 1); + + if (sumA * b == sumB * a) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 6 - Recursion divisorSum() checks if i divides num and adds it then calls itself with i+1. When i exceeds num it returns 0. We call it separately for both a and b. Good practice using recursion for divisor sums. + +// Method 7: Using GCD to Simplify Ratio +#include +int gcd(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} +long long divisorSum(int num) { + long long sum = 0; + for (int i = 1; i <= num; i++) + if (num % i == 0) + sum += i; + return sum; +} +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + long long sumA = divisorSum(a); + long long sumB = divisorSum(b); + + // simplify ratios sumA/a and sumB/b using GCD + int g1 = gcd(sumA, a); + int g2 = gcd(sumB, b); + + long long ratioA_num = sumA / g1, ratioA_den = a / g1; + long long ratioB_num = sumB / g2, ratioB_den = b / g2; + + printf("Abundancy ratio of %d = %lld/%lld\n", a, ratioA_num, ratioA_den); + printf("Abundancy ratio of %d = %lld/%lld\n", b, ratioB_num, ratioB_den); + + if (ratioA_num == ratioB_num && ratioA_den == ratioB_den) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 7 - GCD Ratio We simplify the abundancy ratio sumA/a and sumB/b using GCD. Then compare numerators and denominators separately. This shows the exact ratio clearly and is more mathematically correct than cross multiplying. + +// Method 8: Using Ternary Operator +#include +long long divSum(int n) { + long long s = 0; + for (int i = 1; i <= n; i++) + if (n % i == 0) s += i; + return s; +} +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // condition ? true : false + (divSum(a) * b == divSum(b) * a) + ? printf("(%d, %d) are a Friendly Pair\n", a, b) + : printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 8 - Ternary Operator We call divSum() for both numbers inside the ternary condition directly. If the cross products are equal print yes else print no. All output handled in one clean single statement. Compact version. + +// Method 9: Using switch Statement +#include +long long divSum(int n) { + long long s = 0; + for (int i = 1; i <= n; i++) + if (n % i == 0) s += i; + return s; +} +int isFriendly(int a, int b) { + return divSum(a) * b == divSum(b) * a; +} +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // isFriendly() returns 1 if true and 0 if false + switch (isFriendly(a, b)) { + case 1: + printf("(%d, %d) are a Friendly Pair\n", a, b); + break; + case 0: + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + break; + } + + return 0; +} +// Method 9 - Switch Case isFriendly() returns 1 for friendly pair and 0 for not friendly. Switch works on these values. Case 1 means friendly pair and case 0 means not. Good practice combining function with switch statement. + +// Method 10: Checking Multiple Pairs +#include +long long divSum(int n) { + long long s = 0; + for (int i = 1; i <= n; i++) + if (n % i == 0) s += i; + return s; +} +int main() { + int t; + + printf("Enter number of pairs to check: "); + scanf("%d", &t); + + while (t--) { + int a, b; + printf("Enter pair: "); + scanf("%d %d", &a, &b); + + if (divSum(a) * b == divSum(b) * a) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + } + + return 0; +} +// Method 10 - Multiple Pairs We take number of test cases t and check each pair one by one. Same logic is applied for each pair. Useful when you need to check many pairs at once. Good for competitive programming style input. + +// Method 11: Printing Detailed Information +#include +long long divSum(int n) { + long long s = 0; + for (int i = 1; i <= n; i++) + if (n % i == 0) s += i; + return s; +} +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + long long sumA = divSum(a); + long long sumB = divSum(b); + + printf("Sum of divisors of %d = %lld\n", a, sumA); + printf("Sum of divisors of %d = %lld\n", b, sumB); + printf("Abundancy ratio of %d = %lld/%d\n", a, sumA, a); + printf("Abundancy ratio of %d = %lld/%d\n", b, sumB, b); + + if (sumA * b == sumB * a) + printf("Ratios are equal. (%d, %d) are a Friendly Pair\n", a, b); + else + printf("Ratios are not equal. (%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 11 - Detailed Output We print the divisor sums and abundancy ratios of both numbers before the final verdict. This makes the output more informative and educational showing exactly why the pair is or is not friendly. + +// Method 12: Using Array to Store Divisors +#include +int main() { + int a, b; + long long sumA = 0, sumB = 0; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + int divA[a], divB[b]; + int cA = 0, cB = 0; + + for (int i = 1; i <= a; i++) + if (a % i == 0) { divA[cA++] = i; sumA += i; } + + for (int i = 1; i <= b; i++) + if (b % i == 0) { divB[cB++] = i; sumB += i; } + + printf("Divisors of %d: ", a); + for (int i = 0; i < cA; i++) printf("%d ", divA[i]); + printf("\nDivisors of %d: ", b); + for (int i = 0; i < cB; i++) printf("%d ", divB[i]); + printf("\n"); + + if (sumA * b == sumB * a) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 12 - Array We store all divisors of both numbers in separate arrays and print them. Sums are calculated while storing. This gives full visibility into which divisors were found for each number before the final verdict. + +// Method 13: Using Macro +#include + +long long dsHelper(int n) { + long long s = 0; + for (int i = 1; i <= n; i++) + if (n % i == 0) s += i; + return s; +} + +#define IS_FRIENDLY_PAIR(a, b) (dsHelper(a) * (b) == dsHelper(b) * (a)) + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + if (IS_FRIENDLY_PAIR(a, b)) + printf("(%d, %d) are a Friendly Pair\n", a, b); + else + printf("(%d, %d) are Not a Friendly Pair\n", a, b); + + return 0; +} +// Method 13 - Macro We define IS_FRIENDLY_PAIR as a macro that checks the abundancy ratio equality directly. Wherever IS_FRIENDLY_PAIR(a,b) is written it gets replaced by the full expression. Good to know how macros work in C. +``` diff --git a/Shaivi_Armstrong.Q14.c b/Shaivi_Armstrong.Q14.c new file mode 100644 index 0000000..29aaddc --- /dev/null +++ b/Shaivi_Armstrong.Q14.c @@ -0,0 +1,349 @@ +// C Program to Check a Number is Armstrong or Not + +// Method 1: Using while Loop (Brute Force) +#include +#include +int main() { + int num, original, sum = 0, remainder, digits = 0; + int temp; + + printf("Enter a number: "); + scanf("%d", &num); + + original = num; + temp = num; + + // count number of digits + while (temp != 0) { + digits++; + temp /= 10; + } + + temp = num; + + // calculate sum of digits raised to power of digit count + while (temp != 0) { + remainder = temp % 10; + sum += pow(remainder, digits); + temp /= 10; + } + + if (sum == original) + printf("%d is an Armstrong Number\n", original); + else + printf("%d is Not an Armstrong Number\n", original); + + return 0; +} +// Method 1 - While Loop We first count the number of digits. Then extract each digit using %10 raise it to the power of digit count and add to sum. If sum equals original number it is Armstrong. + +// Method 2: Using for Loop +#include +#include +int main() { + int num, original, sum = 0, digits = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + original = num; + + // count digits + for (int temp = num; temp != 0; temp /= 10) + digits++; + + // calculate armstrong sum + for (int temp = num; temp != 0; temp /= 10) + sum += pow(temp % 10, digits); + + if (sum == original) + printf("%d is an Armstrong Number\n", original); + else + printf("%d is Not an Armstrong Number\n", original); + + return 0; +} +// Method 2 - For Loop Same logic as method 1 but both loops are written as for loops. We use a temp variable to avoid modifying original num. Compact and clean way to write the same solution. + +// Method 3: Using do-while Loop +#include +#include +int main() { + int num, original, sum = 0, digits = 0; + int temp; + + printf("Enter a number: "); + scanf("%d", &num); + + original = num; + temp = num; + + // count digits using do-while + do { + digits++; + temp /= 10; + } while (temp != 0); + + temp = num; + + // calculate armstrong sum using do-while + do { + sum += pow(temp % 10, digits); + temp /= 10; + } while (temp != 0); + + if (sum == original) + printf("%d is an Armstrong Number\n", original); + else + printf("%d is Not an Armstrong Number\n", original); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with digit extraction logic. + +// Method 4: Using Function +#include +#include +int countDigits(int num) { + int count = 0; + while (num != 0) { + count++; + num /= 10; + } + return count; +} +int isArmstrong(int num) { + int digits = countDigits(num); + int temp = num, sum = 0; + while (temp != 0) { + sum += pow(temp % 10, digits); + temp /= 10; + } + return sum == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isArmstrong(num)) + printf("%d is an Armstrong Number\n", num); + else + printf("%d is Not an Armstrong Number\n", num); + + return 0; +} +// Method 4 - Function Logic is split into two functions. countDigits() counts the digits and isArmstrong() checks the condition. Main just takes input and prints. Clean reusable and well organized code. + +// Method 5: Using Recursion +#include +#include +int countDigits(int num) { + if (num == 0) return 0; + return 1 + countDigits(num / 10); +} +int armstrongSum(int num, int digits) { + if (num == 0) return 0; + return pow(num % 10, digits) + armstrongSum(num / 10, digits); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int digits = countDigits(num); + int sum = armstrongSum(num, digits); + + if (sum == num) + printf("%d is an Armstrong Number\n", num); + else + printf("%d is Not an Armstrong Number\n", num); + + return 0; +} +// Method 5 - Recursion Two recursive functions are used. countDigits() counts digits recursively and armstrongSum() calculates the sum recursively. Each calls itself with num/10 until num becomes 0. + +// Method 6: Using String +#include +#include +#include +int main() { + char numStr[20]; + int sum = 0; + + printf("Enter a number: "); + scanf("%s", numStr); + + int digits = strlen(numStr); + + for (int i = 0; i < digits; i++) + sum += pow(numStr[i] - '0', digits); + + int original = 0; + for (int i = 0; i < digits; i++) + original = original * 10 + (numStr[i] - '0'); + + if (sum == original) + printf("%s is an Armstrong Number\n", numStr); + else + printf("%s is Not an Armstrong Number\n", numStr); + + return 0; +} +// Method 6 - String We take the number as a string. strlen() gives digit count directly. Each character is converted to digit by subtracting '0' then raised to power. No need to count digits separately. + +// Method 7: Using Array +#include +#include +int main() { + int num, digits[20], count = 0, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + int original = num, temp = num; + + // store each digit in array + while (temp != 0) { + digits[count++] = temp % 10; + temp /= 10; + } + + // raise each digit to power of count and sum + for (int i = 0; i < count; i++) + sum += pow(digits[i], count); + + if (sum == original) + printf("%d is an Armstrong Number\n", original); + else + printf("%d is Not an Armstrong Number\n", original); + + return 0; +} +// Method 7 - Array We store all digits in an array first then loop through it raising each digit to the power of count. Good for practicing arrays with math logic. Makes the two steps very clear and separate. + +// Method 8: Using Ternary Operator +#include +#include +int countDigits(int n) { + int c = 0; + while (n != 0) { c++; n /= 10; } + return c; +} +int armSum(int n, int d) { + int s = 0, t = n; + while (t != 0) { s += pow(t % 10, d); t /= 10; } + return s; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? true : false + (armSum(num, countDigits(num)) == num) + ? printf("%d is an Armstrong Number\n", num) + : printf("%d is Not an Armstrong Number\n", num); + + return 0; +} +// Method 8 - Ternary Operator We call both helper functions inside the ternary condition directly. If the armstrong sum equals num print yes else print no. All output handled in one clean single statement. + +// Method 9: Using switch Statement +#include +#include +int isArmstrong(int num) { + int digits = 0, sum = 0, temp = num; + while (temp != 0) { digits++; temp /= 10; } + temp = num; + while (temp != 0) { sum += pow(temp % 10, digits); temp /= 10; } + return sum == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isArmstrong() returns 1 if true and 0 if false + switch (isArmstrong(num)) { + case 1: + printf("%d is an Armstrong Number\n", num); + break; + case 0: + printf("%d is Not an Armstrong Number\n", num); + break; + } + + return 0; +} +// Method 9 - Switch Case isArmstrong() returns 1 for armstrong and 0 for not armstrong. Switch works on these values. Case 1 means armstrong and case 0 means not armstrong. Good practice combining function with switch. + +// Method 10: Using Macro +#include +#include + +int digitCount(int n) { + int c = 0; + while (n != 0) { c++; n /= 10; } + return c; +} +int armstrongCheck(int n) { + int d = digitCount(n), s = 0, t = n; + while (t != 0) { s += pow(t % 10, d); t /= 10; } + return s == n; +} + +#define IS_ARMSTRONG(n) armstrongCheck(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_ARMSTRONG(num)) + printf("%d is an Armstrong Number\n", num); + else + printf("%d is Not an Armstrong Number\n", num); + + return 0; +} +// Method 10 - Macro We define IS_ARMSTRONG as a macro that calls armstrongCheck(). Wherever IS_ARMSTRONG(n) is written it gets replaced by the full function call. Good to know how macros wrap functions in C. + +// Method 11: Without using pow() Function +#include +int main() { + int num, sum = 0, digits = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + int original = num, temp = num; + + // count digits + while (temp != 0) { digits++; temp /= 10; } + + temp = num; + + // manually raise to power without pow() + while (temp != 0) { + int digit = temp % 10; + int power = 1; + for (int i = 0; i < digits; i++) + power *= digit; + sum += power; + temp /= 10; + } + + if (sum == original) + printf("%d is an Armstrong Number\n", original); + else + printf("%d is Not an Armstrong Number\n", original); + + return 0; +} +// Method 11 - Without pow() Instead of using pow() from math.h we manually multiply the digit by itself digits times using a small for loop. This avoids including math.h and avoids floating point issues with pow(). diff --git a/Shaivi_Armstrong_Range.Q15.c b/Shaivi_Armstrong_Range.Q15.c new file mode 100644 index 0000000..f4ede49 --- /dev/null +++ b/Shaivi_Armstrong_Range.Q15.c @@ -0,0 +1,368 @@ +// Find the Armstrong Numbers in a Given Range in C + +// Method 1: Using Nested while Loop (Brute Force) +#include +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + int temp = i, sum = 0, digits = 0; + + // count digits + while (temp != 0) { + digits++; + temp /= 10; + } + + temp = i; + + // calculate armstrong sum + while (temp != 0) { + sum += pow(temp % 10, digits); + temp /= 10; + } + + if (sum == i) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 1 - Brute Force For every number in range we count its digits then raise each digit to the power of digit count and add to sum. If sum equals the number itself it is an Armstrong number. + +// Method 2: Using for Loop +#include +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + int sum = 0, digits = 0; + + for (int temp = i; temp != 0; temp /= 10) + digits++; + + for (int temp = i; temp != 0; temp /= 10) + sum += pow(temp % 10, digits); + + if (sum == i) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 2 - For Loop Same logic as method 1 but all loops are written as for loops. Two inner for loops handle digit counting and sum calculation separately. Compact and clean way to write it. + +// Method 3: Using while Loop with do-while +#include +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + int i = start; + while (i <= end) { + int temp = i, sum = 0, digits = 0; + + do { + digits++; + temp /= 10; + } while (temp != 0); + + temp = i; + + do { + sum += pow(temp % 10, digits); + temp /= 10; + } while (temp != 0); + + if (sum == i) + printf("%d ", i); + i++; + } + printf("\n"); + + return 0; +} +// Method 3 - do-while Outer loop is while and inner loops are do-while. Body of do-while runs first then condition is checked. Completes all 3 loop types together. Good practice mixing different loop types. + +// Method 4: Using Function +#include +#include +int countDigits(int num) { + int count = 0; + while (num != 0) { + count++; + num /= 10; + } + return count; +} +int isArmstrong(int num) { + int digits = countDigits(num); + int temp = num, sum = 0; + while (temp != 0) { + sum += pow(temp % 10, digits); + temp /= 10; + } + return sum == num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (isArmstrong(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 4 - Function Logic is split into countDigits() and isArmstrong() functions. Main loop just calls isArmstrong() for each number in range. Code is clean reusable and very easy to read and maintain. + +// Method 5: Using Recursion +#include +#include +int countDigits(int num) { + if (num == 0) return 0; + return 1 + countDigits(num / 10); +} +int armstrongSum(int num, int digits) { + if (num == 0) return 0; + return pow(num % 10, digits) + armstrongSum(num / 10, digits); +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + int digits = countDigits(i); + int sum = armstrongSum(i, digits); + if (sum == i) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 5 - Recursion Two recursive functions handle digit counting and sum calculation. countDigits() adds 1 each call until num is 0. armstrongSum() raises each digit to power and adds recursively. + +// Method 6: Using Array to Store and Print +#include +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int result[1000], count = 0; + + for (int i = start; i <= end; i++) { + int temp = i, sum = 0, digits = 0; + + while (temp != 0) { digits++; temp /= 10; } + temp = i; + while (temp != 0) { sum += pow(temp % 10, digits); temp /= 10; } + + if (sum == i) + result[count++] = i; + } + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = 0; i < count; i++) + printf("%d ", result[i]); + printf("\n"); + + return 0; +} +// Method 6 - Array We store all found Armstrong numbers in a result array and print them at the end. Useful when you need to use the Armstrong numbers later in the program for further processing. + +// Method 7: Using String for Digit Extraction +#include +#include +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + char numStr[20]; + sprintf(numStr, "%d", i); + int digits = strlen(numStr); + int sum = 0; + + for (int j = 0; j < digits; j++) + sum += pow(numStr[j] - '0', digits); + + if (sum == i) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 7 - String We convert each number to string using sprintf(). strlen() gives digit count directly. Each character is converted to digit by subtracting '0' then raised to power. No manual digit counting needed. + +// Method 8: Without using pow() Function +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + int temp = i, sum = 0, digits = 0; + + while (temp != 0) { digits++; temp /= 10; } + temp = i; + + while (temp != 0) { + int digit = temp % 10; + int power = 1; + for (int j = 0; j < digits; j++) + power *= digit; + sum += power; + temp /= 10; + } + + if (sum == i) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 8 - Without pow() Instead of pow() from math.h we manually multiply digit by itself digits times using a small for loop. Avoids math.h header entirely and also avoids floating point precision issues of pow(). + +// Method 9: Using Ternary Operator +#include +#include +int isArmstrong(int num) { + int digits = 0, sum = 0, temp = num; + while (temp != 0) { digits++; temp /= 10; } + temp = num; + while (temp != 0) { sum += pow(temp % 10, digits); temp /= 10; } + return sum == num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + isArmstrong(i) ? printf("%d ", i) : 0; + printf("\n"); + + return 0; +} +// Method 9 - Ternary Operator We use ternary inside the loop. If isArmstrong() returns 1 we print the number else we do nothing using 0. Short and compact way to print results without writing a full if block. + +// Method 10: Using Macro +#include +#include + +int armCheck(int n) { + int d = 0, s = 0, t = n; + while (t != 0) { d++; t /= 10; } + t = n; + while (t != 0) { s += pow(t % 10, d); t /= 10; } + return s == n; +} + +#define IS_ARMSTRONG(n) armCheck(n) + +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (IS_ARMSTRONG(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 10 - Macro We define IS_ARMSTRONG as a macro that calls armCheck(). Wherever IS_ARMSTRONG(n) is written it gets replaced by armCheck(n). Good to know how macros wrap function calls cleanly in C. + +// Method 11: Using Count with Output Message +#include +#include +int main() { + int start, end, found = 0; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Armstrong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + int temp = i, sum = 0, digits = 0; + + while (temp != 0) { digits++; temp /= 10; } + temp = i; + while (temp != 0) { sum += pow(temp % 10, digits); temp /= 10; } + + if (sum == i) { + printf("%d ", i); + found++; + } + } + + if (found == 0) + printf("None"); + printf("\nTotal Armstrong numbers found: %d\n", found); + + return 0; +} +// Method 11 - Count with Message We use a found counter to track how many Armstrong numbers exist in range. If found is 0 we print None. At the end we also print the total count. More complete and user friendly output. diff --git a/Shaivi_Automorphic_Number.Q24.c b/Shaivi_Automorphic_Number.Q24.c new file mode 100644 index 0000000..a77cd53 --- /dev/null +++ b/Shaivi_Automorphic_Number.Q24.c @@ -0,0 +1,386 @@ +// Automorphic Number or Not | C Program + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int num, square, temp, digits = 0, lastDigits; + + printf("Enter a number: "); + scanf("%d", &num); + + square = num * num; + + // count digits in num + temp = num; + while (temp != 0) { + digits++; + temp /= 10; + } + + // extract last 'digits' digits of square + int divisor = 1; + for (int i = 0; i < digits; i++) + divisor *= 10; + + lastDigits = square % divisor; + + if (lastDigits == num) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 1 - For Loop We square the number then count how many digits num has. We extract the same number of digits from the end of square using modulo. If those last digits equal num it is automorphic. Example 5^2=25 ends in 5. + +// Method 2: Using while Loop +#include +int main() { + int num, square, temp, digits = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + square = num * num; + temp = num; + + // count digits using while loop + while (temp != 0) { + digits++; + temp /= 10; + } + + // build divisor using while loop + int divisor = 1, i = 0; + while (i < digits) { + divisor *= 10; + i++; + } + + if (square % divisor == num) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but both digit counting and divisor building use while loops. We initialize counters before and increment inside. Good practice writing the same logic using different loop types. + +// Method 3: Using do-while Loop +#include +int main() { + int num, square, temp, digits = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + square = num * num; + temp = num; + + // count digits using do-while + do { + digits++; + temp /= 10; + } while (temp != 0); + + int divisor = 1, i = 0; + do { + divisor *= 10; + i++; + } while (i < digits); + + if (square % divisor == num) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with digit counting and divisor building logic. + +// Method 4: Using Function +#include +int countDigits(int num) { + int count = 0; + while (num != 0) { + count++; + num /= 10; + } + return count; +} +int isAutomorphic(int num) { + int square = num * num; + int digits = countDigits(num); + int divisor = 1; + for (int i = 0; i < digits; i++) + divisor *= 10; + return square % divisor == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isAutomorphic(num)) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 4 - Function Logic is split into countDigits() and isAutomorphic() functions. countDigits() counts how many digits num has. isAutomorphic() checks if square ends with num. Main just takes input and prints. Clean and reusable. + +// Method 5: Using Recursion +#include +int countDigits(int num) { + if (num == 0) return 0; + return 1 + countDigits(num / 10); +} +int buildDivisor(int digits) { + if (digits == 0) return 1; + return 10 * buildDivisor(digits - 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int square = num * num; + int digits = countDigits(num); + int divisor = buildDivisor(digits); + + if (square % divisor == num) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 5 - Recursion Two recursive functions are used. countDigits() counts digits by dividing num recursively. buildDivisor() builds 10^digits by multiplying 10 recursively. Good practice using recursion for math building blocks. + +// Method 6: Using String +#include +#include +#include +int main() { + int num, square; + char numStr[20], squareStr[20]; + + printf("Enter a number: "); + scanf("%d", &num); + + square = num * num; + + // convert both to strings + sprintf(numStr, "%d", num); + sprintf(squareStr, "%d", square); + + int numLen = strlen(numStr); + int squareLen = strlen(squareStr); + + // check if squareStr ends with numStr + int isAutomorphic = (strcmp(squareStr + squareLen - numLen, numStr) == 0); + + if (isAutomorphic) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 6 - String We convert num and square to strings using sprintf(). Then check if the end of squareStr matches numStr using strcmp(). squareStr + squareLen - numLen points to the last numLen characters of squareStr. + +// Method 7: Using pow() Function +#include +#include +int main() { + int num, square, digits = 0; + int temp; + + printf("Enter a number: "); + scanf("%d", &num); + + square = num * num; + temp = num; + + while (temp != 0) { + digits++; + temp /= 10; + } + + // use pow() to build divisor + int divisor = (int)pow(10, digits); + + if (square % divisor == num) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 7 - pow() Instead of building divisor using a loop we use pow(10, digits) from math.h directly. We cast the result to int since pow() returns double. Cleaner and shorter way to get 10 raised to digit count. + +// Method 8: Using Ternary Operator +#include +int isAutomorphic(int num) { + int sq = num * num, d = 0, div = 1, t = num; + while (t != 0) { d++; t /= 10; } + for (int i = 0; i < d; i++) div *= 10; + return sq % div == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? true : false + isAutomorphic(num) + ? printf("%d is an Automorphic Number\n", num) + : printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 8 - Ternary Operator We call isAutomorphic() inside a ternary condition directly. If it returns 1 print yes else print no. All output handled in one clean single statement. Compact version combining function and ternary. + +// Method 9: Using switch Statement +#include +int isAutomorphic(int num) { + int sq = num * num, d = 0, div = 1, t = num; + while (t != 0) { d++; t /= 10; } + for (int i = 0; i < d; i++) div *= 10; + return sq % div == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isAutomorphic() returns 1 if true and 0 if false + switch (isAutomorphic(num)) { + case 1: + printf("%d is an Automorphic Number\n", num); + break; + case 0: + printf("%d is Not an Automorphic Number\n", num); + break; + } + + return 0; +} +// Method 9 - Switch Case isAutomorphic() returns 1 for automorphic and 0 for not automorphic. Switch works on these values. Case 1 means automorphic and case 0 means not. Good practice combining function with switch. + +// Method 10: Print Automorphic Numbers in a Given Range +#include +int isAutomorphic(int num) { + int sq = num * num, d = 0, div = 1, t = num; + while (t != 0) { d++; t /= 10; } + for (int i = 0; i < d; i++) div *= 10; + return sq % div == num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Automorphic numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (isAutomorphic(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 10 - Range We check every number in the given range and print it if it is automorphic. isAutomorphic() is reused cleanly for each number. Known automorphic numbers are 0 1 5 6 25 76 376 625 so test with a wide range. + +// Method 11: Using Array to Store Automorphic Numbers +#include +int isAutomorphic(int num) { + int sq = num * num, d = 0, div = 1, t = num; + while (t != 0) { d++; t /= 10; } + for (int i = 0; i < d; i++) div *= 10; + return sq % div == num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int result[1000], count = 0; + + for (int i = start; i <= end; i++) + if (isAutomorphic(i)) + result[count++] = i; + + printf("Automorphic numbers between %d and %d are: ", start, end); + for (int i = 0; i < count; i++) + printf("%d ", result[i]); + printf("\nTotal automorphic numbers found: %d\n", count); + + return 0; +} +// Method 11 - Array We store all automorphic numbers found in the range into an array and print them with a total count at the end. Useful when you need to process or use the automorphic numbers further in the program. + +// Method 12: Using Macro +#include + +int autoHelper(int n) { + int sq = n * n, d = 0, div = 1, t = n; + while (t != 0) { d++; t /= 10; } + for (int i = 0; i < d; i++) div *= 10; + return sq % div == n; +} + +#define IS_AUTOMORPHIC(n) autoHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_AUTOMORPHIC(num)) + printf("%d is an Automorphic Number\n", num); + else + printf("%d is Not an Automorphic Number\n", num); + + return 0; +} +// Method 12 - Macro We define IS_AUTOMORPHIC as a macro that calls autoHelper(). Wherever IS_AUTOMORPHIC(n) is written it gets replaced by autoHelper(n). Good to know how macros wrap function calls cleanly in C. + +// Method 13: Using long long for Large Numbers +#include +int main() { + long long num, square, temp, digits = 0, divisor = 1; + + printf("Enter a number: "); + scanf("%lld", &num); + + square = num * num; + temp = num; + + while (temp != 0) { + digits++; + temp /= 10; + } + + for (int i = 0; i < digits; i++) + divisor *= 10; + + if (square % divisor == num) + printf("%lld is an Automorphic Number\n", num); + else + printf("%lld is Not an Automorphic Number\n", num); + + return 0; +} +// Method 13 - Long Long Normal int overflows for large numbers when squaring. We use long long which holds much larger values. This handles bigger automorphic numbers like 376 whose square is 141376 and 5765625 whose square ends in 5765625. diff --git a/Shaivi_Binary_to_Decimal.Q31.c b/Shaivi_Binary_to_Decimal.Q31.c new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Shaivi_Binary_to_Decimal.Q31.c @@ -0,0 +1 @@ + diff --git a/Shaivi_Factor_ofa_No.Q19.c b/Shaivi_Factor_ofa_No.Q19.c new file mode 100644 index 0000000..2955dfd --- /dev/null +++ b/Shaivi_Factor_ofa_No.Q19.c @@ -0,0 +1,300 @@ +// C Program to Find the Factors of a Number + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + for (int i = 1; i <= num; i++) { + if (num % i == 0) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 1 - For Loop We check every number from 1 to num. If num is divisible by i with no remainder then i is a factor. Simple and easy to understand but checks all numbers up to num so it is slow for large numbers. + +// Method 2: Using while Loop +#include +int main() { + int num, i = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + while (i <= num) { + if (num % i == 0) + printf("%d ", i); + i++; + } + printf("\n"); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop. We initialize i before the loop and increment it inside. Good practice to write the same factor logic using different loop types. + +// Method 3: Using do-while Loop +#include +int main() { + int num, i = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + do { + if (num % i == 0) + printf("%d ", i); + i++; + } while (i <= num); + printf("\n"); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with divisibility check logic. + +// Method 4: Using Square Root Optimization +#include +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + for (int i = 1; i <= sqrt(num); i++) { + if (num % i == 0) { + printf("%d ", i); + // print the paired factor if it is different + if (i != num / i) + printf("%d ", num / i); + } + } + printf("\n"); + + return 0; +} +// Method 4 - Square Root Optimization Factors always come in pairs. If i is a factor then num/i is also a factor. So we only check up to sqrt(num) and print both factors at once. Much faster than checking up to num. + +// Method 5: Using Function +#include +void findFactors(int num) { + printf("Factors of %d are: ", num); + for (int i = 1; i <= num; i++) + if (num % i == 0) + printf("%d ", i); + printf("\n"); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + findFactors(num); + + return 0; +} +// Method 5 - Function The factor finding logic is placed in a separate function findFactors(). Main just takes input and calls it. Code is clean reusable and well organized. Good habit for writing structured programs. + +// Method 6: Using Recursion +#include +void findFactors(int num, int i) { + if (i > num) return; + if (num % i == 0) + printf("%d ", i); + findFactors(num, i + 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + findFactors(num, 1); + printf("\n"); + + return 0; +} +// Method 6 - Recursion The function checks if i is a factor and prints it then calls itself with i+1. When i exceeds num the function stops. Good practice for understanding how recursion replaces a simple loop. + +// Method 7: Using Array to Store Factors +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int factors[num], count = 0; + + for (int i = 1; i <= num; i++) + if (num % i == 0) + factors[count++] = i; + + printf("Factors of %d are: ", num); + for (int i = 0; i < count; i++) + printf("%d ", factors[i]); + printf("\nTotal number of factors: %d\n", count); + + return 0; +} +// Method 7 - Array We store all factors in an array first then print them. We also print the total count at the end. Useful when you need to use the factors later in the program for further processing or calculations. + +// Method 8: Using Ternary Operator +#include +void findFactors(int num, int i) { + if (i > num) return; + (num % i == 0) ? printf("%d ", i) : 0; + findFactors(num, i + 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + findFactors(num, 1); + printf("\n"); + + return 0; +} +// Method 8 - Ternary Operator We use ternary inside the recursive function. If num%i is 0 we print i else we do nothing using 0. Short and compact way to print factors without writing a full if block inside recursion. + +// Method 9: Printing Factors in Pairs +#include +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factor pairs of %d are:\n", num); + for (int i = 1; i <= sqrt(num); i++) { + if (num % i == 0) { + if (i == num / i) + printf("%d x %d\n", i, i); + else + printf("%d x %d\n", i, num / i); + } + } + + return 0; +} +// Method 9 - Factor Pairs Instead of printing factors individually we print them as pairs. For every factor i we print i x num/i. If both are equal like in a perfect square we print it only once. More informative output format. + +// Method 10: Count and Print Factors +#include +int main() { + int num, count = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + for (int i = 1; i <= num; i++) { + if (num % i == 0) { + printf("%d ", i); + count++; + } + } + printf("\nTotal number of factors: %d\n", count); + + return 0; +} +// Method 10 - Count Factors Same as method 1 but we also keep a count of how many factors are found. At the end we print the total number of factors. More complete and user friendly output for the program. + +// Method 11: Check if Number is Perfect Number +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d (excluding itself) are: ", num); + for (int i = 1; i < num; i++) { + if (num % i == 0) { + printf("%d ", i); + sum += i; + } + } + + printf("\nSum of factors = %d\n", sum); + + if (sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 11 - Perfect Number Check A perfect number is one whose factors excluding itself add up to the number itself. We print all factors except num and check if their sum equals num. Example 6 = 1+2+3 so 6 is perfect. + +// Method 12: Using Macro +#include + +void factorHelper(int num) { + for (int i = 1; i <= num; i++) + if (num % i == 0) + printf("%d ", i); +} + +#define FIND_FACTORS(n) factorHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Factors of %d are: ", num); + FIND_FACTORS(num); + printf("\n"); + + return 0; +} +// Method 12 - Macro We define FIND_FACTORS as a macro that calls factorHelper(). Wherever FIND_FACTORS(n) is written it gets replaced by factorHelper(n). Good to know how macros wrap function calls cleanly in C. + +// Method 13: Sorted Factors Using Square Root +#include +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // store small and large factors separately + int small[1000], large[1000]; + int sc = 0, lc = 0; + + for (int i = 1; i <= sqrt(num); i++) { + if (num % i == 0) { + small[sc++] = i; + if (i != num / i) + large[lc++] = num / i; + } + } + + // print small factors then large factors in reverse + printf("Factors of %d in sorted order: ", num); + for (int i = 0; i < sc; i++) + printf("%d ", small[i]); + for (int i = lc - 1; i >= 0; i--) + printf("%d ", large[i]); + printf("\n"); + + return 0; +} +// Method 13 - Sorted with Square Root We collect small factors up to sqrt(num) and their pairs separately. Then print small factors forward and large factors in reverse to get a fully sorted output. Efficient and clean approach. diff --git a/Shaivi_Fibonacci.Q16.c b/Shaivi_Fibonacci.Q16.c new file mode 100644 index 0000000..4cc80b8 --- /dev/null +++ b/Shaivi_Fibonacci.Q16.c @@ -0,0 +1,272 @@ +// Fibonacci Series Program in C + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + int a = 0, b = 1; + + printf("Fibonacci Series: "); + for (int i = 1; i <= n; i++) { + printf("%d ", a); + int next = a + b; + a = b; + b = next; + } + printf("\n"); + + return 0; +} +// Method 1 - For Loop We start with a=0 and b=1. Each iteration we print a then calculate next as a+b. Then shift a=b and b=next. This moves the window forward by one step each time. + +// Method 2: Using while Loop +#include +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + int a = 0, b = 1, i = 1; + + printf("Fibonacci Series: "); + while (i <= n) { + printf("%d ", a); + int next = a + b; + a = b; + b = next; + i++; + } + printf("\n"); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but written as a while loop. We initialize i before the loop and increment it inside. Good practice to know both for and while for series problems. + +// Method 3: Using do-while Loop +#include +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + int a = 0, b = 1, i = 1; + + printf("Fibonacci Series: "); + do { + printf("%d ", a); + int next = a + b; + a = b; + b = next; + i++; + } while (i <= n); + printf("\n"); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Note: gives wrong output if n is 0 or negative. + +// Method 4: Using Function +#include +void printFibonacci(int n) { + int a = 0, b = 1; + printf("Fibonacci Series: "); + for (int i = 1; i <= n; i++) { + printf("%d ", a); + int next = a + b; + a = b; + b = next; + } + printf("\n"); +} +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + printFibonacci(n); + + return 0; +} +// Method 4 - Function The series logic is placed in a separate function printFibonacci(). Main just takes input and calls it. Code is clean reusable and well organized. Good habit for writing structured programs. + +// Method 5: Using Recursion +#include +int fibonacci(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + return fibonacci(n - 1) + fibonacci(n - 2); +} +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + printf("Fibonacci Series: "); + for (int i = 0; i < n; i++) + printf("%d ", fibonacci(i)); + printf("\n"); + + return 0; +} +// Method 5 - Recursion fibonacci(n) calls itself with n-1 and n-2 and adds the results. Base cases are 0 and 1. Simple to understand but slow for large n because it recalculates the same values many times. + +// Method 6: Using Array +#include +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + int fib[n]; + fib[0] = 0; + fib[1] = 1; + + for (int i = 2; i < n; i++) + fib[i] = fib[i - 1] + fib[i - 2]; + + printf("Fibonacci Series: "); + for (int i = 0; i < n; i++) + printf("%d ", fib[i]); + printf("\n"); + + return 0; +} +// Method 6 - Array We store all fibonacci values in an array. Each element is the sum of the two before it. Good for when you need to access any fibonacci number later in the program by its index. + +// Method 7: Using Dynamic Programming (Memoization) +#include +#define MAX 1000 + +int memo[MAX]; + +int fibonacci(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + if (memo[n] != -1) return memo[n]; + memo[n] = fibonacci(n - 1) + fibonacci(n - 2); + return memo[n]; +} +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + for (int i = 0; i < MAX; i++) + memo[i] = -1; + + printf("Fibonacci Series: "); + for (int i = 0; i < n; i++) + printf("%d ", fibonacci(i)); + printf("\n"); + + return 0; +} +// Method 7 - Memoization Same as recursion but we store already calculated values in memo array. If a value is already computed we return it directly instead of recalculating. Much faster than plain recursion. + +// Method 8: Using Recursion with Two Variables +#include +void fibRecursive(int a, int b, int n) { + if (n == 0) return; + printf("%d ", a); + fibRecursive(b, a + b, n - 1); +} +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + printf("Fibonacci Series: "); + fibRecursive(0, 1, n); + printf("\n"); + + return 0; +} +// Method 8 - Tail Recursion Instead of calculating fib(n-1)+fib(n-2) separately we pass both current and next values as arguments. Each call prints current and passes next two values. Much more efficient than method 5. + +// Method 9: Using Swap Method +#include +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + int a = 0, b = 1; + + printf("Fibonacci Series: "); + for (int i = 0; i < n; i++) { + printf("%d ", a); + // swap and add without temp variable + b = a + b; + a = b - a; + } + printf("\n"); + + return 0; +} +// Method 9 - Swap Method We update b as a+b first then recover new a as b-a. This avoids using a third temp variable for the swap. Clever trick that works correctly and saves one variable in memory. + +// Method 10: Using Matrix Exponentiation +#include +void multiply(int F[2][2], int M[2][2]) { + int a = F[0][0]*M[0][0] + F[0][1]*M[1][0]; + int b = F[0][0]*M[0][1] + F[0][1]*M[1][1]; + int c = F[1][0]*M[0][0] + F[1][1]*M[1][0]; + int d = F[1][0]*M[0][1] + F[1][1]*M[1][1]; + F[0][0]=a; F[0][1]=b; + F[1][0]=c; F[1][1]=d; +} +int fibonacci(int n) { + int F[2][2] = {{1,1},{1,0}}; + int M[2][2] = {{1,1},{1,0}}; + if (n == 0) return 0; + for (int i = 2; i < n; i++) + multiply(F, M); + return F[0][0]; +} +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + printf("Fibonacci Series: "); + for (int i = 0; i < n; i++) + printf("%d ", fibonacci(i)); + printf("\n"); + + return 0; +} +// Method 10 - Matrix Exponentiation We use the property that fibonacci numbers can be derived from matrix multiplication. Advanced method used in competitive programming. Good to know it exists and learn later. + +// Method 11: Using Golden Ratio Formula +#include +#include +int main() { + int n; + + printf("Enter the number of terms: "); + scanf("%d", &n); + + // phi = (1 + sqrt(5)) / 2 + double phi = (1 + sqrt(5)) / 2; + + printf("Fibonacci Series: "); + for (int i = 0; i < n; i++) + printf("%d ", (int)round(pow(phi, i) / sqrt(5))); + printf("\n"); + + return 0; +} +// Method 11 - Golden Ratio The nth fibonacci number can be calculated directly using the golden ratio formula phi^n/sqrt(5). Purely math based with no loop or recursion needed. Works for small values but loses precision for large n due to floating point. diff --git a/Shaivi_Greatest_Common_Divisor.Q30.c b/Shaivi_Greatest_Common_Divisor.Q30.c new file mode 100644 index 0000000..d228285 --- /dev/null +++ b/Shaivi_Greatest_Common_Divisor.Q30.c @@ -0,0 +1 @@ +// C Program to find GCD Of Two Numbers diff --git a/Shaivi_HCF.Q28.c b/Shaivi_HCF.Q28.c new file mode 100644 index 0000000..a17a8fe --- /dev/null +++ b/Shaivi_HCF.Q28.c @@ -0,0 +1,310 @@ +// HCF Of Two Numbers | C Program +// Method 1 Using for loop (Brute Force) +#include +int main() { + int a, b, hcf = 1; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + for (int i = 1; i <= a && i <= b; i++) { + if (a % i == 0 && b % i == 0) + hcf = i; + } + + printf("HCF = %d\n", hcf); + return 0; +} +// We loop from 1 to the smaller number. Every time both a and b are divisible by i, we update hcf. After the loop ends, hcf holds the greatest such divisor. Simple to understand but not efficient for large numbers + +// Method 2 Using while loop (Subtraction — Euclid) +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + while (a != b) { + if (a > b) + a = a - b; + else + b = b - a; + } + + printf("HCF = %d\n", a); + return 0; +} +// Euclid's original subtraction method. Keep subtracting the smaller number from the larger one until both are equal. That equal value is the HCF. Works correctly but is slow when numbers are far apart. + +// Method 3 Using Euclidean Algorithm (Modulo) +#include +int main() { + int a, b, temp; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + while (b != 0) { + temp = b; + b = a % b; + a = temp; + } + + printf("HCF = %d\n", a); + return 0; +} +// The fastest and most standard method. We replace a with b and b with a%b repeatedly until b becomes 0. When b is 0, a holds the HCF. This is the algorithm used in real-world programs and competitive coding. + +// Method 4 Using Recursive Function +#include + +int hcf(int a, int b) { + if (b == 0) + return a; + return hcf(b, a % b); +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + printf("HCF = %d\n", hcf(a, b)); + return 0; +} +// Euclidean modulo logic written as a recursive function. Base case: if b is 0, return a. Otherwise call hcf(b, a%b) again. Clean and elegant. Very commonly asked in interviews to test recursion understanding. + +// Method 5 Using do-while loop +#include +int main() { + int a, b, temp; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + do { + temp = b; + b = a % b; + a = temp; + } while (b != 0); + + printf("HCF = %d\n", a); + return 0; +} +// Same Euclidean modulo method but using do-while instead of while. The body always executes at least once. Since we always have two valid positive integers, this is safe and produces the same correct result. + +// Method 6 Using Ternary Operator (Recursive) +#include + +int hcf(int a, int b) { + return b == 0 ? a : hcf(b, a % b); +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + printf("HCF = %d\n", hcf(a, b)); + return 0; +} +// The full recursive function collapsed into a single return line using the ternary operator. If b is 0 return a, else recurse. Very compact. Good to write once you clearly understand the recursive version first + +// Method 7 Using Non-recursive Function +#include + +int findHCF(int a, int b) { + while (b != 0) { + int temp = b; + b = a % b; + a = temp; + } + return a; +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + printf("HCF = %d\n", findHCF(a, b)); + return 0; +} + +// Euclidean modulo logic placed inside a separate non-recursive function. Main only handles input and output. This is the cleanest and most reusable approach. Good coding practice to separate logic from I/O. + +// Method 8 Using Temp Variable (Swap method) +#include +int main() { + int a, b, temp; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + while (a % b != 0) { + temp = a % b; + a = b; + b = temp; + } + + printf("HCF = %d\n", b); + return 0; +} +// A variation of the Euclidean method where we check if a%b is 0 in the condition itself. We store a%b in temp, shift b to a and temp to b. When a%b becomes 0, b at that point is the HCF. Slightly different swap style. + +// Method 9 Using Prime Factorization +#include + +int minVal(int x, int y) { + return (x < y) ? x : y; +} + +int main() { + int a, b, hcf = 1; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + for (int i = 2; i <= minVal(a, b); i++) { + while (a % i == 0 && b % i == 0) { + hcf *= i; + a /= i; + b /= i; + } + } + + printf("HCF = %d\n", hcf); + return 0; +} +// We find common prime factors of both numbers. For each prime i starting from 2, if both a and b are divisible by i, multiply hcf by i and divide both. Repeat until no more common primes remain. Good for understanding factorization. + +// Method 10 Using Array of Divisors +#include +int main() { + int a, b, hcf = 1; + int smaller = (a < b) ? a : b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + smaller = (a < b) ? a : b; + + for (int i = smaller; i >= 1; i--) { + if (a % i == 0 && b % i == 0) { + hcf = i; + break; + } + } + + printf("HCF = %d\n", hcf); + return 0; +} + +// Instead of going upward from 1, we loop downward from the smaller number. The very first i that divides both a and b is immediately the HCF. We break out early. Fewer iterations on average compared to the upward brute force approach. + +// Method 11 Using __gcd() Built-in Function +#include +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + printf("HCF = %d\n", __gcd(a, b)); + return 0; +} +// C++ provides a built-in __gcd() function in that computes GCD directly. Works in competitive programming and quick solutions. Not available in pure C standard but supported by GCC compiler for both C and C++ files. + +// Method 12 Using Bitwise AND (Power of 2 check) +#include + +int hcf(int a, int b) { + if (a == b) return a; + if (a == 0) return b; + if (b == 0) return a; + + if (~a & 1) { + if (b & 1) + return hcf(a >> 1, b); + else + return hcf(a >> 1, b >> 1) << 1; + } + if (~b & 1) + return hcf(a, b >> 1); + + return (a > b) ? hcf(a - b, b) : hcf(a, b - a); +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + printf("HCF = %d\n", hcf(a, b)); + return 0; +} +// Binary GCD algorithm (Stein's algorithm). Uses bitwise right shift (>>) to halve even numbers and bitwise AND (&1) to check odd/even. Avoids division entirely. More efficient on hardware where division is expensive. Advanced topic — learn after basics. + +//Method 12 Using Bitwise AND (Power of 2 check) +#include + +int hcf(int a, int b) { + if (a == b) return a; + if (a == 0) return b; + if (b == 0) return a; + + if (~a & 1) { + if (b & 1) + return hcf(a >> 1, b); + else + return hcf(a >> 1, b >> 1) << 1; + } + if (~b & 1) + return hcf(a, b >> 1); + + return (a > b) ? hcf(a - b, b) : hcf(a, b - a); +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + printf("HCF = %d\n", hcf(a, b)); + return 0; +} +// Binary GCD algorithm (Stein's algorithm). Uses bitwise right shift (>>) to halve even numbers and bitwise AND (&1) to check odd/even. Avoids division entirely. More efficient on hardware where division is expensive. Advanced topic — learn after basics. + diff --git a/Shaivi_Harshad_number.Q25.c b/Shaivi_Harshad_number.Q25.c new file mode 100644 index 0000000..4401c21 --- /dev/null +++ b/Shaivi_Harshad_number.Q25.c @@ -0,0 +1,345 @@ +// C Program to Check Whether a Number is Harshad Number or Not + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + // calculate sum of digits using for loop + for (; temp != 0; temp /= 10) + sum += temp % 10; + + if (num % sum == 0) + printf("%d is a Harshad Number\n", num); + else + printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 1 - For Loop We extract each digit using %10 and add to sum using a for loop. If num is divisible by its digit sum it is a Harshad number. Example 18 has digit sum 1+8=9 and 18/9=2 so 18 is Harshad. + +// Method 2: Using while Loop +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + while (temp != 0) { + sum += temp % 10; + temp /= 10; + } + + if (num % sum == 0) + printf("%d is a Harshad Number\n", num); + else + printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop. We extract last digit using %10 add to sum then remove last digit using /10. We repeat until temp becomes 0. Most common and readable approach. + +// Method 3: Using do-while Loop +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + do { + sum += temp % 10; + temp /= 10; + } while (temp != 0); + + if (num % sum == 0) + printf("%d is a Harshad Number\n", num); + else + printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with digit sum extraction logic. + +// Method 4: Using Function +#include +int digitSum(int num) { + int sum = 0; + while (num != 0) { + sum += num % 10; + num /= 10; + } + return sum; +} +int isHarshad(int num) { + return num % digitSum(num) == 0; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isHarshad(num)) + printf("%d is a Harshad Number\n", num); + else + printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 4 - Function Logic is split into digitSum() and isHarshad() functions. digitSum() calculates the sum of digits. isHarshad() checks divisibility. Main just takes input and prints. Clean reusable and well organized code. + +// Method 5: Using Recursion +#include +int digitSum(int num) { + if (num == 0) return 0; + return (num % 10) + digitSum(num / 10); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int sum = digitSum(num); + + if (num % sum == 0) + printf("%d is a Harshad Number\n", num); + else + printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 5 - Recursion digitSum() calls itself with num/10 each time and adds the last digit. When num becomes 0 it returns 0. Good practice for understanding how recursion replaces a digit extraction loop cleanly. + +// Method 6: Using String +#include +#include +int main() { + char numStr[20]; + int sum = 0; + + printf("Enter a number: "); + scanf("%s", numStr); + + int len = strlen(numStr); + + for (int i = 0; i < len; i++) + sum += numStr[i] - '0'; + + int original = 0; + for (int i = 0; i < len; i++) + original = original * 10 + (numStr[i] - '0'); + + if (original % sum == 0) + printf("%s is a Harshad Number\n", numStr); + else + printf("%s is Not a Harshad Number\n", numStr); + + return 0; +} +// Method 6 - String We take the number as a string. Each character is converted to digit by subtracting '0' then added to sum. We also rebuild the original number from the string to check divisibility at the end. + +// Method 7: Using Array to Store Digits +#include +int main() { + int num, sum = 0, temp; + int digits[20], count = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + // store each digit in array + while (temp != 0) { + digits[count++] = temp % 10; + temp /= 10; + } + + // sum all digits from array + for (int i = 0; i < count; i++) + sum += digits[i]; + + if (num % sum == 0) + printf("%d is a Harshad Number\n", num); + else + printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 7 - Array We extract each digit using %10 and store in an array. Then loop through the array to calculate sum. Not the most efficient way but good practice combining arrays with digit extraction logic in C. + +// Method 8: Using Ternary Operator +#include +int digitSum(int n) { + int s = 0; + while (n != 0) { s += n % 10; n /= 10; } + return s; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? true : false + (num % digitSum(num) == 0) + ? printf("%d is a Harshad Number\n", num) + : printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 8 - Ternary Operator We call digitSum() inside the ternary condition directly. If num is divisible by its digit sum print yes else print no. All output handled in one clean single statement. Compact and concise version. + +// Method 9: Using switch Statement +#include +int digitSum(int n) { + int s = 0; + while (n != 0) { s += n % 10; n /= 10; } + return s; +} +int isHarshad(int num) { + return num % digitSum(num) == 0; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isHarshad() returns 1 if true and 0 if false + switch (isHarshad(num)) { + case 1: + printf("%d is a Harshad Number\n", num); + break; + case 0: + printf("%d is Not a Harshad Number\n", num); + break; + } + + return 0; +} +// Method 9 - Switch Case isHarshad() returns 1 for Harshad and 0 for not Harshad. Switch works on these values. Case 1 means Harshad number and case 0 means not. Good practice combining function with switch statement. + +// Method 10: Print Harshad Numbers in a Given Range +#include +int digitSum(int n) { + int s = 0; + while (n != 0) { s += n % 10; n /= 10; } + return s; +} +int isHarshad(int num) { + return num % digitSum(num) == 0; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Harshad numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (i > 0 && isHarshad(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 10 - Range We check every number in the given range and print if it is Harshad. We skip 0 since digit sum would be 0 causing division by zero. Common Harshad numbers include 1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30. + +// Method 11: Using Array to Store Harshad Numbers in Range +#include +int digitSum(int n) { + int s = 0; + while (n != 0) { s += n % 10; n /= 10; } + return s; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int result[1000], count = 0; + + for (int i = start; i <= end; i++) + if (i > 0 && i % digitSum(i) == 0) + result[count++] = i; + + printf("Harshad numbers between %d and %d are: ", start, end); + for (int i = 0; i < count; i++) + printf("%d ", result[i]); + printf("\nTotal Harshad numbers found: %d\n", count); + + return 0; +} +// Method 11 - Array with Count We store all Harshad numbers found in the range in an array and also print the total count at the end. Useful when you need to use the Harshad numbers further in the program for processing. + +// Method 12: Using Macro +#include + +int dsHelper(int n) { + int s = 0; + while (n != 0) { s += n % 10; n /= 10; } + return s; +} + +#define IS_HARSHAD(n) ((n) % dsHelper(n) == 0) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_HARSHAD(num)) + printf("%d is a Harshad Number\n", num); + else + printf("%d is Not a Harshad Number\n", num); + + return 0; +} +// Method 12 - Macro We define IS_HARSHAD as a macro that computes digit sum and checks divisibility inline. Wherever IS_HARSHAD(n) is written it gets replaced by the full expression. Good to know how macros work in C. + +// Method 13: Printing Digit Sum and Quotient +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + while (temp != 0) { + sum += temp % 10; + temp /= 10; + } + + printf("Sum of digits of %d = %d\n", num, sum); + + if (num % sum == 0) { + printf("%d / %d = %d\n", num, sum, num / sum); + printf("%d is a Harshad Number\n", num); + } else { + printf("%d is not exactly divisible by %d\n", num, sum); + printf("%d is Not a Harshad Number\n", num); + } + + return 0; +} +// Method 13 - Detailed Output We print the digit sum and the result of dividing num by sum before the final verdict. This makes the output more informative and educational. Good for understanding why a number is or is not Harshad. diff --git a/Shaivi_LCM.Q29.c b/Shaivi_LCM.Q29.c new file mode 100644 index 0000000..cec8520 --- /dev/null +++ b/Shaivi_LCM.Q29.c @@ -0,0 +1,291 @@ +// C Program to Find the LCM of Two Numbers + +// Method 1: Using for loop (Brute Force) +#include +int main() { + int a, b, lcm; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + lcm = (a > b) ? a : b; + + while (1) { + if (lcm % a == 0 && lcm % b == 0) { + printf("LCM = %d\n", lcm); + break; + } + lcm++; + } + + return 0; +} +// Method 1 - for loop (Brute Force) We start from the larger of the two numbers and keep incrementing. The first number divisible by both a and b is the LCM. Simple logic but slow for large numbers. + + +// Method 2: Using while loop +#include +int main() { + int a, b, lcm, max; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + max = (a > b) ? a : b; + lcm = max; + + while (lcm % a != 0 || lcm % b != 0) + lcm += max; + + printf("LCM = %d\n", lcm); + return 0; +} +// Method 2 - while loop We start from the larger number and keep adding it to itself. We only check multiples of the larger number, which reduces iterations. When it also divides the smaller one it is the LCM. + + +// Method 3: Using LCM = (a * b) / HCF Formula +#include +int main() { + int a, b, x, y, hcf, lcm; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + x = a; y = b; + while (y != 0) { + int temp = y; + y = x % y; + x = temp; + } + hcf = x; + lcm = (a / hcf) * b; + + printf("LCM = %d\n", lcm); + return 0; +} +// Method 3 - LCM Formula LCM(a, b) = (a * b) / HCF(a, b). We first find HCF using the Euclidean algorithm then apply the formula. We divide before multiplying to avoid integer overflow. Most efficient method. + + +// Method 4: Using Recursive Function (HCF then LCM) +#include + +int hcf(int a, int b) { + if (b == 0) + return a; + return hcf(b, a % b); +} + +int main() { + int a, b, lcm; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + lcm = (a / hcf(a, b)) * b; + + printf("LCM = %d\n", lcm); + return 0; +} +// Method 4 - Recursive Function We compute HCF using a clean recursive function and then apply the LCM formula. Separating HCF logic into its own function makes the code reusable and readable. Common in interviews. + + +// Method 5: Using do-while loop +#include +int main() { + int a, b, lcm; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + lcm = (a > b) ? a : b; + + do { + if (lcm % a == 0 && lcm % b == 0) { + printf("LCM = %d\n", lcm); + break; + } + lcm++; + } while (1); + + return 0; +} +// Method 5 - do-while loop Same brute force approach but using do-while. The body runs at least once. We start from the larger number and increment until we find a value divisible by both. Good for practicing do-while syntax. + + +// Method 6: Using Non-recursive Function +#include + +int findLCM(int a, int b) { + int lcm = (a > b) ? a : b; + while (lcm % a != 0 || lcm % b != 0) + lcm++; + return lcm; +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + printf("LCM = %d\n", findLCM(a, b)); + return 0; +} +// Method 6 - Non-recursive Function The LCM logic is moved into a separate function findLCM(). Main only handles input and output. Clean and reusable. Good practice to separate logic from I/O in real programs. + + +// Method 7: Using Ternary Operator +#include + +int hcf(int a, int b) { + return b == 0 ? a : hcf(b, a % b); +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + int lcm = (a / hcf(a, b)) * b; + printf("LCM = %d\n", lcm); + return 0; +} +// Method 7 - Ternary Operator We write the HCF recursive function in a single line using the ternary operator. Then use the LCM formula directly in main. Compact and clean once the logic is understood. + + +// Method 8: Using Temp Variable (Step-up method) +#include +int main() { + int a, b, lcm; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + int i = 1; + while (1) { + lcm = a * i; + if (lcm % b == 0) { + printf("LCM = %d\n", lcm); + break; + } + i++; + } + + return 0; +} +// Method 8 - Temp Variable (Step-up) We generate multiples of a one by one using a counter i. For each multiple of a we check if it is also divisible by b. The first such multiple is the LCM. Clean and easy to trace step by step. + + +// Method 9: Using Array to Store Multiples +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + for (int i = 1; i <= a * b; i++) { + if (i % a == 0 && i % b == 0) { + printf("LCM = %d\n", i); + break; + } + } + + return 0; +} +// Method 9 - Loop up to a*b LCM of two numbers can never exceed a*b so we loop from 1 to a*b. The first number divisible by both is the LCM and we break immediately. Guaranteed to find the answer within the range. + + +// Method 10: Using __lcm() / __gcd() Built-in +#include +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + int lcm = (a / __gcd(a, b)) * b; + printf("LCM = %d\n", lcm); + return 0; +} +// Method 10 - Built-in __gcd() GCC provides __gcd() in . We use it directly in the LCM formula without writing our own HCF. Best for quick solutions in competitive programming. Not standard C but works with GCC compiler. + + +// Method 11: Using Pointers +#include + +void findLCM(int *a, int *b, int *lcm) { + int x = *a, y = *b; + while (y != 0) { + int temp = y; + y = x % y; + x = temp; + } + *lcm = (*a / x) * *b; +} + +int main() { + int a, b, lcm; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + findLCM(&a, &b, &lcm); + printf("LCM = %d\n", lcm); + return 0; +} +// Method 11 - Pointers We pass all variables by pointer to the function. The function computes HCF using Euclidean algorithm then stores the LCM result directly into the pointer. Good for practicing pass-by-reference using pointers in C. + + +// Method 12: Using Bitwise (Binary GCD then LCM) +#include + +int binaryGCD(int a, int b) { + if (a == b) return a; + if (a == 0) return b; + if (b == 0) return a; + if (~a & 1) { + if (b & 1) return binaryGCD(a >> 1, b); + else return binaryGCD(a >> 1, b >> 1) << 1; + } + if (~b & 1) return binaryGCD(a, b >> 1); + return (a > b) ? binaryGCD(a - b, b) : binaryGCD(a, b - a); +} + +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + int lcm = (a / binaryGCD(a, b)) * b; + printf("LCM = %d\n", lcm); + return 0; +} +// Method 12 - Bitwise (Stein's Algorithm) We compute GCD using the Binary GCD (Stein's) algorithm which uses bitwise shifts and AND instead of division. Then apply LCM formula. No modulo or division used inside GCD. Advanced topic for after basics are done. diff --git a/Shaivi_Octal_to_Decimal.Q32.c b/Shaivi_Octal_to_Decimal.Q32.c new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Shaivi_Octal_to_Decimal.Q32.c @@ -0,0 +1 @@ + diff --git a/Shaivi_Palindrome.Q13.c b/Shaivi_Palindrome.Q13.c new file mode 100644 index 0000000..edb59ac --- /dev/null +++ b/Shaivi_Palindrome.Q13.c @@ -0,0 +1,319 @@ +// Palindrome Program in C + +// Method 1: Using while Loop (Brute Force) +#include +int main() { + int num, original, reversed = 0, remainder; + + printf("Enter a number: "); + scanf("%d", &num); + + original = num; + + while (num != 0) { + remainder = num % 10; + reversed = reversed * 10 + remainder; + num = num / 10; + } + + if (original == reversed) + printf("%d is a Palindrome\n", original); + else + printf("%d is Not a Palindrome\n", original); + + return 0; +} +// Method 1 - While Loop We reverse the number using %10 and /10 and store it in reversed. Then compare original with reversed. If both are equal the number reads same from both sides so it is palindrome. + +// Method 2: Using for Loop +#include +int main() { + int num, original, reversed = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + original = num; + + for (; num != 0; num /= 10) + reversed = reversed * 10 + (num % 10); + + if (original == reversed) + printf("%d is a Palindrome\n", original); + else + printf("%d is Not a Palindrome\n", original); + + return 0; +} +// Method 2 - For Loop Same logic as method 1 but written as a for loop. Initialization is empty since variables are already set. num /= 10 removes last digit each time. Compact and clean version. + +// Method 3: Using do-while Loop +#include +int main() { + int num, original, reversed = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + original = num; + + do { + reversed = reversed * 10 + (num % 10); + num /= 10; + } while (num != 0); + + if (original == reversed) + printf("%d is a Palindrome\n", original); + else + printf("%d is Not a Palindrome\n", original); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with number reversal logic. + +// Method 4: Using Function +#include +int isPalindrome(int num) { + int original = num, reversed = 0; + while (num != 0) { + reversed = reversed * 10 + (num % 10); + num /= 10; + } + return original == reversed; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPalindrome(num)) + printf("%d is a Palindrome\n", num); + else + printf("%d is Not a Palindrome\n", num); + + return 0; +} +// Method 4 - Function The palindrome logic is placed in a separate function isPalindrome() that returns 1 if true and 0 if false. Main just takes input and prints. Clean reusable and well organized code. + +// Method 5: Using Recursion +#include +int reverseNum(int num, int rev) { + if (num == 0) + return rev; + return reverseNum(num / 10, rev * 10 + (num % 10)); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int reversed = reverseNum(num, 0); + + if (num == reversed) + printf("%d is a Palindrome\n", num); + else + printf("%d is Not a Palindrome\n", num); + + return 0; +} +// Method 5 - Recursion We use a recursive function to reverse the number. It passes the reversed value as a second argument and builds it up each call. When num is 0 the final reversed number is returned. + +// Method 6: Using String +#include +#include +int main() { + char numStr[20]; + + printf("Enter a number: "); + scanf("%s", numStr); + + int len = strlen(numStr); + int isPalin = 1; + + for (int i = 0; i < len / 2; i++) { + if (numStr[i] != numStr[len - 1 - i]) { + isPalin = 0; + break; + } + } + + if (isPalin) + printf("%s is a Palindrome\n", numStr); + else + printf("%s is Not a Palindrome\n", numStr); + + return 0; +} +// Method 6 - String We take the number as a string and compare characters from both ends moving towards the middle. If any pair does not match it is not a palindrome. Good for practicing string logic in C. + +// Method 7: Using Array +#include +int main() { + int num, digits[20], count = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + int original = num; + + while (num != 0) { + digits[count++] = num % 10; + num /= 10; + } + + // digits array has digits in reverse order already + // rebuild original from array and compare + int rebuilt = 0; + for (int i = 0; i < count; i++) + rebuilt = rebuilt * 10 + digits[i]; + + if (original == rebuilt) + printf("%d is a Palindrome\n", original); + else + printf("%d is Not a Palindrome\n", original); + + return 0; +} +// Method 7 - Array We store digits in an array using %10 which gives digits in reverse order. Then rebuild the number from the array and compare with original. Good practice combining arrays with number logic. + +// Method 8: Using Ternary Operator +#include +int reverseNum(int num, int rev) { + return (num == 0) ? rev : reverseNum(num / 10, rev * 10 + (num % 10)); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int reversed = reverseNum(num, 0); + + (num == reversed) + ? printf("%d is a Palindrome\n", num) + : printf("%d is Not a Palindrome\n", num); + + return 0; +} +// Method 8 - Ternary Operator We use recursive reversal to get reversed number then use ternary to print result in one statement. Short and clean version combining recursion and ternary together. + +// Method 9: Using Two Pointer on String +#include +#include +int main() { + char numStr[20]; + + printf("Enter a number: "); + scanf("%s", numStr); + + int left = 0, right = strlen(numStr) - 1; + int isPalin = 1; + + // two pointers moving from both ends towards middle + while (left < right) { + if (numStr[left] != numStr[right]) { + isPalin = 0; + break; + } + left++; + right--; + } + + if (isPalin) + printf("%s is a Palindrome\n", numStr); + else + printf("%s is Not a Palindrome\n", numStr); + + return 0; +} +// Method 9 - Two Pointer We use two pointers left and right starting from both ends of the string. Move them towards the middle comparing characters at each step. If mismatch found it is not a palindrome. + +// Method 10: Using switch Statement +#include +int isPalindrome(int num) { + int original = num, reversed = 0; + while (num != 0) { + reversed = reversed * 10 + (num % 10); + num /= 10; + } + return original == reversed; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isPalindrome() returns 1 if true and 0 if false + switch (isPalindrome(num)) { + case 1: + printf("%d is a Palindrome\n", num); + break; + case 0: + printf("%d is Not a Palindrome\n", num); + break; + } + + return 0; +} +// Method 10 - Switch Case isPalindrome() returns 1 for palindrome and 0 for not palindrome. Switch works on these values. Case 1 means palindrome and case 0 means not palindrome. Good practice combining function with switch. + +// Method 11: Using Macro +#include + +int reverseHelper(int num) { + int rev = 0; + while (num != 0) { + rev = rev * 10 + (num % 10); + num /= 10; + } + return rev; +} + +#define IS_PALINDROME(n) ((n) == reverseHelper(n)) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_PALINDROME(num)) + printf("%d is a Palindrome\n", num); + else + printf("%d is Not a Palindrome\n", num); + + return 0; +} +// Method 11 - Macro We define IS_PALINDROME as a macro that compares num with its reverse. Wherever IS_PALINDROME(n) is written it gets replaced by the full comparison. Good to know how macros work in C. + +// Method 12: Using abs() for Negative Numbers +#include +#include +int main() { + int num, reversed = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + // negative numbers are never palindrome but we handle it cleanly + int temp = abs(num); + int original = temp; + + while (temp != 0) { + reversed = reversed * 10 + (temp % 10); + temp /= 10; + } + + if (num < 0) + printf("%d is Not a Palindrome\n", num); + else if (original == reversed) + printf("%d is a Palindrome\n", num); + else + printf("%d is Not a Palindrome\n", num); + + return 0; +} +// Method 12 - Negative Numbers Negative numbers are never palindromes because of the minus sign. We handle this cleanly by checking sign first. abs() from stdlib.h removes the minus for safe processing. diff --git a/Shaivi_Power_no.Q18.c b/Shaivi_Power_no.Q18.c new file mode 100644 index 0000000..9873044 --- /dev/null +++ b/Shaivi_Power_no.Q18.c @@ -0,0 +1,299 @@ +// C Program to Print Power of a Number + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int base, exp; + long long result = 1; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + for (int i = 1; i <= exp; i++) + result *= base; + + printf("%d ^ %d = %lld\n", base, exp, result); + + return 0; +} +// Method 1 - For Loop We multiply result by base exp times. We start result at 1 and keep multiplying. long long is used to handle large values. Most basic and easy to understand way to calculate power. + +// Method 2: Using while Loop +#include +int main() { + int base, exp; + long long result = 1; + int i = 1; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + while (i <= exp) { + result *= base; + i++; + } + + printf("%d ^ %d = %lld\n", base, exp, result); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop. We initialize i before the loop and increment it inside. Good practice to write the same power logic using different loop types. + +// Method 3: Using do-while Loop +#include +int main() { + int base, exp; + long long result = 1; + int i = 1; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + if (exp == 0) { + printf("%d ^ %d = 1\n", base, exp); + } else { + do { + result *= base; + i++; + } while (i <= exp); + printf("%d ^ %d = %lld\n", base, exp, result); + } + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. We handle exp=0 separately since any number to power 0 is 1. Completes all 3 loop types for this problem. Good to know edge cases. + +// Method 4: Using pow() Function +#include +#include +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + long long result = (long long)pow(base, exp); + + printf("%d ^ %d = %lld\n", base, exp, result); + + return 0; +} +// Method 4 - pow() Function The math.h library provides a built in pow() function that takes base and exponent and returns the result. We cast it to long long to avoid floating point display. Simplest one liner method. + +// Method 5: Using Function +#include +long long power(int base, int exp) { + long long result = 1; + for (int i = 1; i <= exp; i++) + result *= base; + return result; +} +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %lld\n", base, exp, power(base, exp)); + + return 0; +} +// Method 5 - Function The power logic is placed in a separate function power() that takes base and exp and returns the result. Main just handles input and output. Clean reusable and well organized code. + +// Method 6: Using Recursion +#include +long long power(int base, int exp) { + if (exp == 0) return 1; + return base * power(base, exp - 1); +} +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %lld\n", base, exp, power(base, exp)); + + return 0; +} +// Method 6 - Recursion The function multiplies base with the result of calling itself with exp-1. When exp reaches 0 it returns 1 which is the base case. Good practice for understanding recursive multiplication. + +// Method 7: Using Fast Power (Binary Exponentiation) +#include +long long fastPower(int base, int exp) { + long long result = 1; + long long b = base; + + while (exp > 0) { + // if exp is odd multiply result by base + if (exp % 2 == 1) + result *= b; + b *= b; + exp /= 2; + } + return result; +} +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %lld\n", base, exp, fastPower(base, exp)); + + return 0; +} +// Method 7 - Binary Exponentiation Instead of multiplying exp times we halve the exponent each step. If exp is odd we multiply result by base. This reduces the number of multiplications from n to log(n). Very fast method. + +// Method 8: Using Recursive Fast Power +#include +long long fastPower(int base, int exp) { + if (exp == 0) return 1; + if (exp % 2 == 0) { + long long half = fastPower(base, exp / 2); + return half * half; + } + return base * fastPower(base, exp - 1); +} +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %lld\n", base, exp, fastPower(base, exp)); + + return 0; +} +// Method 8 - Recursive Fast Power If exp is even we calculate half power and square it. If odd we multiply base once and reduce exp by 1. This is the recursive version of binary exponentiation. Very efficient method. + +// Method 9: Using Ternary Operator +#include +long long power(int base, int exp) { + return (exp == 0) ? 1 : base * power(base, exp - 1); +} +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %lld\n", base, exp, power(base, exp)); + + return 0; +} +// Method 9 - Ternary Operator The entire recursive function is written in a single line using ternary. If exp is 0 return 1 else multiply base with recursive call. Compact and clean version of method 6. + +// Method 10: Handling Negative Exponents +#include +#include +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + if (exp < 0) { + // negative exponent means 1 / base^|exp| + double result = 1.0 / pow(base, -exp); + printf("%d ^ %d = %lf\n", base, exp, result); + } else { + long long result = (long long)pow(base, exp); + printf("%d ^ %d = %lld\n", base, exp, result); + } + + return 0; +} +// Method 10 - Negative Exponents Normal methods only work for positive exponents. For negative exponents the result is 1 divided by base raised to the absolute value of exp. We use double to show the decimal result. + +// Method 11: Print All Powers from 1 to N +#include +int main() { + int base, n; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter value of N: "); + scanf("%d", &n); + + long long result = 1; + + printf("Powers of %d from 1 to %d:\n", base, n); + for (int i = 1; i <= n; i++) { + result *= base; + printf("%d ^ %d = %lld\n", base, i, result); + } + + return 0; +} +// Method 11 - All Powers 1 to N Instead of finding just one power we print all powers from 1 to n. We keep multiplying result by base and print each step. Useful for seeing the full growth of a power series. + +// Method 12: Using Macro +#include +#include + +#define POWER(b, e) ((long long)pow(b, e)) + +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %lld\n", base, exp, POWER(base, exp)); + + return 0; +} +// Method 12 - Macro We define POWER as a macro that wraps the pow() function with a cast to long long. Wherever POWER(b,e) is written it gets replaced by the full expression. Good to know how macros simplify repeated expressions. + +// Method 13: Using Bitwise Operator +#include +long long power(int base, int exp) { + long long result = 1; + long long b = base; + + while (exp > 0) { + // check if last bit is 1 using & operator + if (exp & 1) + result *= b; + b *= b; + // right shift to remove last bit + exp >>= 1; + } + return result; +} +int main() { + int base, exp; + + printf("Enter base: "); + scanf("%d", &base); + printf("Enter exponent: "); + scanf("%d", &exp); + + printf("%d ^ %d = %lld\n", base, exp, power(base, exp)); + + return 0; +} +// Method 13 - Bitwise Same as binary exponentiation but we use bitwise & to check if exp is odd and >>= to halve it. exp & 1 checks the last bit. exp >>= 1 removes the last bit. Faster and more low level version. diff --git a/Shaivi_Prime_factor_ofa_no.Q20.c b/Shaivi_Prime_factor_ofa_no.Q20.c new file mode 100644 index 0000000..8136a8d --- /dev/null +++ b/Shaivi_Prime_factor_ofa_no.Q20.c @@ -0,0 +1,357 @@ +// Prime Factors of a Number in C + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Prime factors of %d are: ", num); + for (int i = 2; i <= num; i++) { + while (num % i == 0) { + printf("%d ", i); + num /= i; + } + } + printf("\n"); + + return 0; +} +// Method 1 - For Loop We start from 2 and keep dividing num by i as long as it is divisible. This ensures only prime factors are printed because all smaller factors are already divided out before reaching larger ones. + +// Method 2: Using while Loop +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Prime factors of %d are: ", num); + int i = 2; + while (i <= num) { + while (num % i == 0) { + printf("%d ", i); + num /= i; + } + i++; + } + printf("\n"); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but outer loop is a while loop. We initialize i before the loop and increment it at the end. Good practice to write the same logic using different loop types. + +// Method 3: Using Square Root Optimization +#include +#include +int main() { + int num, original; + + printf("Enter a number: "); + scanf("%d", &num); + + original = num; + printf("Prime factors of %d are: ", original); + + // divide out all small prime factors up to sqrt + for (int i = 2; i <= sqrt(num); i++) { + while (num % i == 0) { + printf("%d ", i); + num /= i; + } + } + + // if remaining num is greater than 1 it is a prime factor + if (num > 1) + printf("%d ", num); + printf("\n"); + + return 0; +} +// Method 3 - Square Root We only check divisors up to sqrt(num). After dividing out all small factors if num is still greater than 1 that remaining value is itself a large prime factor. Much faster than method 1. + +// Method 4: Using Function +#include +#include +void primeFactors(int num) { + printf("Prime factors of %d are: ", num); + for (int i = 2; i <= sqrt(num); i++) { + while (num % i == 0) { + printf("%d ", i); + num /= i; + } + } + if (num > 1) + printf("%d ", num); + printf("\n"); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + primeFactors(num); + + return 0; +} +// Method 4 - Function The prime factorization logic is placed in a separate function primeFactors(). Main just takes input and calls it. Code is clean reusable and well organized. Good habit for structured programs. + +// Method 5: Using Recursion +#include +void primeFactors(int num, int i) { + if (num <= 1) return; + if (num % i == 0) { + printf("%d ", i); + primeFactors(num / i, i); + } else { + primeFactors(num, i + 1); + } +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Prime factors of %d are: ", num); + primeFactors(num, 2); + printf("\n"); + + return 0; +} +// Method 5 - Recursion If num is divisible by i we print i and recurse with num/i. If not we recurse with i+1. When num becomes 1 we stop. Good practice for understanding how recursion replaces nested loops. + +// Method 6: Using Array to Store Prime Factors +#include +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int factors[100], count = 0; + int temp = num; + + for (int i = 2; i <= sqrt(temp); i++) { + while (temp % i == 0) { + factors[count++] = i; + temp /= i; + } + } + if (temp > 1) + factors[count++] = temp; + + printf("Prime factors of %d are: ", num); + for (int i = 0; i < count; i++) + printf("%d ", factors[i]); + printf("\nTotal prime factors: %d\n", count); + + return 0; +} +// Method 6 - Array We store all prime factors in an array first then print them along with the total count. Useful when you need to use the prime factors later in the program for further processing or calculations. + +// Method 7: Using Sieve of Eratosthenes +#include +#define MAX 100000 +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // build smallest prime factor sieve + int spf[MAX]; + for (int i = 0; i < MAX; i++) + spf[i] = i; + + for (int i = 2; i * i < MAX; i++) { + if (spf[i] == i) { + for (int j = i * i; j < MAX; j += i) + if (spf[j] == j) + spf[j] = i; + } + } + + printf("Prime factors of %d are: ", num); + int temp = num; + while (temp != 1) { + printf("%d ", spf[temp]); + temp /= spf[temp]; + } + printf("\n"); + + return 0; +} +// Method 7 - Sieve We precompute the smallest prime factor for every number using a sieve. Then repeatedly divide num by its smallest prime factor. Very fast for multiple queries as sieve is built only once. + +// Method 8: Print Unique Prime Factors Only +#include +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Unique prime factors of %d are: ", num); + for (int i = 2; i <= sqrt(num); i++) { + if (num % i == 0) { + printf("%d ", i); + while (num % i == 0) + num /= i; + } + } + if (num > 1) + printf("%d ", num); + printf("\n"); + + return 0; +} +// Method 8 - Unique Factors Instead of printing repeated prime factors we print each unique prime factor only once. We divide out all occurrences before moving to next. Example for 12 we print 2 3 instead of 2 2 3. + +// Method 9: Print Prime Factors with Their Powers +#include +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Prime factorization of %d: ", num); + for (int i = 2; i <= sqrt(num); i++) { + if (num % i == 0) { + int power = 0; + while (num % i == 0) { + power++; + num /= i; + } + if (power == 1) + printf("%d ", i); + else + printf("%d^%d ", i, power); + } + } + if (num > 1) + printf("%d ", num); + printf("\n"); + + return 0; +} +// Method 9 - With Powers We count how many times each prime factor divides num and store it as power. If power is 1 we just print the factor. If greater than 1 we print factor^power. Example 12 prints as 2^2 3. + +// Method 10: Using do-while Loop +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Prime factors of %d are: ", num); + int i = 2; + do { + if (num % i == 0) { + do { + printf("%d ", i); + num /= i; + } while (num % i == 0); + } + i++; + } while (i <= num); + printf("\n"); + + return 0; +} +// Method 10 - do-while Loop Both outer and inner loops use do-while. Body always runs at least once before condition check. Completes all 3 loop types for this problem. Good practice nesting do-while loops together. + +// Method 11: Using Ternary and Recursion +#include +void primeFactors(int num, int i) { + if (num <= 1) return; + (num % i == 0) ? (printf("%d ", i), primeFactors(num / i, i)) + : primeFactors(num, i + 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Prime factors of %d are: ", num); + primeFactors(num, 2); + printf("\n"); + + return 0; +} +// Method 11 - Ternary with Recursion The recursive logic is compressed into a single ternary line. If divisible print and recurse with num/i else recurse with i+1. Compact and clean version that combines ternary and recursion together. + +// Method 12: Using Macro +#include +#include + +void pfHelper(int num) { + for (int i = 2; i <= sqrt(num); i++) { + while (num % i == 0) { + printf("%d ", i); + num /= i; + } + } + if (num > 1) printf("%d ", num); +} + +#define PRIME_FACTORS(n) pfHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Prime factors of %d are: ", num); + PRIME_FACTORS(num); + printf("\n"); + + return 0; +} +// Method 12 - Macro We define PRIME_FACTORS as a macro that calls pfHelper(). Wherever PRIME_FACTORS(n) is written it gets replaced by pfHelper(n). Good to know how macros wrap function calls cleanly in C. + +// Method 13: Check if Number is Prime then Factor +#include +#include +int isPrime(int n) { + if (n <= 1) return 0; + for (int i = 2; i * i <= n; i++) + if (n % i == 0) return 0; + return 1; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPrime(num)) { + printf("%d is itself a Prime Number\n", num); + printf("Prime factors of %d are: %d\n", num, num); + } else { + int temp = num; + printf("Prime factors of %d are: ", num); + for (int i = 2; i <= sqrt(temp); i++) { + while (temp % i == 0) { + printf("%d ", i); + temp /= i; + } + } + if (temp > 1) printf("%d ", temp); + printf("\n"); + } + + return 0; +} +// Method 13 - Prime Check First We first check if the number itself is prime. If it is we print it directly as its own prime factor. If not we proceed with normal factorization. Adds an extra check for a cleaner and smarter output. diff --git a/Shaivi_Strong_Number.Q21.c b/Shaivi_Strong_Number.Q21.c new file mode 100644 index 0000000..76e7ede --- /dev/null +++ b/Shaivi_Strong_Number.Q21.c @@ -0,0 +1,370 @@ +// Strong Number Program in C + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + while (temp != 0) { + int digit = temp % 10; + + // calculate factorial of digit + int fact = 1; + for (int i = 1; i <= digit; i++) + fact *= i; + + sum += fact; + temp /= 10; + } + + if (sum == num) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 1 - For Loop We extract each digit using %10 then calculate its factorial using a for loop. Add all factorials to sum. If sum equals original number it is a Strong number. Example 145 = 1! + 4! + 5! = 145. + +// Method 2: Using while Loop +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + while (temp != 0) { + int digit = temp % 10; + + // calculate factorial using while loop + int fact = 1, i = 1; + while (i <= digit) { + fact *= i; + i++; + } + + sum += fact; + temp /= 10; + } + + if (sum == num) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but the factorial calculation uses a while loop instead of for loop. We initialize i before and increment inside. Good practice using while loop for factorial inside a while loop. + +// Method 3: Using do-while Loop +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + do { + int digit = temp % 10; + + int fact = 1; + for (int i = 1; i <= digit; i++) + fact *= i; + + sum += fact; + temp /= 10; + } while (temp != 0); + + if (sum == num) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with digit extraction and factorial logic. + +// Method 4: Using Function +#include +int factorial(int n) { + int fact = 1; + for (int i = 1; i <= n; i++) + fact *= i; + return fact; +} +int isStrong(int num) { + int temp = num, sum = 0; + while (temp != 0) { + sum += factorial(temp % 10); + temp /= 10; + } + return sum == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isStrong(num)) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 4 - Function Logic is split into two functions. factorial() calculates factorial of a digit and isStrong() checks the condition. Main just takes input and prints. Clean reusable and well organized code structure. + +// Method 5: Using Recursion +#include +int factorial(int n) { + if (n == 0 || n == 1) return 1; + return n * factorial(n - 1); +} +int strongSum(int num) { + if (num == 0) return 0; + return factorial(num % 10) + strongSum(num / 10); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int sum = strongSum(num); + + if (sum == num) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 5 - Recursion Two recursive functions are used. factorial() calculates digit factorial recursively. strongSum() extracts each digit recursively and adds its factorial. When num becomes 0 it returns 0 and stops. + +// Method 6: Using Precomputed Factorial Array +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + // precompute factorials of 0 to 9 + int fact[10]; + fact[0] = 1; + for (int i = 1; i <= 9; i++) + fact[i] = fact[i - 1] * i; + + temp = num; + while (temp != 0) { + sum += fact[temp % 10]; + temp /= 10; + } + + if (sum == num) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 6 - Precomputed Array Since digits are only 0 to 9 we precompute all factorials once and store in an array. Then just look up fact[digit] directly instead of recalculating each time. Faster and more efficient method. + +// Method 7: Using String +#include +#include +int main() { + char numStr[20]; + int sum = 0; + + printf("Enter a number: "); + scanf("%s", numStr); + + int len = strlen(numStr); + + // precompute factorials 0 to 9 + int fact[10]; + fact[0] = 1; + for (int i = 1; i <= 9; i++) + fact[i] = fact[i - 1] * i; + + for (int i = 0; i < len; i++) + sum += fact[numStr[i] - '0']; + + int original = 0; + for (int i = 0; i < len; i++) + original = original * 10 + (numStr[i] - '0'); + + if (sum == original) + printf("%s is a Strong Number\n", numStr); + else + printf("%s is Not a Strong Number\n", numStr); + + return 0; +} +// Method 7 - String We take the number as a string. Each character is converted to digit by subtracting '0'. Factorial is looked up from precomputed array. No need to extract digits manually using %10 and /10. + +// Method 8: Using Ternary Operator +#include +int factorial(int n) { + int f = 1; + for (int i = 1; i <= n; i++) f *= i; + return f; +} +int strongSum(int n) { + int s = 0, t = n; + while (t != 0) { s += factorial(t % 10); t /= 10; } + return s; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? true : false + (strongSum(num) == num) + ? printf("%d is a Strong Number\n", num) + : printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 8 - Ternary Operator We call strongSum() inside a ternary condition directly. If sum equals num print yes else print no. All output handled in one clean single statement. Compact version combining functions and ternary. + +// Method 9: Using switch Statement +#include +int factorial(int n) { + int f = 1; + for (int i = 1; i <= n; i++) f *= i; + return f; +} +int isStrong(int num) { + int s = 0, t = num; + while (t != 0) { s += factorial(t % 10); t /= 10; } + return s == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isStrong() returns 1 if true and 0 if false + switch (isStrong(num)) { + case 1: + printf("%d is a Strong Number\n", num); + break; + case 0: + printf("%d is Not a Strong Number\n", num); + break; + } + + return 0; +} +// Method 9 - Switch Case isStrong() returns 1 for strong and 0 for not strong. Switch works on these values. Case 1 means strong number and case 0 means not strong number. Good practice combining function with switch. + +// Method 10: Print Strong Numbers in a Given Range +#include +int factorial(int n) { + int f = 1; + for (int i = 1; i <= n; i++) f *= i; + return f; +} +int isStrong(int num) { + int s = 0, t = num; + while (t != 0) { s += factorial(t % 10); t /= 10; } + return s == num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Strong numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (isStrong(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 10 - Range We check every number in the given range and print it if it is a strong number. isStrong() is reused cleanly for each number. Known strong numbers are 1 2 145 and 40585 so test with a wide range. + +// Method 11: Using Macro +#include + +int factHelper(int n) { + int f = 1; + for (int i = 1; i <= n; i++) f *= i; + return f; +} +int strongHelper(int n) { + int s = 0, t = n; + while (t != 0) { s += factHelper(t % 10); t /= 10; } + return s == n; +} + +#define IS_STRONG(n) strongHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_STRONG(num)) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 11 - Macro We define IS_STRONG as a macro that calls strongHelper(). Wherever IS_STRONG(n) is written it gets replaced by strongHelper(n). Good to know how macros wrap function calls cleanly in C. + +// Method 12: Without using pow() or Extra Library +#include +int main() { + int num, sum = 0, temp; + + printf("Enter a number: "); + scanf("%d", &num); + + temp = num; + + while (temp != 0) { + int digit = temp % 10; + + // manually calculate factorial without any library + int fact = 1; + int i = 2; + while (i <= digit) { + fact *= i; + i++; + } + + sum += fact; + temp /= 10; + } + + if (sum == num) + printf("%d is a Strong Number\n", num); + else + printf("%d is Not a Strong Number\n", num); + + return 0; +} +// Method 12 - No Library We calculate factorial manually starting from i=2 since multiplying by 1 changes nothing. No math.h or any other library is needed at all. Clean standalone solution using only stdio.h for input and output. diff --git a/Shaivi_Sum_First_N_N.Q3.c b/Shaivi_Sum_First_N_N.Q3.c new file mode 100644 index 0000000..b9e7310 --- /dev/null +++ b/Shaivi_Sum_First_N_N.Q3.c @@ -0,0 +1,135 @@ +// Sum of First N Natural Numbers + +// Method 1: Using a Loop (Brute Force) +#include +int main() { + int n, sum = 0; + + printf("Enter a positive number: "); + scanf("%d", &n); + + for (int i = 1; i <= n; i++) { + sum = sum + i; + } + + printf("Sum of first %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 1 - Simple for Loop We start sum at 0 and add every number from 1 to n one by one. Easy to understand and works for any beginner. Most basic way to do it. + +// Method 2: Using while Loop +#include +int main() { + int n, sum = 0, i = 1; + + printf("Enter a positive number: "); + scanf("%d", &n); + + while (i <= n) { + sum += i; + i++; + } + + printf("Sum of first %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop instead. We manually write i++ to move forward. Good to know both for and while do the same job differently. + +// Method 3: Using Mathematical Formula +#include +int main() { + int n; + + printf("Enter a positive number: "); + scanf("%d", &n); + + // Formula: sum = n * (n + 1) / 2 + int sum = n * (n + 1) / 2; + + printf("Sum of first %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 3 - Formula No loop needed at all. The formula n*(n+1)/2 gives the answer directly in one step. This is the fastest and smartest method. Very useful to remember. + +// Method 4: Using Recursion +#include +int sumRecursive(int n) { + if (n == 0) + return 0; + return n + sumRecursive(n - 1); +} +int main() { + int n; + + printf("Enter a positive number: "); + scanf("%d", &n); + + printf("Sum of first %d natural numbers = %d\n", n, sumRecursive(n)); + + return 0; +} +// Method 4 - Recursion The function calls itself with n-1 each time until n becomes 0. Then it adds all the values as it comes back. Good for understanding how recursion works. + +// Method 5: Using Function (Non-Recursive) +#include +int findSum(int n) { + int sum = 0; + for (int i = 1; i <= n; i++) + sum += i; + return sum; +} +int main() { + int n; + + printf("Enter a positive number: "); + scanf("%d", &n); + + printf("Sum of first %d natural numbers = %d\n", n, findSum(n)); + + return 0; +} +// Method 5 - Function The loop logic is moved into a separate function findSum(). Main just takes input and prints. This keeps the code clean and reusable. Good coding habit. + +// Method 6: Using do-while Loop +#include +int main() { + int n, sum = 0, i = 1; + + printf("Enter a positive number: "); + scanf("%d", &n); + + do { + sum += i; + i++; + } while (i <= n); + + printf("Sum of first %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 6 - do-while Loop Works like while loop but checks condition after running the body once. So it always runs at least one time. Useful to know all 3 loop types in C. + +// Method 7: Using Array +#include +int main() { + int n; + + printf("Enter a positive number: "); + scanf("%d", &n); + + int arr[n]; + for (int i = 0; i < n; i++) + arr[i] = i + 1; + + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; + + printf("Sum of first %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 7 - Array We first store all numbers 1 to n in an array then add them up in a second loop. Not the most efficient but helps practice working with arrays in C. diff --git a/Shaivi_Sum_N_N.Q4.c b/Shaivi_Sum_N_N.Q4.c new file mode 100644 index 0000000..421fe10 --- /dev/null +++ b/Shaivi_Sum_N_N.Q4.c @@ -0,0 +1,135 @@ +// Sum of N Natural Numbers + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int n, sum = 0; + + printf("Enter the value of N: "); + scanf("%d", &n); + + for (int i = 1; i <= n; i++) { + sum = sum + i; + } + + printf("Sum of %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 1 - Simple for Loop We start sum at 0 and keep adding each number from 1 to n. The loop runs n times and adds i each time. Most basic and easy to understand method. + +// Method 2: Using while Loop +#include +int main() { + int n, sum = 0, i = 1; + + printf("Enter the value of N: "); + scanf("%d", &n); + + while (i <= n) { + sum += i; + i++; + } + + printf("Sum of %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 2 - While Loop Same as method 1 but with a while loop. We initialize i before the loop and increment it inside. Good practice to understand how while loop works. + +// Method 3: Using do-while Loop +#include +int main() { + int n, sum = 0, i = 1; + + printf("Enter the value of N: "); + scanf("%d", &n); + + do { + sum += i; + i++; + } while (i <= n); + + printf("Sum of %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 3 - do-while Loop The body runs first then condition is checked. So it always executes at least once. Completes all 3 loop types in C - for, while and do-while. + +// Method 4: Using Mathematical Formula +#include +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + // Formula: sum = n * (n + 1) / 2 + int sum = n * (n + 1) / 2; + + printf("Sum of %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 4 - Formula No loop at all. The formula n*(n+1)/2 gives the answer in one line directly. This is the most efficient method. Very important formula to remember always. + +// Method 5: Using Function +#include +int findSum(int n) { + int sum = 0; + for (int i = 1; i <= n; i++) + sum += i; + return sum; +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + printf("Sum of %d natural numbers = %d\n", n, findSum(n)); + + return 0; +} +// Method 5 - Function The sum logic is written in a separate function findSum() and called from main. This makes code clean and reusable. A good habit for writing organized programs. + +// Method 6: Using Recursion +#include +int sumRecursive(int n) { + if (n == 0) + return 0; + return n + sumRecursive(n - 1); +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + printf("Sum of %d natural numbers = %d\n", n, sumRecursive(n)); + + return 0; +} +// Method 6 - Recursion The function calls itself with n-1 each time. When n reaches 0 it stops and returns 0. Then adds all values on the way back. Good for learning recursion concept. + +// Method 7: Using Array +#include +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + int arr[n]; + for (int i = 0; i < n; i++) + arr[i] = i + 1; + + int sum = 0; + for (int i = 0; i < n; i++) + sum += arr[i]; + + printf("Sum of %d natural numbers = %d\n", n, sum); + + return 0; +} +// Method 7 - Array Numbers 1 to n are stored in an array first then added in a second loop. Not the most efficient way but great for practising arrays and loops together in C. diff --git a/Shaivi_even_odd.Q2.c b/Shaivi_even_odd.Q2.c new file mode 100644 index 0000000..2797b9a --- /dev/null +++ b/Shaivi_even_odd.Q2.c @@ -0,0 +1,133 @@ +//The number is Even or Odd Program in C + +//1. Using Modulus Operator % +#include +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + if (n % 2 == 0) + printf("%d is Even\n", n); + else + printf("%d is Odd\n", n); + return 0; +} + +//2. Using Bitwise AND Operator & +#include +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + if (n & 1) + printf("%d is Odd\n", n); + else + printf("%d is Even\n", n); + return 0; +} + +//3. Using Ternary Operator ? : +#include +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + printf("%d is %s\n", n, (n % 2 == 0) ? "Even" : "Odd"); + return 0; +} + +//4. Using Division (Without Modulus) +#include +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + if ((n / 2) * 2 == n) + printf("%d is Even\n", n); + else + printf("%d is Odd\n", n); + return 0; +} + +//5. Using a Function +#include + +int isEven(int n) { + return (n % 2 == 0); +} + +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + if (isEven(n)) + printf("%d is Even\n", n); + else + printf("%d is Odd\n", n); + return 0; +} + +//6. Using Recursion +#include + +int isEven(int n) { + if (n < 0) n = -n; // handle negatives + if (n == 0) return 1; + if (n == 1) return 0; + return isEven(n - 2); +} + +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + printf("%d is %s\n", n, isEven(n) ? "Even" : "Odd"); + return 0; +} + +//7. Using Bitwise XOR ^ + +#include +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + if ((n ^ 1) == n + 1) + printf("%d is Even\n", n); + else + printf("%d is Odd\n", n); + return 0; +} + +//8. Using Right Shift >> +#include +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + if (((n >> 1) << 1) == n) + printf("%d is Even\n", n); + else + printf("%d is Odd\n", n); + return 0; +} + +//9. Using printf without if +//(n%2==0) evaluates to 0 or 1 +#include +int main() { + int n; + printf("Enter a number: "); + scanf("%d", &n); + char *results[] = {"Odd", "Even"}; + printf("%d is %s\n", n, results[n % 2 == 0]); + return 0; +} + +//Conclusion: + +//Explored multiple ways to check whether a number is even or odd in C language. +//Each method gives the same result but works differently internally. +//The modulus operator is the simplest and most commonly used method. +//The bitwise AND operator is the most efficient at the hardware level since it directly checks the last bit of the number. +//Methods like recursion and XOR are not practical for this problem but help in understanding how logic can be applied in different ways. diff --git a/Shaivi_greatest_three.Q7.c b/Shaivi_greatest_three.Q7.c new file mode 100644 index 0000000..799d288 --- /dev/null +++ b/Shaivi_greatest_three.Q7.c @@ -0,0 +1,182 @@ +// Find the Greatest of the Three Numbers in C + +// Method 1: Using if-else (Brute Force) +#include +int main() { + int a, b, c; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + printf("Enter third number: "); + scanf("%d", &c); + + if (a >= b && a >= c) { + printf("%d is the Greatest\n", a); + } else if (b >= a && b >= c) { + printf("%d is the Greatest\n", b); + } else { + printf("%d is the Greatest\n", c); + } + + return 0; +} +// Method 1 - if-else We check each number against the other two using && operator. If a is greater than both print a. If b is greater than both print b. Otherwise c is the greatest. + +// Method 2: Using Nested if +#include +int main() { + int a, b, c; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + printf("Enter third number: "); + scanf("%d", &c); + + if (a > b) { + if (a > c) + printf("%d is the Greatest\n", a); + else + printf("%d is the Greatest\n", c); + } else { + if (b > c) + printf("%d is the Greatest\n", b); + else + printf("%d is the Greatest\n", c); + } + + return 0; +} +// Method 2 - Nested if We first compare a and b. Then inside each branch we compare the winner with c. This is nesting one if inside another. Good for understanding step by step comparison logic. + +// Method 3: Using Ternary Operator +#include +int main() { + int a, b, c, greatest; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + printf("Enter third number: "); + scanf("%d", &c); + + // first find greater of a and b then compare with c + greatest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); + + printf("%d is the Greatest\n", greatest); + + return 0; +} +// Method 3 - Ternary Operator We nest two ternary operators. First compare a and b then compare the bigger one with c. All done in a single line. Good for short comparisons once basics are clear. + +// Method 4: Using Function +#include +void findGreatest(int a, int b, int c) { + if (a >= b && a >= c) + printf("%d is the Greatest\n", a); + else if (b >= a && b >= c) + printf("%d is the Greatest\n", b); + else + printf("%d is the Greatest\n", c); +} +int main() { + int a, b, c; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + printf("Enter third number: "); + scanf("%d", &c); + + findGreatest(a, b, c); + + return 0; +} +// Method 4 - Function The comparison logic is placed in a separate function findGreatest() that takes all three numbers. Main just handles input and output. Clean reusable and well organized code. + +// Method 5: Using Temp Variable +#include +int main() { + int a, b, c, greatest; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + printf("Enter third number: "); + scanf("%d", &c); + + // first assume a is greatest + greatest = a; + + if (b > greatest) + greatest = b; + if (c > greatest) + greatest = c; + + printf("%d is the Greatest\n", greatest); + + return 0; +} +// Method 5 - Temp Variable We assume a is the greatest first. Then compare b and c one by one with greatest and update if bigger. Simple and clean approach. Very easy to extend for more numbers. + +// Method 6: Using switch Statement +#include +int main() { + int a, b, c; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + printf("Enter third number: "); + scanf("%d", &c); + + // (a >= b && a >= c) gives 1 if true and 0 if false + switch (a >= b && a >= c) { + case 1: + printf("%d is the Greatest\n", a); + break; + case 0: + if (b >= c) + printf("%d is the Greatest\n", b); + else + printf("%d is the Greatest\n", c); + break; + } + + return 0; +} +// Method 6 - Switch Case The condition a >= b && a >= c returns 1 if true and 0 if false. Case 1 means a is greatest. In case 0 we compare b and c to find the greater one between them. + +// Method 7: Using Bitwise Operator +#include +int main() { + int a, b, c; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + printf("Enter third number: "); + scanf("%d", &c); + + // right shift by 31 checks the sign bit + // if sign bit is 1 the number is negative + int greatest = a; + + if ((b - greatest) >> 31 == 0 && b != greatest) + greatest = b; + if ((c - greatest) >> 31 == 0 && c != greatest) + greatest = c; + + printf("%d is the Greatest\n", greatest); + + return 0; +} +// Method 7 - Bitwise We check the sign bit of the difference using >> 31. If the result is 0 the difference is positive meaning the new number is greater. Slightly advanced topic learn after basics are done. diff --git a/Shaivi_greatest_two.Q6.c b/Shaivi_greatest_two.Q6.c new file mode 100644 index 0000000..92ddf82 --- /dev/null +++ b/Shaivi_greatest_two.Q6.c @@ -0,0 +1,168 @@ +// Find the Greatest of the Two Numbers in C + +// Method 1: Using if-else (Brute Force) +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + if (a > b) { + printf("%d is the Greatest\n", a); + } else if (b > a) { + printf("%d is the Greatest\n", b); + } else { + printf("Both numbers are Equal\n"); + } + + return 0; +} +// Method 1 - if-else We compare a and b using simple conditions. If a is greater print a. If b is greater print b. If neither is greater then both are equal. Most basic and clear method. + +// Method 2: Using Nested if +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + if (a >= b) { + if (a == b) + printf("Both numbers are Equal\n"); + else + printf("%d is the Greatest\n", a); + } else { + printf("%d is the Greatest\n", b); + } + + return 0; +} +// Method 2 - Nested if We first check if a is greater or equal to b. Inside that we check if they are equal. This is called nesting one if inside another. Good for understanding nested logic. + +// Method 3: Using Ternary Operator +#include +int main() { + int a, b, greatest; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // condition ? value if true : value if false + greatest = (a > b) ? a : b; + + if (a == b) + printf("Both numbers are Equal\n"); + else + printf("%d is the Greatest\n", greatest); + + return 0; +} +// Method 3 - Ternary Operator Short form of if-else. We write condition then ? then true value then : then false value. Result is stored in greatest. Good for short and simple comparisons. + +// Method 4: Using Function +#include +void findGreatest(int a, int b) { + if (a > b) + printf("%d is the Greatest\n", a); + else if (b > a) + printf("%d is the Greatest\n", b); + else + printf("Both numbers are Equal\n"); +} +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + findGreatest(a, b); + + return 0; +} +// Method 4 - Function The comparison logic is written in a separate function findGreatest() and just called from main. This keeps code clean and reusable. A good habit for organized programs. + +// Method 5: Using Subtraction +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // if a - b is positive then a is greater + // if a - b is negative then b is greater + int diff = a - b; + + if (diff > 0) + printf("%d is the Greatest\n", a); + else if (diff < 0) + printf("%d is the Greatest\n", b); + else + printf("Both numbers are Equal\n"); + + return 0; +} +// Method 5 - Subtraction We subtract b from a. If the result is positive a is greater. If negative b is greater. If zero both are equal. A different way to compare without using > or < directly. + +// Method 6: Using switch Statement +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // (a > b) gives 1 if true and 0 if false + switch (a > b) { + case 1: + printf("%d is the Greatest\n", a); + break; + case 0: + if (a == b) + printf("Both numbers are Equal\n"); + else + printf("%d is the Greatest\n", b); + break; + } + + return 0; +} +// Method 6 - Switch Case A condition like a > b returns 1 if true and 0 if false. Switch works on these values. Case 1 means a is greater and case 0 handles b greater or equal case. + +// Method 7: Using Bitwise Operator +#include +int main() { + int a, b; + + printf("Enter first number: "); + scanf("%d", &a); + printf("Enter second number: "); + scanf("%d", &b); + + // right shift by 31 checks the sign bit of the difference + int diff = a - b; + + if (diff == 0) + printf("Both numbers are Equal\n"); + else if (diff >> 31) + printf("%d is the Greatest\n", b); + else + printf("%d is the Greatest\n", a); + + return 0; +} +// Method 7 - Bitwise We subtract b from a and check the sign bit using >> 31. If sign bit is 1 the difference is negative meaning b is greater. Slightly advanced. Learn it after basics are clear. diff --git a/Shaivi_leap_year.Q8.c b/Shaivi_leap_year.Q8.c new file mode 100644 index 0000000..aa16058 --- /dev/null +++ b/Shaivi_leap_year.Q8.c @@ -0,0 +1,149 @@ +// Check if the Year is a Leap Year or Not in C + +// Method 1: Using if-else (Brute Force) +#include +int main() { + int year; + + printf("Enter a year: "); + scanf("%d", &year); + + if (year % 400 == 0) { + printf("%d is a Leap Year\n", year); + } else if (year % 100 == 0) { + printf("%d is Not a Leap Year\n", year); + } else if (year % 4 == 0) { + printf("%d is a Leap Year\n", year); + } else { + printf("%d is Not a Leap Year\n", year); + } + + return 0; +} +// Method 1 - if-else A year is leap if divisible by 400. If divisible by 100 but not 400 it is not a leap year. If divisible by 4 but not 100 it is a leap year. Otherwise not a leap year. + +// Method 2: Using Nested if +#include +int main() { + int year; + + printf("Enter a year: "); + scanf("%d", &year); + + if (year % 4 == 0) { + if (year % 100 == 0) { + if (year % 400 == 0) + printf("%d is a Leap Year\n", year); + else + printf("%d is Not a Leap Year\n", year); + } else { + printf("%d is a Leap Year\n", year); + } + } else { + printf("%d is Not a Leap Year\n", year); + } + + return 0; +} +// Method 2 - Nested if We go step by step. First check divisible by 4. Inside that check divisible by 100. Inside that check divisible by 400. Each condition narrows down the result further. + +// Method 3: Using Logical Operators +#include +int main() { + int year; + + printf("Enter a year: "); + scanf("%d", &year); + + // leap year condition in one line using && and || + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { + printf("%d is a Leap Year\n", year); + } else { + printf("%d is Not a Leap Year\n", year); + } + + return 0; +} +// Method 3 - Logical Operators We combine all conditions in one line using && and ||. Divisible by 4 but not 100 OR divisible by 400 means leap year. Clean and most commonly used method. + +// Method 4: Using Ternary Operator +#include +int main() { + int year; + + printf("Enter a year: "); + scanf("%d", &year); + + // condition ? "if true" : "if false" + ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) + ? printf("%d is a Leap Year\n", year) + : printf("%d is Not a Leap Year\n", year); + + return 0; +} +// Method 4 - Ternary Operator Short form of if-else. We put the full leap year condition before ? then true part then : then false part. All done in one statement. Good for short and clean checks. + +// Method 5: Using Function +#include +int isLeapYear(int year) { + if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) + return 1; + return 0; +} +int main() { + int year; + + printf("Enter a year: "); + scanf("%d", &year); + + if (isLeapYear(year)) + printf("%d is a Leap Year\n", year); + else + printf("%d is Not a Leap Year\n", year); + + return 0; +} +// Method 5 - Function The leap year logic is placed in a separate function isLeapYear() that returns 1 for leap and 0 for not leap. Main just checks the return value. Clean and reusable code. + +// Method 6: Using switch Statement +#include +int main() { + int year; + + printf("Enter a year: "); + scanf("%d", &year); + + // condition gives 1 if true and 0 if false + switch ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { + case 1: + printf("%d is a Leap Year\n", year); + break; + case 0: + printf("%d is Not a Leap Year\n", year); + break; + } + + return 0; +} +// Method 6 - Switch Case The leap year condition returns 1 if true and 0 if false. Switch works on these values. Case 1 means leap year and case 0 means not a leap year. Simple and clean. + +// Method 7: Using Macro +#include + +// defining leap year condition as a macro +#define IS_LEAP(y) ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) + +int main() { + int year; + + printf("Enter a year: "); + scanf("%d", &year); + + if (IS_LEAP(year)) + printf("%d is a Leap Year\n", year); + else + printf("%d is Not a Leap Year\n", year); + + return 0; +} +// Method 7 - Macro We define the leap year condition as a macro IS_LEAP using #define. Wherever we write IS_LEAP(y) it gets replaced by the full condition. Slightly advanced but good to know. diff --git a/Shaivi_nth_fibonacci.Q17.c b/Shaivi_nth_fibonacci.Q17.c new file mode 100644 index 0000000..b57eb7a --- /dev/null +++ b/Shaivi_nth_fibonacci.Q17.c @@ -0,0 +1,300 @@ +// Finding Nth Term of a Fibonacci Series in C + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + int a = 0, b = 1; + + if (n == 1) { + printf("Nth term of Fibonacci = 0\n"); + } else if (n == 2) { + printf("Nth term of Fibonacci = 1\n"); + } else { + for (int i = 3; i <= n; i++) { + int next = a + b; + a = b; + b = next; + } + printf("Nth term of Fibonacci = %d\n", b); + } + + return 0; +} +// Method 1 - For Loop We handle first two terms as special cases. For n greater than 2 we run the loop from 3 to n shifting a and b forward each time. When loop ends b holds the nth fibonacci term. + +// Method 2: Using while Loop +#include +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + int a = 0, b = 1, i = 3; + + if (n == 1) { + printf("Nth term of Fibonacci = 0\n"); + } else if (n == 2) { + printf("Nth term of Fibonacci = 1\n"); + } else { + while (i <= n) { + int next = a + b; + a = b; + b = next; + i++; + } + printf("Nth term of Fibonacci = %d\n", b); + } + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop. We initialize i as 3 before the loop and increment inside. Good practice to write the same solution using different loop types. + +// Method 3: Using do-while Loop +#include +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + int a = 0, b = 1, i = 3; + + if (n == 1) { + printf("Nth term of Fibonacci = 0\n"); + } else if (n == 2) { + printf("Nth term of Fibonacci = 1\n"); + } else { + do { + int next = a + b; + a = b; + b = next; + i++; + } while (i <= n); + printf("Nth term of Fibonacci = %d\n", b); + } + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Special cases for n=1 and n=2 are still handled separately. + +// Method 4: Using Function +#include +int getNthFibonacci(int n) { + if (n == 1) return 0; + if (n == 2) return 1; + int a = 0, b = 1; + for (int i = 3; i <= n; i++) { + int next = a + b; + a = b; + b = next; + } + return b; +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + printf("Nth term of Fibonacci = %d\n", getNthFibonacci(n)); + + return 0; +} +// Method 4 - Function The logic is placed in a separate function getNthFibonacci() that returns the result directly. Main just takes input and prints. Clean reusable and well organized code structure. + +// Method 5: Using Recursion +#include +int fibonacci(int n) { + if (n == 1) return 0; + if (n == 2) return 1; + return fibonacci(n - 1) + fibonacci(n - 2); +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + printf("Nth term of Fibonacci = %d\n", fibonacci(n)); + + return 0; +} +// Method 5 - Recursion fibonacci(n) calls itself with n-1 and n-2 and adds results. Base cases are n=1 returns 0 and n=2 returns 1. Easy to understand but slow for large n due to repeated calculations. + +// Method 6: Using Memoization (Top Down DP) +#include +#define MAX 1000 + +int memo[MAX]; + +int fibonacci(int n) { + if (n == 1) return 0; + if (n == 2) return 1; + if (memo[n] != -1) return memo[n]; + memo[n] = fibonacci(n - 1) + fibonacci(n - 2); + return memo[n]; +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + for (int i = 0; i < MAX; i++) + memo[i] = -1; + + printf("Nth term of Fibonacci = %d\n", fibonacci(n)); + + return 0; +} +// Method 6 - Memoization Same as recursion but already computed values are stored in memo array. If value is already calculated we return it directly instead of recalculating. Much faster than plain recursion. + +// Method 7: Using Array (Bottom Up DP) +#include +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + int fib[n + 1]; + fib[1] = 0; + fib[2] = 1; + + for (int i = 3; i <= n; i++) + fib[i] = fib[i - 1] + fib[i - 2]; + + printf("Nth term of Fibonacci = %d\n", fib[n]); + + return 0; +} +// Method 7 - Bottom Up DP We fill the array from index 1 to n. Each value is sum of two before it. No recursion needed at all. We directly access fib[n] at the end. Efficient and easy to understand approach. + +// Method 8: Using Tail Recursion +#include +int fibTail(int n, int a, int b) { + if (n == 1) return a; + if (n == 2) return b; + return fibTail(n - 1, b, a + b); +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + printf("Nth term of Fibonacci = %d\n", fibTail(n, 0, 1)); + + return 0; +} +// Method 8 - Tail Recursion We pass current and next fibonacci values as arguments. Each call reduces n by 1 and shifts values forward. When n reaches 1 we return a directly. More efficient than normal recursion. + +// Method 9: Using Ternary Operator +#include +int fibonacci(int n) { + return (n == 1) ? 0 : (n == 2) ? 1 : fibonacci(n - 1) + fibonacci(n - 2); +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + printf("Nth term of Fibonacci = %d\n", fibonacci(n)); + + return 0; +} +// Method 9 - Ternary Operator The entire recursive function is written in a single line using nested ternary operators. If n=1 return 0 if n=2 return 1 else recurse. Compact and clean version of method 5. + +// Method 10: Using Golden Ratio Formula +#include +#include +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + // phi = (1 + sqrt(5)) / 2 + double phi = (1 + sqrt(5)) / 2; + + // nth fibonacci = round(phi^(n-1) / sqrt(5)) + int result = (int)round(pow(phi, n - 1) / sqrt(5)); + + printf("Nth term of Fibonacci = %d\n", result); + + return 0; +} +// Method 10 - Golden Ratio The nth fibonacci term is calculated directly using the golden ratio formula without any loop or recursion. Works well for small values but loses precision for large n due to floating point limits. + +// Method 11: Using Matrix Exponentiation +#include +void multiply(int F[2][2], int M[2][2]) { + int a = F[0][0]*M[0][0] + F[0][1]*M[1][0]; + int b = F[0][0]*M[0][1] + F[0][1]*M[1][1]; + int c = F[1][0]*M[0][0] + F[1][1]*M[1][0]; + int d = F[1][0]*M[0][1] + F[1][1]*M[1][1]; + F[0][0]=a; F[0][1]=b; + F[1][0]=c; F[1][1]=d; +} +int fibonacci(int n) { + if (n == 1) return 0; + int F[2][2] = {{1,1},{1,0}}; + int M[2][2] = {{1,1},{1,0}}; + for (int i = 2; i < n; i++) + multiply(F, M); + return F[0][0]; +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + printf("Nth term of Fibonacci = %d\n", fibonacci(n)); + + return 0; +} +// Method 11 - Matrix Exponentiation Fibonacci numbers can be derived using matrix multiplication of a 2x2 matrix. Advanced method used in competitive programming for very large n values. Good to know it exists and learn later. + +// Method 12: Using switch Statement +#include +int getNthFib(int n) { + if (n == 1) return 0; + if (n == 2) return 1; + int a = 0, b = 1; + for (int i = 3; i <= n; i++) { + int next = a + b; + a = b; + b = next; + } + return b; +} +int main() { + int n; + + printf("Enter the value of N: "); + scanf("%d", &n); + + // use switch for special cases + switch (n) { + case 1: + printf("Nth term of Fibonacci = 0\n"); + break; + case 2: + printf("Nth term of Fibonacci = 1\n"); + break; + default: + printf("Nth term of Fibonacci = %d\n", getNthFib(n)); + break; + } + + return 0; +} +// Method 12 - Switch Statement Switch handles the first two special cases directly. The default case calls getNthFib() for all other values of n. Good practice combining switch with a function for cleaner output handling. diff --git a/Shaivi_perfect_Square.Q23.c b/Shaivi_perfect_Square.Q23.c new file mode 100644 index 0000000..66ff51f --- /dev/null +++ b/Shaivi_perfect_Square.Q23.c @@ -0,0 +1,391 @@ +// Program to Check for Perfect Square in C + +// Method 1: Using sqrt() Function (Brute Force) +#include +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num < 0) { + printf("%d is Not a Perfect Square\n", num); + } else { + int root = (int)sqrt(num); + if (root * root == num) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + } + + return 0; +} +// Method 1 - sqrt() We take the square root of num and cast it to int to remove decimal. Then multiply root by itself and compare with original num. If equal it is a perfect square. Negative numbers are handled separately. + +// Method 2: Using for Loop (Brute Force) +#include +int main() { + int num, isPerfectSq = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num < 0) { + printf("%d is Not a Perfect Square\n", num); + } else { + for (int i = 0; i * i <= num; i++) { + if (i * i == num) { + isPerfectSq = 1; + break; + } + } + + if (isPerfectSq) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + } + + return 0; +} +// Method 2 - For Loop We check every number i starting from 0. If i*i equals num we found the square root and it is a perfect square. We stop as soon as i*i exceeds num. No math library needed at all. + +// Method 3: Using while Loop +#include +int main() { + int num, i = 0, isPerfectSq = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num < 0) { + printf("%d is Not a Perfect Square\n", num); + } else { + while (i * i <= num) { + if (i * i == num) { + isPerfectSq = 1; + break; + } + i++; + } + + if (isPerfectSq) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + } + + return 0; +} +// Method 3 - While Loop Same logic as method 2 but using a while loop. We initialize i before the loop and increment it inside. Good practice to write the same perfect square logic using different loop types. + +// Method 4: Using do-while Loop +#include +int main() { + int num, i = 0, isPerfectSq = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num < 0) { + printf("%d is Not a Perfect Square\n", num); + } else if (num == 0) { + printf("0 is a Perfect Square\n"); + } else { + do { + if (i * i == num) { + isPerfectSq = 1; + break; + } + i++; + } while (i * i <= num); + + if (isPerfectSq) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + } + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. We handle 0 separately since do-while always runs once. Completes all 3 loop types for this problem. Good to practice do-while with math checks. + +// Method 5: Using Function +#include +#include +int isPerfectSquare(int num) { + if (num < 0) return 0; + int root = (int)sqrt(num); + return root * root == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPerfectSquare(num)) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + + return 0; +} +// Method 5 - Function The perfect square logic is placed in a separate function isPerfectSquare() that returns 1 if true and 0 if false. Main just takes input and prints. Clean reusable and well organized code structure. + +// Method 6: Using Recursion +#include +int checkSquare(int num, int i) { + if (i * i > num) return 0; + if (i * i == num) return 1; + return checkSquare(num, i + 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num < 0) + printf("%d is Not a Perfect Square\n", num); + else if (checkSquare(num, 0)) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + + return 0; +} +// Method 6 - Recursion The function checks if i*i equals num. If i*i exceeds num it returns 0. If equal it returns 1. Otherwise it calls itself with i+1. Good practice for understanding how recursion replaces a loop. + +// Method 7: Using Binary Search +#include +int isPerfectSquare(int num) { + if (num < 0) return 0; + if (num == 0 || num == 1) return 1; + + int low = 1, high = num / 2, mid; + + while (low <= high) { + mid = low + (high - low) / 2; + long long sq = (long long)mid * mid; + + if (sq == num) return 1; + else if (sq < num) low = mid + 1; + else high = mid - 1; + } + return 0; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPerfectSquare(num)) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + + return 0; +} +// Method 7 - Binary Search Instead of checking every number we binary search between 1 and num/2. Each step we check mid*mid against num and halve the search space. Much faster than brute force for large numbers. + +// Method 8: Using Bitwise Operator +#include +int isPerfectSquare(int num) { + if (num < 0) return 0; + if (num == 0) return 1; + + int x = num; + int root = 0; + + // find square root using bitwise method + for (int bit = 1 << 15; bit > 0; bit >>= 1) { + root |= bit; + if (root * root > x) + root ^= bit; + } + return root * root == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPerfectSquare(num)) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + + return 0; +} +// Method 8 - Bitwise We build the square root bit by bit from the most significant bit down. We set each bit and check if root*root exceeds num. If it does we unset it. Advanced low level technique good to know exists. + +// Method 9: Using Newton Raphson Method +#include +int isPerfectSquare(int num) { + if (num < 0) return 0; + if (num == 0) return 1; + + double x = num; + + // iterate until result converges + while (1) { + double root = (x + num / x) / 2.0; + if (root >= x) break; + x = root; + } + + int r = (int)x; + return r * r == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPerfectSquare(num)) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + + return 0; +} +// Method 9 - Newton Raphson We use the Newton Raphson iterative formula to converge on the square root. Each iteration improves the estimate. When it stops improving we check if the integer root squared equals num. + +// Method 10: Using Ternary Operator +#include +#include +int isPerfectSquare(int num) { + if (num < 0) return 0; + int r = (int)sqrt(num); + return r * r == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? true : false + isPerfectSquare(num) + ? printf("%d is a Perfect Square\n", num) + : printf("%d is Not a Perfect Square\n", num); + + return 0; +} +// Method 10 - Ternary Operator We call isPerfectSquare() inside a ternary condition directly. If it returns 1 print yes else print no. All output handled in one clean single statement. Compact version combining function and ternary. + +// Method 11: Using switch Statement +#include +#include +int isPerfectSquare(int num) { + if (num < 0) return 0; + int r = (int)sqrt(num); + return r * r == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isPerfectSquare() returns 1 if true and 0 if false + switch (isPerfectSquare(num)) { + case 1: + printf("%d is a Perfect Square\n", num); + break; + case 0: + printf("%d is Not a Perfect Square\n", num); + break; + } + + return 0; +} +// Method 11 - Switch Case isPerfectSquare() returns 1 for perfect square and 0 for not. Switch works on these values. Case 1 means perfect square and case 0 means not. Good practice combining function with switch. + +// Method 12: Print Perfect Squares in a Given Range +#include +#include +int isPerfectSquare(int num) { + if (num < 0) return 0; + int r = (int)sqrt(num); + return r * r == num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Perfect squares between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (isPerfectSquare(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 12 - Range We check every number in the given range and print it if it is a perfect square. isPerfectSquare() is reused cleanly for each number. Good practice combining range loops with a reusable function. + +// Method 13: Using Macro +#include +#include + +int sqHelper(int n) { + if (n < 0) return 0; + int r = (int)sqrt(n); + return r * r == n; +} + +#define IS_PERFECT_SQUARE(n) sqHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_PERFECT_SQUARE(num)) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + + return 0; +} +// Method 13 - Macro We define IS_PERFECT_SQUARE as a macro that calls sqHelper(). Wherever IS_PERFECT_SQUARE(n) is written it gets replaced by sqHelper(n). Good to know how macros wrap function calls cleanly in C. + +// Method 14: Using Odd Number Subtraction Property +#include +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num < 0) { + printf("%d is Not a Perfect Square\n", num); + } else { + int temp = num, odd = 1; + + // every perfect square is sum of consecutive odd numbers + // 1=1 4=1+3 9=1+3+5 16=1+3+5+7 + while (temp > 0) { + temp -= odd; + odd += 2; + } + + if (temp == 0) + printf("%d is a Perfect Square\n", num); + else + printf("%d is Not a Perfect Square\n", num); + } + + return 0; +} +// Method 14 - Odd Subtraction Every perfect square is the sum of consecutive odd numbers starting from 1. So we subtract 1 3 5 7 and so on from num. If we reach exactly 0 it is a perfect square. Unique math property approach. diff --git a/Shaivi_perfect_no.Q22.c b/Shaivi_perfect_no.Q22.c new file mode 100644 index 0000000..147f4b4 --- /dev/null +++ b/Shaivi_perfect_no.Q22.c @@ -0,0 +1,334 @@ +// C Program to Check Perfect Number or Not + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + for (int i = 1; i < num; i++) + if (num % i == 0) + sum += i; + + if (sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 1 - For Loop We add all divisors of num excluding num itself. If the sum equals num it is a perfect number. Example 6 = 1+2+3 = 6 so 6 is perfect. Most basic and easy to understand method. + +// Method 2: Using while Loop +#include +int main() { + int num, sum = 0, i = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + while (i < num) { + if (num % i == 0) + sum += i; + i++; + } + + if (sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop. We initialize i before the loop and increment it inside. Good practice to write the same perfect number logic using different loop types. + +// Method 3: Using do-while Loop +#include +int main() { + int num, sum = 0, i = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + do { + if (num % i == 0) + sum += i; + i++; + } while (i < num); + + if (sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to practice do-while with divisor sum logic. + +// Method 4: Using Square Root Optimization +#include +#include +int main() { + int num, sum = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + // factors always come in pairs so check only up to sqrt + for (int i = 2; i <= sqrt(num); i++) { + if (num % i == 0) { + sum += i; + if (i != num / i) + sum += num / i; + } + } + + if (num > 1 && sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 4 - Square Root Divisors come in pairs. If i divides num then num/i is also a divisor. We check only up to sqrt(num) and add both factors at once. We start sum at 1 since 1 is always a divisor. Much faster method. + +// Method 5: Using Function +#include +int isPerfect(int num) { + int sum = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) + sum += i; + return sum == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPerfect(num)) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 5 - Function The perfect number logic is placed in a separate function isPerfect() that returns 1 if true and 0 if false. Main just takes input and prints. Clean reusable and well organized code structure. + +// Method 6: Using Recursion +#include +int divisorSum(int num, int i) { + if (i == num) return 0; + if (num % i == 0) return i + divisorSum(num, i + 1); + return divisorSum(num, i + 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + int sum = divisorSum(num, 1); + + if (sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 6 - Recursion divisorSum() checks if i divides num and adds it then calls itself with i+1. When i equals num it stops and returns 0. Good practice for understanding how recursion replaces a simple divisor loop. + +// Method 7: Using Array to Store Divisors +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + int divisors[num], count = 0; + + for (int i = 1; i < num; i++) { + if (num % i == 0) { + divisors[count++] = i; + sum += i; + } + } + + printf("Divisors of %d are: ", num); + for (int i = 0; i < count; i++) + printf("%d ", divisors[i]); + printf("\nSum of divisors = %d\n", sum); + + if (sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 7 - Array We store all divisors in an array and also calculate their sum. We print the divisors list and sum before the final result. More informative output showing exactly which divisors were found and their total. + +// Method 8: Using Ternary Operator +#include +int isPerfect(int num) { + int s = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) s += i; + return s == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? true : false + isPerfect(num) + ? printf("%d is a Perfect Number\n", num) + : printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 8 - Ternary Operator We call isPerfect() inside a ternary condition directly. If it returns 1 print yes else print no. All output handled in one clean single statement. Compact version combining function and ternary. + +// Method 9: Using switch Statement +#include +int isPerfect(int num) { + int s = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) s += i; + return s == num; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // isPerfect() returns 1 if true and 0 if false + switch (isPerfect(num)) { + case 1: + printf("%d is a Perfect Number\n", num); + break; + case 0: + printf("%d is Not a Perfect Number\n", num); + break; + } + + return 0; +} +// Method 9 - Switch Case isPerfect() returns 1 for perfect and 0 for not perfect. Switch works on these values. Case 1 means perfect number and case 0 means not perfect number. Good practice combining function with switch. + +// Method 10: Print Perfect Numbers in a Given Range +#include +int isPerfect(int num) { + int s = 0; + for (int i = 1; i < num; i++) + if (num % i == 0) s += i; + return s == num; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Perfect numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (isPerfect(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 10 - Range We check every number in the given range and print it if it is a perfect number. isPerfect() is reused cleanly for each number. Known perfect numbers are 6 28 496 and 8128 so test with a wide range. + +// Method 11: Using Euclid Euler Formula +#include +#include +int isPrime(int n) { + if (n <= 1) return 0; + for (int i = 2; i * i <= n; i++) + if (n % i == 0) return 0; + return 1; +} +int main() { + int limit; + + printf("Enter limit to find even perfect numbers: "); + scanf("%d", &limit); + + // Euclid Euler formula: 2^(p-1) * (2^p - 1) is perfect if (2^p - 1) is prime + printf("Even perfect numbers up to %d: ", limit); + for (int p = 2; p <= 30; p++) { + long long mersenne = (1LL << p) - 1; + if (isPrime(mersenne)) { + long long perfect = (1LL << (p - 1)) * mersenne; + if (perfect <= limit) + printf("%lld ", perfect); + } + } + printf("\n"); + + return 0; +} +// Method 11 - Euclid Euler Formula Every even perfect number has the form 2^(p-1) * (2^p - 1) where (2^p - 1) is a Mersenne prime. This is a mathematical formula to generate perfect numbers directly. Advanced but good to know. + +// Method 12: Using Macro +#include + +int perfectHelper(int n) { + int s = 0; + for (int i = 1; i < n; i++) + if (n % i == 0) s += i; + return s == n; +} + +#define IS_PERFECT(n) perfectHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (IS_PERFECT(num)) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 12 - Macro We define IS_PERFECT as a macro that calls perfectHelper(). Wherever IS_PERFECT(n) is written it gets replaced by perfectHelper(n). Good to know how macros wrap function calls cleanly in C. + +// Method 13: Without using Division Operator +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + // use multiplication instead of division to check divisibility + for (int i = 1; i < num; i++) + for (int j = 1; j <= num; j++) + if (i * j == num) { + sum += i; + break; + } + + if (sum == num) + printf("%d is a Perfect Number\n", num); + else + printf("%d is Not a Perfect Number\n", num); + + return 0; +} +// Method 13 - Without Division Instead of using % operator we use multiplication to check if i is a divisor. We look for j such that i*j equals num. Not efficient but a good exercise to think about divisibility differently. diff --git a/Shaivi_positive_negative.Q1.c b/Shaivi_positive_negative.Q1.c new file mode 100644 index 0000000..697979f --- /dev/null +++ b/Shaivi_positive_negative.Q1.c @@ -0,0 +1,162 @@ +// positive or negative number + +//Method 1: Using Brute Force +#include + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num > 0) { + printf("%d is Positive\n", num); + } + if (num < 0) { + printf("%d is Negative\n", num); + } + if (num == 0) { + printf("The number is Zero\n"); + } + + return 0; +} +//Method 1 - Simple if We write 3 separate if statements for positive, negative and zero. Each condition is checked one by one.Easy to understand but not the most efficient. + + +//Method 2: Using Nested if-else Statements +#include + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num > 0) { + printf("%d is Positive\n", num); + } else if (num < 0) { + printf("%d is Negative\n", num); + } else { + printf("The number is Zero\n"); + } + + return 0; +} +//Method 2 - if else if Same as method 1 but once a condition is true the rest are skipped. This is better and cleaner than writing 3 separate if statements. + + +//Method 3: Using the ternary operator +#include + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? "if true" : "if false" + (num >= 0) ? printf("%d is Positive or Zero\n", num) + : printf("%d is Negative\n", num); + + return 0; +} +//Method 3 - Ternary Operator It is a short form of if else. We write condition then ? then true part then : then false part. Good for short and simple checks. + + +//Method 4: Using switch Statement +#include + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // (num > 0) gives 1 if true, 0 if false + // (num < 0) gives 1 if true, 0 if false + switch (num > 0) { + case 1: + printf("%d is Positive\n", num); + break; + case 0: + if (num < 0) + printf("%d is Negative\n", num); + else + printf("The number is Zero\n"); + break; + } + + return 0; +} +//Method 4 - Switch Case A condition like num > 0 returns 1 if true and 0 if false. Switch works on these values. Case 1 means positive and case 0 means negative or zero. + + +//Method 5: Using Function +#include + +void checkNumber(int num) { + if (num > 0) + printf("%d is Positive\n", num); + else if (num < 0) + printf("%d is Negative\n", num); + else + printf("The number is Zero\n"); +} + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + checkNumber(num); + + return 0; +} +//Method 5 - Function We write the checking logic in a separate function and just call it in main. This is a good habit for writing clean and reusable code. + + +//Method 6: Using Bitwise Operator +#include + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // right shift by 31 gives 0 for positive, -1 for negative + if (num == 0) + printf("The number is Zero\n"); + else if (num >> 31) + printf("%d is Negative\n", num); + else + printf("%d is Positive\n", num); + + return 0; +} +//Method 6 - abs() abs() removes the minus sign from a number. So if abs(num) == num it means the number has no minus sign and is positive. We need to include stdlib.h to use it. + + +//Method 7: Using abs() Function +#include +#include + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // abs() gives absolute value (removes minus sign) + if (num == 0) + printf("The number is Zero\n"); + else if (abs(num) == num) + printf("%d is Positive\n", num); + else + printf("%d is Negative\n", num); + + return 0; +} +//Method 7 - Bitwise This is slightly advanced. num >> 31 checks the sign bit of the number. Just know it exists for now and learn it later. diff --git a/Shaivi_prime_num.Q9.c b/Shaivi_prime_num.Q9.c new file mode 100644 index 0000000..899df86 --- /dev/null +++ b/Shaivi_prime_num.Q9.c @@ -0,0 +1,190 @@ +// C Program to Check Whether a Number is Prime Number or Not + +// Method 1: Using if-else (Brute Force) +#include +int main() { + int num, isPrime = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num <= 1) { + isPrime = 0; + } else { + for (int i = 2; i < num; i++) { + if (num % i == 0) { + isPrime = 0; + break; + } + } + } + + if (isPrime) + printf("%d is a Prime Number\n", num); + else + printf("%d is Not a Prime Number\n", num); + + return 0; +} +// Method 1 - Brute Force We check if num is divisible by any number from 2 to num-1. If any divisor is found we set isPrime to 0 and break. Numbers less than or equal to 1 are never prime. + +// Method 2: Using Square Root Optimization +#include +#include +int main() { + int num, isPrime = 1; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num <= 1) { + isPrime = 0; + } else { + for (int i = 2; i <= sqrt(num); i++) { + if (num % i == 0) { + isPrime = 0; + break; + } + } + } + + if (isPrime) + printf("%d is a Prime Number\n", num); + else + printf("%d is Not a Prime Number\n", num); + + return 0; +} +// Method 2 - Square Root Instead of checking up to num-1 we only check up to sqrt(num). If a number has a factor larger than its square root the other factor will always be smaller. Much faster method. + +// Method 3: Using while Loop +#include +int main() { + int num, isPrime = 1, i = 2; + + printf("Enter a number: "); + scanf("%d", &num); + + if (num <= 1) { + isPrime = 0; + } else { + while (i < num) { + if (num % i == 0) { + isPrime = 0; + break; + } + i++; + } + } + + if (isPrime) + printf("%d is a Prime Number\n", num); + else + printf("%d is Not a Prime Number\n", num); + + return 0; +} +// Method 3 - While Loop Same logic as method 1 but using a while loop instead of for loop. We initialize i before the loop and increment it inside. Good practice to use while loop for such checks. + +// Method 4: Using Function +#include +int isPrime(int num) { + if (num <= 1) + return 0; + for (int i = 2; i * i <= num; i++) { + if (num % i == 0) + return 0; + } + return 1; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (isPrime(num)) + printf("%d is a Prime Number\n", num); + else + printf("%d is Not a Prime Number\n", num); + + return 0; +} +// Method 4 - Function The prime checking logic is placed in a separate function isPrime() that returns 1 for prime and 0 for not prime. We use i*i <= num instead of sqrt to avoid math.h header. + +// Method 5: Using Recursion +#include +int checkPrime(int num, int i) { + if (num <= 1) + return 0; + if (i * i > num) + return 1; + if (num % i == 0) + return 0; + return checkPrime(num, i + 1); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + if (checkPrime(num, 2)) + printf("%d is a Prime Number\n", num); + else + printf("%d is Not a Prime Number\n", num); + + return 0; +} +// Method 5 - Recursion The function calls itself with i+1 each time. If i*i goes beyond num it means no divisor was found and number is prime. If num%i is 0 a divisor is found so not prime. + +// Method 6: Using Ternary Operator +#include +int checkPrime(int num) { + if (num <= 1) return 0; + for (int i = 2; i * i <= num; i++) + if (num % i == 0) return 0; + return 1; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // condition ? "if true" : "if false" + checkPrime(num) + ? printf("%d is a Prime Number\n", num) + : printf("%d is Not a Prime Number\n", num); + + return 0; +} +// Method 6 - Ternary Operator We use the checkPrime() function with a ternary operator to print the result in one statement. Short and clean way to display output based on a function return value. + +// Method 7: Using switch Statement +#include +int checkPrime(int num) { + if (num <= 1) return 0; + for (int i = 2; i * i <= num; i++) + if (num % i == 0) return 0; + return 1; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + // checkPrime() returns 1 if prime and 0 if not prime + switch (checkPrime(num)) { + case 1: + printf("%d is a Prime Number\n", num); + break; + case 0: + printf("%d is Not a Prime Number\n", num); + break; + } + + return 0; +} +// Method 7 - Switch Case checkPrime() returns 1 for prime and 0 for not prime. Switch works on these values. Case 1 means prime and case 0 means not prime. Good practice combining function with switch. diff --git a/Shaivi_prime_range.Q10.c b/Shaivi_prime_range.Q10.c new file mode 100644 index 0000000..5112f83 --- /dev/null +++ b/Shaivi_prime_range.Q10.c @@ -0,0 +1,225 @@ +// C Program to Print Prime Numbers in a Given Range + +// Method 1: Using Nested for Loop (Brute Force) +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Prime numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + if (i <= 1) continue; + int isPrime = 1; + for (int j = 2; j < i; j++) { + if (i % j == 0) { + isPrime = 0; + break; + } + } + if (isPrime) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 1 - Nested for Loop For every number in the range we check if it is divisible by any number from 2 to i-1. If no divisor found it is prime. Numbers less than or equal to 1 are skipped. + +// Method 2: Using Square Root Optimization +#include +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Prime numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + if (i <= 1) continue; + int isPrime = 1; + for (int j = 2; j <= sqrt(i); j++) { + if (i % j == 0) { + isPrime = 0; + break; + } + } + if (isPrime) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 2 - Square Root Instead of checking up to i-1 we only check up to sqrt(i). If a number has a factor bigger than its square root the other factor is always smaller. Much faster than method 1. + +// Method 3: Using i*i Instead of sqrt() +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Prime numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) { + if (i <= 1) continue; + int isPrime = 1; + for (int j = 2; j * j <= i; j++) { + if (i % j == 0) { + isPrime = 0; + break; + } + } + if (isPrime) + printf("%d ", i); + } + printf("\n"); + + return 0; +} +// Method 3 - i*i Optimization Same as method 2 but we use j*j <= i instead of sqrt(). This avoids including math.h header and is slightly cleaner. Most recommended way to write prime check in C. + +// Method 4: Using while Loop +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Prime numbers between %d and %d are: ", start, end); + int i = start; + while (i <= end) { + if (i > 1) { + int isPrime = 1, j = 2; + while (j * j <= i) { + if (i % j == 0) { + isPrime = 0; + break; + } + j++; + } + if (isPrime) + printf("%d ", i); + } + i++; + } + printf("\n"); + + return 0; +} +// Method 4 - While Loop Same logic as method 3 but both outer and inner loops are written as while loops. We manually initialize and increment the counters. Good practice to use while loop for such problems. + +// Method 5: Using a Function +#include +int isPrime(int num) { + if (num <= 1) return 0; + for (int i = 2; i * i <= num; i++) + if (num % i == 0) return 0; + return 1; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Prime numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (isPrime(i)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 5 - Function The prime checking logic is moved into a separate function isPrime(). Main loop just calls it for each number in range. Code is clean reusable and easy to read and maintain. + +// Method 6: Using Recursion +#include +int checkPrime(int num, int i) { + if (num <= 1) return 0; + if (i * i > num) return 1; + if (num % i == 0) return 0; + return checkPrime(num, i + 1); +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Prime numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (checkPrime(i, 2)) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 6 - Recursion checkPrime() calls itself with i+1 each time. If i*i goes beyond num no divisor was found so it is prime. If num%i is 0 a divisor is found so not prime. Good recursion practice. + +// Method 7: Using Sieve of Eratosthenes +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int sieve[end + 1]; + for (int i = 0; i <= end; i++) + sieve[i] = 1; + + sieve[0] = sieve[1] = 0; + + for (int i = 2; i * i <= end; i++) { + if (sieve[i]) { + for (int j = i * i; j <= end; j += i) + sieve[j] = 0; + } + } + + printf("Prime numbers between %d and %d are: ", start, end); + for (int i = start; i <= end; i++) + if (sieve[i]) + printf("%d ", i); + printf("\n"); + + return 0; +} +// Method 7 - Sieve of Eratosthenes We create an array and mark all multiples of each prime as 0. What remains marked as 1 are primes. This is the fastest known method for printing all primes in a range. + +// Method 8: Using 6k+1 Optimization +#include +int isPrime6k(int num) { + if (num <= 1) return 0; + if (num <= 3) return 1; + if (num % 2 == 0 || num % 3 == 0) return 0; + for (int i = 5; i * i <= num; i += 6) + if (num % i == 0 || num % (i + 2) == 0) return 0; + return 1; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); diff --git a/Shaivi_reverse_num.Q12.c b/Shaivi_reverse_num.Q12.c new file mode 100644 index 0000000..cf5cbe0 --- /dev/null +++ b/Shaivi_reverse_num.Q12.c @@ -0,0 +1,239 @@ +// C Program to Reverse a Given Number + +// Method 1: Using while Loop (Brute Force) +#include +int main() { + int num, reversed = 0, remainder; + + printf("Enter a number: "); + scanf("%d", &num); + + while (num != 0) { + remainder = num % 10; + reversed = reversed * 10 + remainder; + num = num / 10; + } + + printf("Reversed number = %d\n", reversed); + + return 0; +} +// Method 1 - While Loop We extract the last digit using %10 and build the reversed number by multiplying reversed by 10 and adding the digit. Then remove last digit using /10. Repeat until num is 0. + +// Method 2: Using for Loop +#include +int main() { + int num, reversed = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + for (; num != 0; num /= 10) + reversed = reversed * 10 + (num % 10); + + printf("Reversed number = %d\n", reversed); + + return 0; +} +// Method 2 - For Loop Same logic as method 1 but written as a for loop. Initialization is empty since reversed is already set. num /= 10 removes last digit each time. Compact and clean version. + +// Method 3: Using do-while Loop +#include +int main() { + int num, reversed = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + do { + reversed = reversed * 10 + (num % 10); + num /= 10; + } while (num != 0); + + printf("Reversed number = %d\n", reversed); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works same as while loop here. Completes all 3 loop types for this problem. Good to know for single digit numbers it still works fine. + +// Method 4: Using Function +#include +int reverseNumber(int num) { + int reversed = 0; + while (num != 0) { + reversed = reversed * 10 + (num % 10); + num /= 10; + } + return reversed; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Reversed number = %d\n", reverseNumber(num)); + + return 0; +} +// Method 4 - Function The reverse logic is placed in a separate function reverseNumber() that returns the result. Main just takes input and prints. Clean reusable and well organized code structure. + +// Method 5: Using Recursion +#include +int reverseRecursive(int num, int reversed) { + if (num == 0) + return reversed; + return reverseRecursive(num / 10, reversed * 10 + (num % 10)); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Reversed number = %d\n", reverseRecursive(num, 0)); + + return 0; +} +// Method 5 - Recursion The function passes the reversed number as a second argument. Each call extracts the last digit and builds reversed. When num becomes 0 the final reversed number is returned. + +// Method 6: Using String +#include +#include +int main() { + char numStr[20]; + + printf("Enter a number: "); + scanf("%s", numStr); + + int len = strlen(numStr); + // swap characters from both ends towards middle + for (int i = 0; i < len / 2; i++) { + char temp = numStr[i]; + numStr[i] = numStr[len - 1 - i]; + numStr[len - 1 - i] = temp; + } + + printf("Reversed number = %s\n", numStr); + + return 0; +} +// Method 6 - String We take the number as a string and swap characters from both ends moving towards the middle. No math needed at all. Good for practicing string manipulation and character swapping in C. + +// Method 7: Using Array +#include +int main() { + int num, digits[20], count = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + while (num != 0) { + digits[count++] = num % 10; + num /= 10; + } + + printf("Reversed number = "); + for (int i = 0; i < count; i++) + printf("%d", digits[i]); + printf("\n"); + + return 0; +} +// Method 7 - Array We extract digits one by one and store them in an array. Since %10 always gives the last digit the array naturally stores digits in reverse order. Then we just print the array. + +// Method 8: Using Stack Logic +#include +int main() { + int num, stack[20], top = -1; + + printf("Enter a number: "); + scanf("%d", &num); + + // push digits onto stack + while (num != 0) { + stack[++top] = num % 10; + num /= 10; + } + + // pop digits from stack to get reversed number + printf("Reversed number = "); + while (top >= 0) + printf("%d", stack[top--]); + printf("\n"); + + return 0; +} +// Method 8 - Stack We push each digit onto a stack array. Since stack follows Last In First Out order popping gives digits in reverse. A great way to understand stack concept using arrays in C. + +// Method 9: Using Ternary Operator +#include +int reverseNum(int num, int rev) { + return (num == 0) ? rev : reverseNum(num / 10, rev * 10 + (num % 10)); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Reversed number = %d\n", reverseNum(num, 0)); + + return 0; +} +// Method 9 - Ternary Operator The recursive function is rewritten using ternary in a single line. If num is 0 return rev else recurse with updated values. Compact and clean version of method 5. + +// Method 10: Using abs() for Negative Numbers +#include +#include +int main() { + int num, reversed = 0, isNegative = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + // handle negative numbers + if (num < 0) { + isNegative = 1; + num = abs(num); + } + + while (num != 0) { + reversed = reversed * 10 + (num % 10); + num /= 10; + } + + if (isNegative) + printf("Reversed number = -%d\n", reversed); + else + printf("Reversed number = %d\n", reversed); + + return 0; +} +// Method 10 - Negative Numbers Normal methods fail for negative numbers because % gives negative remainder in C. We store the sign first using a flag then use abs() to process normally and add sign back at end. + +// Method 11: Using Macro +#include + +int reverseHelper(int num) { + int reversed = 0; + while (num != 0) { + reversed = reversed * 10 + (num % 10); + num /= 10; + } + return reversed; +} + +#define REVERSE(n) reverseHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Reversed number = %d\n", REVERSE(num)); + + return 0; +} +// Method 11 - Macro We define REVERSE as a macro that calls the helper function. Wherever REVERSE(n) is written it gets replaced by reverseHelper(n). Good to know how macros wrap functions cleanly in C. diff --git a/Shaivi_sum_digits.Q11.c b/Shaivi_sum_digits.Q11.c new file mode 100644 index 0000000..ab42c2b --- /dev/null +++ b/Shaivi_sum_digits.Q11.c @@ -0,0 +1,182 @@ +// Sum of Digits of a Number in C + +// Method 1: Using while Loop (Brute Force) +#include +int main() { + int num, sum = 0, remainder; + + printf("Enter a number: "); + scanf("%d", &num); + + while (num != 0) { + remainder = num % 10; + sum = sum + remainder; + num = num / 10; + } + + printf("Sum of digits = %d\n", sum); + + return 0; +} +// Method 1 - While Loop We extract the last digit using %10 and add it to sum. Then remove the last digit using /10. We keep doing this until num becomes 0. Most basic and easy to understand method. + +// Method 2: Using for Loop +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + for (; num != 0; num /= 10) + sum += num % 10; + + printf("Sum of digits = %d\n", sum); + + return 0; +} +// Method 2 - For Loop Same logic as method 1 but written as a for loop. No initialization needed so we leave it empty. num /= 10 removes last digit each iteration. Compact and clean way to write it. + +// Method 3: Using do-while Loop +#include +int main() { + int num, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + do { + sum += num % 10; + num /= 10; + } while (num != 0); + + printf("Sum of digits = %d\n", sum); + + return 0; +} +// Method 3 - do-while Loop Body executes first then condition is checked. Works the same as while loop here. Completes all 3 loop types for this problem. Good to know do-while for at least one digit numbers. + +// Method 4: Using Function +#include +int digitSum(int num) { + int sum = 0; + while (num != 0) { + sum += num % 10; + num /= 10; + } + return sum; +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Sum of digits = %d\n", digitSum(num)); + + return 0; +} +// Method 4 - Function The digit sum logic is placed in a separate function digitSum() that returns the result. Main just takes input and prints. Clean reusable and well organized code structure. + +// Method 5: Using Recursion +#include +int digitSum(int num) { + if (num == 0) + return 0; + return (num % 10) + digitSum(num / 10); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Sum of digits = %d\n", digitSum(num)); + + return 0; +} +// Method 5 - Recursion The function extracts the last digit using %10 and adds it to the result of calling itself with num/10. When num becomes 0 it returns 0 and adding stops. Good recursion practice. + +// Method 6: Using String +#include +#include +int main() { + char numStr[20]; + int sum = 0; + + printf("Enter a number: "); + scanf("%s", numStr); + + for (int i = 0; i < strlen(numStr); i++) + sum += numStr[i] - '0'; + + printf("Sum of digits = %d\n", sum); + + return 0; +} +// Method 6 - String We take the number as a string. Each character digit can be converted to integer by subtracting '0' from it. We loop through all characters and keep adding. Good for practicing strings in C. + +// Method 7: Using Array +#include +int main() { + int num, digits[20], count = 0, sum = 0; + + printf("Enter a number: "); + scanf("%d", &num); + + while (num != 0) { + digits[count++] = num % 10; + num /= 10; + } + + for (int i = 0; i < count; i++) + sum += digits[i]; + + printf("Sum of digits = %d\n", sum); + + return 0; +} +// Method 7 - Array We extract each digit and store it in an array first then add them all in a second loop. Not the most efficient way but good for practicing arrays and digit extraction together. + +// Method 8: Using Ternary Operator +#include +int digitSum(int num) { + return (num == 0) ? 0 : (num % 10) + digitSum(num / 10); +} +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Sum of digits = %d\n", digitSum(num)); + + return 0; +} +// Method 8 - Ternary Operator The recursive function is rewritten using ternary operator in a single line. If num is 0 return 0 else extract last digit and recurse. Compact and clean version of method 5. + +// Method 9: Using Macro +#include + +int sumHelper(int num) { + int sum = 0; + while (num != 0) { + sum += num % 10; + num /= 10; + } + return sum; +} + +#define DIGIT_SUM(n) sumHelper(n) + +int main() { + int num; + + printf("Enter a number: "); + scanf("%d", &num); + + printf("Sum of digits = %d\n", DIGIT_SUM(num)); + + return 0; +} +// Method 9 - Macro We define DIGIT_SUM as a macro that calls the helper function. Wherever DIGIT_SUM(n) is written it gets diff --git a/Shaivi_sum_num_range.Q5.c b/Shaivi_sum_num_range.Q5.c new file mode 100644 index 0000000..ae7686c --- /dev/null +++ b/Shaivi_sum_num_range.Q5.c @@ -0,0 +1,153 @@ +// Program to find the Sum of numbers in a given range in C + +// Method 1: Using for Loop (Brute Force) +#include +int main() { + int start, end, sum = 0; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + for (int i = start; i <= end; i++) { + sum = sum + i; + } + + printf("Sum of numbers from %d to %d = %d\n", start, end, sum); + + return 0; +} +// Method 1 - Simple for Loop We run the loop from start to end and keep adding each number to sum. Very easy to understand. Most basic and straightforward way to solve this problem. + +// Method 2: Using while Loop +#include +int main() { + int start, end, sum = 0; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int i = start; + while (i <= end) { + sum += i; + i++; + } + + printf("Sum of numbers from %d to %d = %d\n", start, end, sum); + + return 0; +} +// Method 2 - While Loop Same logic as method 1 but using a while loop. We initialize i before the loop and increment it inside. Good practice to learn while loop with range problems. + +// Method 3: Using do-while Loop +#include +int main() { + int start, end, sum = 0; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int i = start; + do { + sum += i; + i++; + } while (i <= end); + + printf("Sum of numbers from %d to %d = %d\n", start, end, sum); + + return 0; +} +// Method 3 - do-while Loop Body runs first then condition is checked. Works the same as while loop here. Completes all 3 loop types. Note: gives wrong result if start is greater than end. + +// Method 4: Using Mathematical Formula +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + // Formula: sum of 1 to end minus sum of 1 to (start-1) + int sum = (end * (end + 1) / 2) - ((start - 1) * start / 2); + + printf("Sum of numbers from %d to %d = %d\n", start, end, sum); + + return 0; +} +// Method 4 - Formula We use n*(n+1)/2 twice. First get sum from 1 to end then subtract sum from 1 to (start-1). What remains is the sum of the range. No loop needed at all. + +// Method 5: Using Function +#include +int rangeSum(int start, int end) { + int sum = 0; + for (int i = start; i <= end; i++) + sum += i; + return sum; +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Sum of numbers from %d to %d = %d\n", start, end, rangeSum(start, end)); + + return 0; +} +// Method 5 - Function The loop logic is placed inside a separate function rangeSum() which takes start and end as parameters. Main just handles input and output. Clean and reusable code. + +// Method 6: Using Recursion +#include +int sumRecursive(int start, int end) { + if (start > end) + return 0; + return start + sumRecursive(start + 1, end); +} +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + printf("Sum of numbers from %d to %d = %d\n", start, end, sumRecursive(start, end)); + + return 0; +} +// Method 6 - Recursion The function adds start to the result of calling itself with start+1. It keeps going until start is greater than end then returns 0. Good for learning recursion logic. + +// Method 7: Using Array +#include +int main() { + int start, end; + + printf("Enter start of range: "); + scanf("%d", &start); + printf("Enter end of range: "); + scanf("%d", &end); + + int size = end - start + 1; + int arr[size]; + + for (int i = 0; i < size; i++) + arr[i] = start + i; + + int sum = 0; + for (int i = 0; i < size; i++) + sum += arr[i]; + + printf("Sum of numbers from %d to %d = %d\n", start, end, sum); + + return 0; +} +// Method 7 - Array We calculate the size as end-start+1 and store all numbers of the range in an array. Then add them in a second loop. Good for practising arrays with range logic.