Writing to a file
/* write_file.c */
#include <stdio.h>
#include <math.h>
# define Pi M_PI
int main()
{
int i;
FILE *fp;
fp = fopen("output.txt","w");
fprintf(fp, " Angle \t Sine \n");
fprintf(fp, "--------------------------\n");
for (i = 0;i <= 90;i++)
fprintf(fp,"%2d \t %f\n",i,sin((i/90.0)*(Pi/2)));
fclose(fp);
}
Powers of 2
#include <stdio.h>
unsigned long power2(int exp) {
unsigned long res;
if (exp == 0)
res = 1; /* Zeroth power is equal to 1 */
else
res = 2 * power2(exp-1); /* Recursive definition of power2 */
return(res);
}
int main() {
int m, n;
printf("Enter a positive integer > ");
scanf("%d",&n);
for(m = 1; m <= n; m=m+1 )
printf("%2d power of 2 is equal to %12lu.\n",m, power2(m));
}
Factorial
#include <stdio.h>
int fact(int n) {
int res;
if (n == 0)
res = 1; /* Factorial of 1 is equal to 1 */
else
res = n * fact(n-1); /* Recursive definition of factorial of n */
return(res);
}
int main() {
int n;
printf("Enter a positive integer > ");
scanf("%d",&n);
printf("%d factorial is equal to %d.\n",n, fact(n));
}