Chapter 4
#include <stdio.h>
#include <stdlib.h>
main(){
int i, abs_val(int);;
for(i = -10; i <= 10; i++)
printf("abs of %d is %d\n", i, abs_val(i));
exit(EXIT_SUCCESS);
}
int
abs_val(int x){
if(x < 0)
return(-x);
return(x);
}
There are two files that form the answer to this exercise. This is the
first.
#include <stdio.h>
#include <stdlib.h>
int curr_line(void), curr_col(void);
void output(char);
main(){
printf("line %d\n", curr_line());
printf("column %d\n", curr_col());
output('a');
printf("column %d\n", curr_col());
output('\n');
printf("line %d\n", curr_line());
printf("column %d\n", curr_col());
exit(EXIT_SUCCESS);
}
The second file contains the functions and static variables.
#include <stdio.h>
int curr_line(void), curr_col(void);
void output(char);
static int lineno=1, colno=1;
int
curr_line(void){
return(lineno);
}
int
curr_col(void){
return(colno);
}
void
output(char a){
putchar(a);
colno++;
if(a == '\n'){
colno = 1;
lineno++;
}
}
The recursive function:
#include <stdio.h>
#include <stdlib.h>
void recur(void);
main(){
recur();
exit(EXIT_SUCCESS);
}
void
recur(void){
static ntimes;
ntimes++;
if(ntimes < 100)
recur();
printf("%d\n", ntimes);
ntimes--;
}
And finally, the largest of all of the answers.
#include <stdio.h>
#include <stdlib.h>
#define PI 3.141592
#define INCREMENT (PI/20)
#define DELTA .0001
double sine(double), cosine(double);
static unsigned int fact(unsigned int n);
static double pow(double x, unsigned int n);
main(){
double arg = 0;
for(arg = 0; arg <= PI; arg += INCREMENT){
printf("value %f\tsine %f\tcosine %f\n", arg, sine(arg), cosine(arg));
}
exit(EXIT_SUCCESS);
}
static unsigned int
fact(unsigned int n){
unsigned int answer;
answer = 1;
while(n > 1)
answer *= n--;
return(answer);
}
static double
pow(double x, unsigned int n){
double answer;
answer = 1;
while(n){
answer *= x;
n--;
}
return(answer);
}
double
sine(double x){
double difference, thisval, lastval;
unsigned int term;
int sign;
sign = -1;
term = 3;
thisval = x;
do{
lastval = thisval;
thisval = lastval + pow(x, term)/fact(term) * sign;
term += 2;
sign = -sign;
difference = thisval - lastval;
if(difference < 0)
difference = -difference;
}while(difference > DELTA && term < 16);
return(thisval);
}
double
cosine(double x){
double difference, thisval, lastval;
unsigned int term;
int sign;
sign = -1;
term = 2;
thisval = 1;
do{
lastval = thisval;
thisval = lastval + pow(x, term)/fact(term) * sign;
term += 2;
sign = -sign;
difference = thisval - lastval;
if(difference < 0)
difference = -difference;
}while(difference > DELTA && term < 16);
return(thisval);
}
|
Printer-friendly version
The C Book
This book is published as a matter of historical interest.
Please read the
copyright and disclaimer information.
GBdirect Ltd provides up-to-date training and consultancy in
C,
Embedded C,
C++
and a wide range of
other subjects based on
open standards if you happen to be interested.
|