function 1/notes... · web viewa function may be given any name, with the exception of main. no...

22

Click here to load reader

Upload: habao

Post on 08-Apr-2019

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

FUNCTION

Introduction to Function

A function is a subroutine that contains one or more executable statements. A function should perform only one task. Each function has a name and a list of arguments that it will receive. A function may be given any name, with the exception of main. No function can have the same as a reserved word.

The main( ) function is always the first to execute. It doesn’t need to be first in a program, but is usually is. Good C programmer write programs that consists of many small function, even if their programs execute one or more of these functions only once.

Creating a function.

Function basic:

1. Function must have name.2. Function name - same rule that applies to naming variables.3. Function names have one set of parentheses immediately following them (). 4. The body of the function, starting immediately after the closing parentheses of the functions name

FORMAT:

Explanations:

return-value-type The data type of resulted from the function caller.The return-value-type void indicates that a function does not return a

value.Unspecified return-value-type is assumed by the compiler to be int.

function-name Any valid identifier.

parameter list A list of variable declarations that specify each parameter’s name and type.

FORMAT:type var_1, type var_2,.... , type var_NIf a function has no parameters, that is when the parameter list is empty or void, we use either function-name (void)

Programming I Page 1

return-value-type function-name ( parameter list )

{

declarations and statements

}

Page 2: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

FUNCTION STRUCTURE :

Preprocessor directive

return_type function_name(parameter ); // function prototype / function declaration

int main(){ variables declaration;

statements;function_name(parameter); // function call……….return 0;

}return_type function_name(parameter) // function header{ variables declaration;

statements; // function definition…………….return value;

}

CODING EXAMPLE (BASIC) :

#include <stdio.h>

void welcome(void);

int main(){ welcome();}

void welcome(void){ printf(“Welcome to Malaysia\n”);}

Programming I Page 2

Function Prototype/Declarations

Function Call

Function Definition

Function Header

Page 3: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

Four types of function :

Programming I Page 3

1. Function without return value and without passing parameterExample :

1. void mainMenu(void);2. void mainMenu( );

2. Function without return value but with passing parameter(s) Example :

1. void displayResult(int total);2. void display(int num, float total);

3. Function with return value but without passing parameter Example :

1. int GetInput( );2. float GetValue(void);

4. Function with return value and with passing parameter(s) Example :

1. int areaCircle(int radius);2. float average(float num1, float num2);

Page 4: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 1(a)

// Program that demonstrate the use of function // Function without return value and without passing parameter

#include <stdio.h>

// Function declaration or function prototypevoid nextFun(void);void thirdFun(void);

// The following program illustrates function calls int main(){

printf("First function called main()\n");nextFun(); // second function is called thirdFun(); // third function is called nextFun(); // second function is called thirdFun(); // third function is called nextFun(); // second function is called thirdFun(); // third function is called printf("main( ) is completed\n");system(“PAUSE”);return 0;

}

// Function definitionvoid nextFun(void) // second function declaration {

printf("Inside nextFun()\n"); // no variables are defined // in the program }

// Function definitionvoid thirdFun(void) // third function declaration {

printf("Inside thirdFun()\n");}

Programming I Page 4

Page 5: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 1(b)

// Program that demonstrate the use of external variable //Function without return value and without passing parameter(s) - global variable

#include <stdio.h>

// Function declaration or function prototypes void check(void); // External variables int numlike;

// Main function int main(void){

printf("Please enter any number you like:");scanf("%d",&numlike);

check(); // Function callsystem(“PAUSE”);return 0;

}

// Checks if number is lucky number // Function definitionvoid check(void){

if (numlike==10){

printf("Great, you are selected as best number holder\n");}else{

printf("Sorry, you failed. Try again\n");}

}

Programming I Page 5

Page 6: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 2(a)

//Program that demonstrate the use of internal variable & passing parameter //Function without return value but with passing parameter(s)

#include <stdio.h>

// Function declaration or function prototypes void check(int numlike);

// Main function int main(void){

// Local variables int numlike;

printf("Please enter any number you like:");scanf("%d",&numlike);

check(numlike); // Function call system(“PAUSE”);return 0;

}

// Checks if number is lucky number // Function definition

void check(int numlike){

if (numlike==10){

printf("Great, you are selected as best number holder\n");}else{

printf("Sorry, you failed. Try again\n");}

}

Programming I Page 6

Page 7: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 2(b)

// Program that demonstrate the use of functions returning integer value //Function without return value but with passing parameter(s) #include <stdio.h>

// Function declaration or prototypevoid multiply(int num1, int num2);

int main(){

int num1, num2;printf("Please enter first number :");scanf("%d",&num1);printf("Please enter second number : ");scanf("%d",&num2);

multiply(num1,num2); system(“PAUSE”);return 0;

}

// Function definitionvoid multiply (int num1, int num2) {

int ans;ans = num1*num2; printf("The answer is %d\n",ans);

}

Programming I Page 7

Page 8: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 2(c)

// Program that demonstrate the use of functions returning floating point value //Function without return value but with passing parameter(s) #include <stdio.h>

//Function declaration @ prototypevoid sum(float a, float b);

// Main programint main(){

float first, second;first = 1023.23;second = 990.9;sum(first,second);system(“PAUSE”);return 0;

}

// Function definitionvoid sum(float a, float b) {

float ans;ans = a+ b; printf("The answer is %.2f\n",ans);

}

Programming I Page 8

Page 9: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 3

//Function with return value but without passing parameter

#include <stdio.h>

// Function declaration or function prototypes int get_input();

// Main function int main(){

int input;input = get_input(); // Function callprintf("Number entered is %d\n",input);system(“PAUSE”);return 0;

}

// Function definition (to get input)int get_input(){

int numlike;printf("Please enter any number you like :");scanf("%d",&numlike);return (numlike);

}

Programming I Page 9

Page 10: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 4

//Function with return value and with passing parameter

#include <stdio.h>

// Function declaration or function prototypes int calculate(int numlike);

// Main function int main(){

int numlike, answer;

printf("Please enter any number you like :");scanf("%d",&numlike);

answer = calculate(numlike); // Function callprintf("Answer :%d\n",answer);system(“PAUSE”);return 0;

}

// Function definition (to calculate)int calculate(int numlike){

int ans;ans = numlike * numlike;return (ans);

}

Programming I Page 10

Page 11: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 5

/* Program that demonstrate the use of function and parameter passing */

#include <stdio.h>

// Function declaration or function prototypes int getInput();void displayInput(int input);void checkInput(int input);

// Main function Int main(){

int input;

input = getInput(); // Function calldisplayInput(input); // Function callcheckInput(input); // Function callsystem(“PAUSE”);return 0;

}

// Function definition (to get input)int getInput(){

int numlike;printf("Please enter any number you like :");scanf("%d",&numlike);return(numlike);

}

// Function definition (to display input)void displayInput(int input){

printf("The number you like is %d\n",input);}

// Function definition (to checks if number is lucky number) void checkInput(int input){

if (input==10) printf("Great, you are selected as best number holder\n");else

printf("Sorry, you failed. Try again\n");}

Programming I Page 11

Page 12: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

Math Library Function

Math library function allows the programmer to perform certain common mathematical calculations. Functions are normally called by writing the name of the function followed by the argument (or a comma-separated list of arguments) of the function followed by a right parenthesis.

For example, a programmer desiring to calculate and print the square root of 9.00 using Math Library Function might writeprintf(“Square root of 9 is %d", sqrt(9) );When this statement is executed, the math library function sqrt is called to calculate the square root of the number contained in the parenthesis (9). The number 9 is the argument of the sqrt function.

Table shows commonly used math library functions.

Function Description Exampleceil ( x ) round x to the smallest integer

not less than xceil( 9.2 ) is 10.0ceil( - 9.8 ) is - 9.0

cos ( x ) trigonometric cosine of x(x in radians)

cos ( 0. 0 ) is 1.0

exp ( x ) exponential function ex exp ( 1.0 ) is 2.71828exp ( 2.0 ) is 7.38906

fabs ( x ) absolute value of x if x > 0 then abs ( x ) is xif x = 0 then abs ( x ) is 0if x < 0 then abs ( x ) is x

floor ( x ) rounds x to the largest integer not greater than x

floor ( 9.2 ) is 9.0floor ( - 9.8 ) is - 10.0

fmod ( x , y ) reminder of x / y as a floating point number

fmod ( 13.657 , 2.333 ) is1.992

log ( x ) natural logarithm if x (base e) log ( 2.718282 ) is 1.0log ( 7.389056 ) is 2.0

log10 ( x ) logarithm of x (base 10) log ( 10.0 ) is 1.0log ( 100.0 ) is 2.0

pow ( x , y) X raised to power y ( x y ) pow ( 2 , 7) is 128pow ( 9 , .5 ) is 3

sin ( x ) trigonometric sine of x ( x in radians )

sin ( 0.0 ) is 0

sqrt ( x ) square root of x sqrt ( 900.0 ) is 30.0sqrt ( 9.0 ) is 3.0

tan ( x ) trigonometric tangent of x( x in radians )

tan ( 0.0 ) is 0

Programming I Page 12

Page 13: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

EXAMPLE 1 : Math Library Function

printf(“Power of 92 is %.2f:", pow(9,2));

EXAMPLE 2 : Function

//Program that demonstrates uses a function with arguments to calculate sqrt #include <stdio.h>

// Function declaration or function prototypevoid power(float num1);

// Main functionint main(){

float num1;

printf("Please enter any number you like:");scanf("%f",&num1);power(num1); // Function call power() with passing valuesystem(“PAUSE”);return 0;

} // Function definitionvoid power(float num1) {

printf("Power of %.2f is %.2f\n",num1,num1*num1);}

Programming I Page 13

Page 14: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

Function exercise

Exercise 1

Write a C program which consist of the following function prototype(declaration).

a. void displayHeader();a. float getFloat();c. void displayFloat(float aFloat);d. void displayFooter();

From main function your have to call the function accordingly.

Please download the sample output from

http://www.yosof.net/teaching/BED14103-Programming%201/Exercises/function_exercise1.exe

or view the video here

Exercise 2

Write a program to find the power 2 of an integer.The program consists of the following function prototype.

a. void displayHeader();b. int getInteger();c. int power2(int aNum);d. void displayResult(int num, int result);e. void displayFooter();

From main function your have to call the function accordingly.

Please download the sample output from

http://www.yosof.net/teaching/BED14103-Programming%201/Exercises/function_exercise2.exe

or view the video here

Exercise 3

Write a C program to convert mark to grade point and mark to grade.This program consist 5 function.

a. funtion to display Introduction of the program(no passing parameter and no return value).

Programming I Page 14

Page 15: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

b. function to get mark from user ( this function will ask user to enter mark then return the mark).

c. function to convert mark to gp.( this function will accept mark as a parameter and return the gp)

d. function to convert mark to grade.( this function will accept mark as a parameter and return the grade)

e. funtion to display mark, gp and grade (this funtion will have 3 passing parameter e.g mark,gp and grade).

From main function call the functions accordingly.

The conversion table is given below:

GRADE GPA MARKSA 4.00 80-100A- 3.67 75-79B+ 3.33 70-74B 3.00 65-69B- 2.67 60-64C+ 2.33 55-59C 2.00 50-54C- 1.67 45-49D 1.00 40-44F 0.00 0-39

Please download the sample output from

http://www.yosof.net/teaching/BED14103-Programming%201/Exercises/function_exercise3.exe

or view the video here

Exercise 4

Write a C program to construct a mini calculator system.This function consist of 7 functions.

a. function header as introduction of the systemb. function footer to display a copyright.c. function getInteger.(this function will ask user to enter an integer then return the value)d. function add .( this function will have 2 passing parameter , do addition operation and return the result)e. function sub .( this function will have 2 passing parameter , do subtract operation and return the result)f. function mul .

Programming I Page 15

Page 16: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

( this function will have 2 passing parameter , do multiply operation and return the result)g. function dev .( this function will have 2 passing parameter , do devide operation and return the result)

From main function you have to call the function accordingly.

Exercise 5

Write a c program to calculate gpa for a student(Please refer to the Exercise 3.....just continue from answer of exercise 3)

Using function ask user to enter no of subject.

Please download the sample output from

http://www.yosof.net/teaching/BED14103-Programming%201/Exercises/function_exercise5.exe

Exercise 6

Write a C program of Mark Conversion System. The program will convert from mark to grade point or from mark to grade or from mark to both grade point and grade for any mark entered by user.

The conversion table is given below:

GRADE GPA MARKSA 4.00 80-100A- 3.67 75-79B+ 3.33 70-74B 3.00 65-69B- 2.67 60-64C+ 2.33 55-59C 2.00 50-54C- 1.67 45-49D 1.00 40-44F 0.00 0-39

Note:You are required to use AT LEAST 4 type of FUNCTIONS statements when writing the program.Write a menu driven program which has the following options:

a. Mark to Grade Point (GP) Conversion.b. Mark to Grade Conversion.c. Mark to Grade Point and Gradeo. Exit

The interface of the system should be as follows:

Mark Conversion System for British Malaysian Institute Sdn. Bhd.

Programming I Page 16

Page 17: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

-----------------------------------------------------------------------a. Mark to Grade Point (GP) Conversionb. Mark to Grade Conversionc. Mark to Grade Point and Gradeo. Exit-----------------------------------------------------------------------Please enter your choice :

If .a. is entered:-----------------------------------------------------------------------Mark Conversion System for British Malaysian Institute Sdn. Bhd

Mark to Grade point (GP)-----------------------------------------------------------------------

Please enter the mark: 80.0For the mark= 80.0 the GP is 4.00-----------------------------------------------------------------------then the program shall return to the menu

If .b. is entered:-----------------------------------------------------------------------Mark Conversion System for British Malaysian Institute Sdn. Bhd

Mark to Grade -----------------------------------------------------------------------

Please enter the mark: 80.0For the mark= 80.0 the Grade is A-----------------------------------------------------------------------then the program shall return to the menu

If .c. is entered:-----------------------------------------------------------------------Mark Conversion System for British Malaysian Institute Sdn. Bhd

Mark to Grade Point and Grade -----------------------------------------------------------------------

Please enter the mark: 80.0For the mark= 80.0 the Grade Point is 400 and Grade is A-----------------------------------------------------------------------then the program shall return to the menu

The program MUST check whether the value of unit input by the user is positive, zero or negative.

Error message MUST be displayed if zero or negative values are typed in.

If .o. is entered, the program shall end.Otherwise, the program shall return to the first screen by mentioning wrong choice is entered.

Please download the sample output from

Programming I Page 17

Page 18: FUNCTION 1/Notes... · Web viewA function may be given any name, with the exception of main. No function can have the same as a reserved word. ( The main( ) function is always the

Universiti Kuala Lumpur -BMI ______________________________________________________________________________

http://www.yosof.net/teaching/BED14103-Programming%201/Exercises/function_exercise6.exe

Programming I Page 18