TP10-Function
Lab’s objectives:
• Using function to separate tasks (code grouping) under a name containing a piece of codes which
make our code more readable, reusable and easy to fix bugs
Deadline: 6 days
---------------------------------------------------------------------------------------------------------------------------
Problem1: Create a function in C programming to display all sequence numbers from 1 to n
except the number 10, where n is a parameter of this function.
Example:
INPUT:
Enter a number: 20
Output:
Display number using function displaySequence(1, 20):
1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 20
………..
INPUT:
Enter a number: -7
Output:
Invalid input number. You are only allowed to input the positive number greater than 1.
Problem2: Create a function in C programming to compute a cube of a number n, where n is
taken as a parameter of this function. This function has a return value which is the cube of the
number n passed though the function parameter. The program asks a user to input the number n,
then call the function to compute the cube. Keep the program running as an infinite loop such
that the user can test with as many numbers as possible.
Remark: Validate the input number so that it only allows the positive number
Example:
INPUT:
Enter a number: 5
Output:
The cube of 5 equals to: 125
………..
INPUT:
Enter a number: 0
Output:
Error! Invalid input number! You must input a number greater than 0. Please try again!
Problem3 : Create a function in C to calculate the factorial of a number n, where n is a
parameter. The function should return the factorial of n. If n is less than 0, print an error message.
Example:
INPUT:
Enter a number: 5
Output:
The factorial of 5 is 120.
INPUT:
Enter a number: 0
Output:
Invalid input! Please enter a non-negative number !
Problem4 : Create a function in C that takes an integer n as a parameter and returns the sum of
its digits.
Example:
INPUT:
Enter a number: 1234
Output:
The sum of the digits of 1234 is 10.
Problem5 : Create a function in C to check if a number n is prime. The function should return 1
if the number is prime, and 0 otherwise. The program should prompt the user for input and
validate that the input is greater than 1.
Example:
INPUT:
Enter a number that greater than 1: 7
Output:
7 is a prime number.
INPUT:
Enter a number that greater than 1: 4
Output:
4 is not a prime number.