Practice Web Page - http://www.cs.tau.ac.il/~efif/courses/Programming_Fall_04
int multByTwo(int x) { int retval; retval = x * 2; return retval; } |
#include <stdio.h> int multByTwo(int x); int main(void) { int i; for (i = 0; i < 10; ++i) { int j; j = multByTwo(i); printf ("%d times two is %d\n", i, j); } |
#include <stdio.h> #include <math.h> int main() { int i, prime, sq; printf("Enetr a number: "); if (scanf("%d", &prime) != 1) { printf("ERROR: failed to read a number!\n"); return -1; } sq = (int) sqrt(prime); for (i = 2; (i <= sq) && (prime % i != 0); i++); if (i > sq) printf("%d is prime\n", prime); else printf("%d is not prime (divided by %d)\n", prime, i); return 0; } |
#include <stdio.h> #include <math.h> int main() { int i, j, sq, last; printf("Enetr a number: "); if (scanf("%d", &last) != 1) { printf("ERROR: failed to read a number!\n"); return -1; } for (i = 2; i <= last; i++) { sq = (int) sqrt(i); for (j = 2 ; j <= sq; j++) if (i % j == 0) break; if (j > sq) printf("the number %d is prime\n", i); } return 0; } |
#include <stdio.h> #include <math.h> int is_prime(int num) { int i, sq; sq = (int) sqrt(num); for (i = 2 ; i <= sq; i++) { if (num % i == 0) return 0; } return 1; } int main() { int i, j, sq, last; printf("Enetr a number: "); if (scanf("%d", &last) != 1) { printf("ERROR: failed to read a number!\n"); return -1; } for (i = 2; i <= last; i++) { if (is_prime(i) == 1) printf("the number %d is prime\n", i); } return 0; } |
double pi1(int num) { double result = 0.0; int i; for (i = 1; i <= num; i++) result += 1.0 / (i * i); result *= 6; return sqrt(result); } |
double pi2(double epsilon) { double result = 0.0; double expr; int i = 0; do { double sign = (i % 2 == 0) ? 1.0 : -1.0; expr = 1.0 / (2.0 * i + 1); result += sign * expr; i++; } while(expr > epsilon); return result * 4.0; } |