Exercise Sheet 1 - Functions
Exercise Sheet 1 - Functions
Set (1)
Ex1. Write a method to get mean of the degrees of student
(Test your function using these values Math = 80 , Science =67, Arabic= 65 , Studies= 88 ,
English = 56 ).
Ex2. Write a method to transfer inches to centimeters (1 inch= 2.54 centimeters)
Ex3. Write a method to get the volume and the area of a sphere or radius r
Ex4. Write a program to tell whether a number is prime.
Ex5. Write a program that uses the function defined in exercise 4 to calculate the summation
of prime numbers between 1 and 100.
Ex6. Write a program that takes a series of numbers and counts the number of positive and
negative values. (Hint: take user input in the function)
Ex7. Write a program that takes a series of numbers and counts the number of odd and even
values. (Hint: take user input in the function)
Bonus exercise: Write a C++ program to calculate 10 Fibonacci numbers, where each number
is calculated as the total of its two preceding values, starting with 1 and 2.
Set (2)
1. What is wrong with the following Method?
int show(int x) {
System.out.printf("%d %d\n", x, x*x);
return x*x;
System.out.printf("%d %d\n", x, x*x*x);
return x*x*x;
}
4. Write a Method that takes two integers as arguments and returns the
value of the larger one.
5. Write a Method that takes three integers as arguments and returns the
value of the largest one.
6. Write a Method that takes a real number as an argument and returns the
absolute value of that number.
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.
#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;
}
#include <stdio.h>
13. Run the following program through the compiler to see the
error messages that gcc (or cc) produces for semicolon errors.
int main(void) {
int a, b, c;
c = 0
b = 0;
if (a > b)
c = 0
else
b = 0;
return 0;
}