C
This commit is contained in:
9
DeitelC/Chapter5/exercise5-42.c
Normal file
9
DeitelC/Chapter5/exercise5-42.c
Normal file
@ -0,0 +1,9 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
int c = '\0'; // variable to hold character input by user
|
||||
if ((c = getchar()) != EOF) {
|
||||
printf("%c", c);
|
||||
main();
|
||||
}
|
||||
}
|
23
DeitelC/Chapter5/exercise5-43.c
Normal file
23
DeitelC/Chapter5/exercise5-43.c
Normal file
@ -0,0 +1,23 @@
|
||||
#include <stdio.h>
|
||||
int mystery(int a, int b); // function prototype
|
||||
|
||||
int main(void) {
|
||||
printf("%s", "Enter two positive integers: ");
|
||||
int x = 0; // first integer
|
||||
int y = 0; // second integer
|
||||
scanf("%d%d", &x, &y);
|
||||
printf("The result is %d\n", mystery(x, y));
|
||||
}
|
||||
|
||||
// Parameter b must be a positive integer
|
||||
// to prevent infinite recursion
|
||||
int mystery(int a, int b) {
|
||||
// base case
|
||||
if (1 == b) {
|
||||
return a;
|
||||
} else if (b > 1) { // recursive step
|
||||
return a + mystery(a, b - 1);
|
||||
} else {
|
||||
return -a + mystery(a, b + 1);
|
||||
}
|
||||
}
|
19
DeitelC/Chapter5/greatestCommonDivisor.c
Normal file
19
DeitelC/Chapter5/greatestCommonDivisor.c
Normal file
@ -0,0 +1,19 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int gcd (int, int);
|
||||
|
||||
int main (void) {
|
||||
printf("%d\n", gcd(15, 20));
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int gcd (int x, int y) {
|
||||
if(!y) {
|
||||
return x;
|
||||
} else {
|
||||
return gcd(y, x % y);
|
||||
}
|
||||
}
|
11
DeitelC/Chapter5/recursiveMain.c
Normal file
11
DeitelC/Chapter5/recursiveMain.c
Normal file
@ -0,0 +1,11 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int main (void) {
|
||||
static int count = 1;
|
||||
|
||||
printf("%d\n", count++);
|
||||
if (count <= 5) {
|
||||
main();
|
||||
}
|
||||
return 0;
|
||||
}
|
28
DeitelC/Chapter5/recursivePrime.c
Normal file
28
DeitelC/Chapter5/recursivePrime.c
Normal file
@ -0,0 +1,28 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int isPrimeX (int, int);
|
||||
int isPrime (int);
|
||||
|
||||
int main (void) {
|
||||
printf("%d\n", isPrime(11));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int isPrime (int x) {
|
||||
return isPrimeX (x, 2);
|
||||
}
|
||||
|
||||
|
||||
int isPrimeX (int x, int i) {
|
||||
if (x <= 2) {
|
||||
return (x == 2) ? 1 : 0;
|
||||
}
|
||||
if (x % i == 0){
|
||||
return 0;
|
||||
}
|
||||
if (i * i > x) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return isPrimeX (x, i + 1);
|
||||
}
|
Reference in New Issue
Block a user