EXERCISES ON C FUNCTIONS
1. What is wrong with the following C function?
int square(int x);
{ return x*x; }
2. What is the effect of calling show(4)?
int show(int x) {
printf("%d %d\n", x, x*x);
return x*x;
printf("%d %d\n", x, x*x*x);
return x*x*x;
}
3. What does the following C function do?
int eq3(int a, int b, int c) {
if ((a == b) && (a == c))
return 1;
else
return 0;
}
4. Write a C function that takes two integers as arguments and
returns the value of the larger one.
5. Write a C function that takes three integers as arguments and
returns the value of the largest one.
6. Write a C function that takes a real number as an argument
and returns the absolute value of that number.
7. Write a C function that takes a positive integer n as an argument and
returns the largest power of two greater than or equal to n.
8. Write a C function that takes a positive integer n as an argument and
returns 1 if n is prime, and 0 otherwise.
9. Write a C function that takes a positive integer n as an argument and
returns 0 if n is prime, and 1 otherwise.
10. Write a function that takes a positive integer as input and
returns the leading digit in its decimal representation. For
example, the leading digit of 234567 is 2.
11. What values are printed out by the following C program?
#include <stdio.h>
int f(int x) {
return x + 2;
}
int main(void) {
int x = 5;
printf("%d %d\n", f(x+2), f(f(x+2)));
return 0;
}
12. What values are printed out by the following C program?
#include <stdio.h>
int confusion(int x, int y) {
x = 2*x + y;
return x;
}
int main(void) {
int x = 2, y = 5;
y = confusion(y, x);
x = confusion(y, x);
printf("%d %d\n", x, y);
return 0;
}
13. Run the following program through the compiler to see the
error messages that gcc (or cc) produces for semicolon errors.
int square (int x);
{ return x*x; }
int main(void) {
int a, b, c;
c = 0
b = 0;
if (a > b)
c = 0
else
b = 0;
return 0;
}