1. Factorial Program
Using Iteration
#include <stdio.h>
int main() {
int n, i;
unsigned long long fact = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
if(n < 0)
printf("Factorial is not defined for negative numbers.\n");
else {
for(i = 1; i <= n; i++)
fact *= i;
printf("Factorial of %d = %llu\n", n, fact);
}
return 0;
}
Using Recursion
#include <stdio.h>
unsigned long long factorial(int n) {
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
if(n < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("Factorial of %d = %llu\n", n, factorial(n));
return 0;
}
2. Power of a Number Program
Description
Calculates base^exponent using a function.
Program
#include <stdio.h>
double power(double base, int exponent) {
double result = 1;
for(int i = 1; i <= exponent; i++)
result *= base;
return result;
}
int main() {
double base;
int exponent;
printf("Enter base and exponent: ");
scanf("%lf %d", &base, &exponent);
printf("%.2lf^%d = %.2lf\n", base, exponent, power(base, exponent));
return 0;
}
Sample Output:
Enter base and exponent: 2 5
2.00^5 = 32.00
3. Menu-Driven Program
Description
A program that allows the user to choose operations from a menu using functions.
Program
#include <stdio.h>
void add() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d\n", a + b);
}
void subtract() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Difference = %d\n", a - b);
}
void multiply() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Product = %d\n", a * b);
}
int main() {
int choice;
do {
printf("\nMenu:\n1. Add\n2. Subtract\n3. Multiply\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1: add(); break;
case 2: subtract(); break;
case 3: multiply(); break;
case 4: printf("Exiting program...\n"); break;
default: printf("Invalid choice!\n");
}
} while(choice != 4);
return 0;
}
Sample Output:
Menu:
1. Add
2. Subtract
3. Multiply
4. Exit
Enter your choice: 1
Enter two numbers: 5 10
Sum = 15
Key Points to Remember
- Use functions for modular, reusable code
- Menu-driven programs improve user interaction
- Always include input validation
- Recursion and iteration both can solve factorial problems