FUNCTIONS EXAMPLES.

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

Building Java Programs
Computer Programming w/ Eng. Applications
Return values.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
7. C program structure.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
CP104 Introduction to Programming Top-down design with functions Lecture 6-8 __ 1 Top-Down Design with Functions C Library functions Case studies Top-down.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) MATH Functions in C Language.
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
STANDARD FUNCTIONS Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Nested LOOPS.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
The switch Statement.  Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each.
Dr. Soha S. Zaghloul2 Let arr be an array of 20 integers. Write a complete program that first fills the array with up to 20 input values. Then, the program.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Programming 2 Overview of Programming 1. Write the equations in C++ notation : a) R =   a + b  24  2 a  b) W = a 12 + b 2 – 2abcos(y) 2a.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
USING & CREATING FUNCTIONS. MODULAR PROGRAMMING  Why Modular Programming?  Improves Readability & Understandability  Improve Maintainability  Allows.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
Repetition statements
ARRAYS.
Variables, Operators, and Expressions
Simple C Programs.
Decision making If.. else statement.
Chapter 6: User-Defined Functions I
ECE Application Programming
Functions in C ++ Subject: Programming Languages ​​for III year Topic: functions, member class.
FUNCTION Functions is a sub-program that contains one or more statements and it performs some task when called.
Mathematical Functions
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
BIL 104E Introduction to Scientific and Engineering Computing
TMF1414 Introduction to Programming
ECE Application Programming
Functions, Part 2 of 2 Topics Functions That Return a Value
REPETITION STATEMENTS
Introduction to Programming
Math Library and IO formatting
User-Defined Functions
Formatted and Unformatted Input/Output Functions
Control Statement Examples
Arrays, Part 1 of 2 Topics Definition of a Data Structure
IDENTIFIERS CSC 111.
Functions.
SELECTION STATEMENTS (2)
Lecture4.
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
The switch Statement Topics Multiple Selection switch Statement
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Decision making If statement.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
REPETITION STATEMENTS
Computer Programming Techniques Semester 1, 1998
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays I Handling lists of data.
Introduction to Problem Solving and Programming
Functions Extra Examples.
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
The switch Statement Topics Multiple Selection switch Statement
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 2 of 2 Topics Array Names Hold Address How Indexing Works
ICS103: Programming in C 5: Repetition and Loop Statements
Functions in C Math Library Functions Functions Function Definitions
Presentation transcript:

FUNCTIONS EXAMPLES

1. EXAMPLE (1) Write a complete modular program that accepts a score in the main program, then calls the function GetGrade that calculates the corresponding letter grade. The program should stop if the user enters -999. The function should consider invalid scores. #include <stdio.h> char GetGrade (double score); int main (void) { double score; char grade; do { printf (“Enter student’s score>”); scanf (“%f”, &score); if (score == -999.0) break; grade = GetGrade (score); printf (“Grade = %c”, grade); } while (score != -999.0); } // end main Dr. Soha S. Zaghloul 2

1. EXAMPLE (1) – cont’d char GetGrade (double score) { char grd; if (score >= 0.0) && (score < 60.0) grd=‘F’; else if (score >= 60.0) && (score < 70.0) grd=‘D’; else if (score >= 70.0) && (score < 80.0) grd=‘C’; else if (score >= 80.0) && (score < 90.0) grd=‘B’; else if (score >= 90.0) && (score < 100.0) grd=‘A’; else grd=‘X’; return (grd); } // end GetGrade Dr. Soha S. Zaghloul 3

1. EXAMPLE (1) – cont’d #include <stdio.h> char GetGrade (double score); int main (void) { double score; char grade; do { printf (“Enter student’s score>”); scanf (“%f”, &score); if (score == -999.0) break; grade = GetGrade (score); if (grade != ‘X’) printf (“Grade = %c”, grade); else printf (“Invalid Input”); } while (score != -999.0); } // end main Dr. Soha S. Zaghloul 4

1. EXAMPLE (1) – the whole program #include <stdio.h> char GetGrade (double score); int main (void) { double score; char grade; do { printf (“Enter student’s score>”); scanf (“%f”, &score); if (score == -999.0) break; grade = GetGrade (score); if (grade != ‘X’) printf (“Grade = %c”, grade); else printf (“Invalid Input”); } while (score != -999.0); } // end main char GetGrade (double score) char grd; if (score >= 0.0) && (score < 60.0) grd=‘F’; else if (score >= 60.0) && (score < 70.0) grd=‘D’; else if (score >= 70.0) && (score < 80.0) grd=‘C’; else if (score >= 80.0) && (score < 90.0) grd=‘B’; else if (score >= 90.0) && (score < 100.0) grd=‘A’; else grd=‘X’; return (grd); } // end GetGrade Dr. Soha S. Zaghloul 5

Sentinel cannot be -999 as we validate user entry, so we use a flag. 2. EXAMPLE (2) Write a complete modular program that accepts a score in the main program, then calls the function GetGrade that calculates the corresponding letter grade. The program should stop if the user enters -999. The user is not allowed to enter values less than 0 or greater than 100. #include <stdio.h> char GetGrade (double score); int main (void) { double score; char grade, ans; do { score = -1.0; while (score < 0.0) || (score > 100.0) printf (“Enter student’s score>”); scanf (“%f”, &score); } // end while (score < 0.0…. grade = GetGrade (score); printf (“Would you like to continue? (Y/N)”); scanf(“%c” &ans); } while (ans != ‘N’); } // end main Sentinel cannot be -999 as we validate user entry, so we use a flag. Validating user entry Update Dr. Soha S. Zaghloul 6

2. EXAMPLE (2) – cont’d char GetGrade (double score) { char grd; if (score >= 0.0) && (score < 60.0) grd=‘F’; else if (score >= 60.0) && (score < 70.0) grd=‘D’; else if (score >= 70.0) && (score < 80.0) grd=‘C’; else if (score >= 80.0) && (score < 90.0) grd=‘B’; else if (score >= 90.0) && (score < 100.0) grd=‘A’; else grd=‘X’; return (grd); } Dr. Soha S. Zaghloul 7

2. EXAMPLE (2) – the whole program #include <stdio.h> char GetGrade (double score); int main (void) { double score; char grade, ans; do { score = -1.0; while (score < 0.0) || (score > 100.0) printf (“Enter student’s score>”); scanf (“%f”, &score); } // end while (score < 0.0…. grade = GetGrade (score); printf (“Would you like to continue? (Y/N)”); scanf(“%c” &ans); } while (ans != ‘N’); } // end main char GetGrade (double score) char grd; if (score < 60.0) grd=‘F’; else if (score >= 60.0) && (score < 70.0) grd=‘D’; else if (score >= 70.0) && (score < 80.0) grd=‘C’; else if (score >= 80.0) && (score < 90.0) grd=‘B’; else grd=‘A’; return (grd); } // end GetGrade Dr. Soha S. Zaghloul 8

3. EXAMPLE (3) Write a complete modular program that accepts a score in the main program, then calls the function GetGrade that calculates the corresponding letter grade. The program should stop if the user enters -999. The user is not allowed to enter values less than 0 or greater than 100. The program should then count the number of students in each grade. Dr. Soha S. Zaghloul 9

3. EXAMPLE (3) – the whole program #include <stdio.h> char GetGrade (double score); int main (void) { int Acount=0, Bcount=0, Ccount=0, Dcount=0, Fcount=0; //declare & initialize counters double score; char grade, ans; do { score = -1.0; while (score < 0.0) || (score > 100.0) printf (“Enter student’s score>”); scanf (“%f”, &score); } // end while (score < 0.0…. grade = GetGrade (score); switch (grade) { case ‘A’: Acount++; break; case ‘B’: Bcount++; break; case ‘C’: Ccount++; break; case ‘D’: Dcount++; break; case ‘F’: Fcount++; break; } //end switch printf (“Would you like to continue? (Y/N)”); scanf(“%c” &ans); } while (ans != ‘N’); printf (“Acount= %d, Bcount= %d, Ccount= %d, Dcount= %d, Fcount= %d”, Acount, Bcount, Ccount, Dcount, Fcount); } // end main char GetGrade (double score) ---- (refer to previous slides) return (grd); } // end GetGrade Dr. Soha S. Zaghloul 10

4. EXAMPLE (4) Write a complete modular program that accepts an integer number n and calculates its factorial in the function factorial. The user is not allowed to enter negative numbers. #include <stdio.h> int factorial (int n); int main (void) { int result, number = -1; while (number < 0) printf (“Enter an integer positive number>”); scanf (“%d”, number); } // end while (number < 0) result = factorial (number); printf (“Factorial of %d = %d”, number, result); } // end main Dr. Soha S. Zaghloul 11

4. EXAMPLE (4) – cont’d int factorial (int n) { int product = 1, i; switch (n) case 0: case 1: product = 1; break; default: for (i = n; i > 1; i--) product *= i; // product = product * i; } return (product); } //end factorial Update Dr. Soha S. Zaghloul 12

4. EXAMPLE (4) – the whole program #include <stdio.h> int factorial (int n); int main (void) { int result, number = -1; while (number < 0) { printf (“Enter an integer positive number>”); scanf (“%d”, number); } // end while (number < 0) result = factorial (number); printf (“Factorial of %d = %d”, number, result); } // end main int factorial (int n) { int product = 1, i; switch (n) { case 0: case 1: product = 1; break; default: for (i = n; i > 1; i--) product *= i; // product = product * i; } // end switch return (product); } //end factorial Dr. Soha S. Zaghloul 13

5. EXAMPLE (5) Rewrite the payroll program in lecture L 8.3 (see below) by moving the loop processing into a function subprogram called payroll. Return the total payroll amount payroll as the function result. total_pay = 0; //accumulator variable initialized count_emp = 0; while (count_emp < 7) { printf (“hours> “); scanf (“%d”, &hours); printf (“rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“pay is SR%6.2f\n”, pay); count_emp++; //count_emp = count_emp + 1; total_pay = total_pay + pay; // total_pay += pay; } // end of while loop printf (“\n all employees processed\n”); printf (“total payroll is sr%8.2f\n”, total_pay); Dr. Soha S. Zaghloul 14

5. EXAMPLE (5) – cont’d The function returns the total payment which is of type double  function’s type is double. The function receives the number of employees number of type int  formal parameter is an integer variable. int count_emp; double hours, rate, pay, total_pay; total_pay = 0; //accumulator variable initialized printf (“enter number of employees>”); scanf (“%d”, count_emp); for (i= 1; i<= count_emp; i++) { printf (“hours> “); scanf (“%d”, &hours); printf (“rate> “); scanf (“%f”, &rate); pay = hours * rate; printf (“pay is SR%6.2f\n”, pay); total_pay += pay; } // end of for loop printf (“\n all employees processed\n”); printf (“total payroll is SR %8.2f\n”, total_pay); Dr. Soha S. Zaghloul 15

5. EXAMPLE (5) – the whole program #include <stdio.h> double payroll (int number); int main (void) { int count_emp; double total_pay; printf (“enter number of employees>”); scanf (“%d”, count_emp); total_pay = payroll (count_emp); printf (“\n all employees processed\n”); printf (“total payroll is SR %8.2f\n”, total_pay); } //end main double payroll (int number) { int i; double hours, rate, pay, total = 0.0; for (i= 1; i<= number; i++) printf (“Enter hours> “); scanf (“%f”, hours); printf (“Enter rate> “); scanf (“%f”, rate); pay = hours * rate; total += pay; } //end for return (total); } // end payroll Dr. Soha S. Zaghloul 16

6. Generalization of payroll function By using generic names, the same function could be used in multiple purposes such as the calculation of: Total points a student earned (credit hours * points) Total sales of a store (item * price) Total taxes (income * tax) and so on… double Sum_of_Product (int number) { int i; double item1, item2, product, total = 0.0; for (i= 1; i<= number; i++) { printf (“Enter item1> “); scanf (“%f”, item1); printf (“Enter item2> “); scanf (“%f”, item2); product = item1 * item2; total += product; } //end for return (total); } // end payroll Dr. Soha S. Zaghloul 17

7. self-check Exercise (1) Write a complete modular program that displays a menu, and performs the appropriate action accordingly in the corresponding function. The menu and the function names are listed below: Option Action Name Return 1 Exchange num1 and num2 Swap nothing 2 Exchange num2 and num3 Swap nothing 3 Exchange num1 and num3 Swap nothing 4 Sort the three numbers Sort nothing 5 Find their minimum Min int 6 Find their maximum Max int 7 Find their average Average double Dr. Soha S. Zaghloul 18

8. self-check exercise (2) Write a modular program that calculates and prints the bill for Riyadh’s power consumption. The rates vary depending on whether the user is residential, commercial, or industrial. A code of R corresponds to a Residential, C corresponds to a Commercial, and I to Industrial. Any other code should be treated as an error. The program should read the power consumption rate in KWH (Kilowatt per Hour); then it calculates the due amount according to the following: The rate is SAR 5 per KWH for Residential, SAR 10 per KWH for Commercial and SAR 20 per KWH for Industrial. The input data should be made in the main function. The calculation of the due amount is made in a function called DueAmount. The total of the amounts due should also be calculated. Dr. Soha S. Zaghloul 19

9. built-in functions C performs mathematical operations through mathematical libraries; namely, <stdlib.h> and <math.h>. These are listed below: Function Library Purpose Argument(s) Result abs(x) <stdlib.h> Returns the absolute value of its integer argument. Example: x = -5, abs(x) = 5 int fabs(x) <math.h> Returns the absolute value of its double argument. Example: x= -5.2, fabs(x) = 5.2 double ceil(x) Returns the smallest integral value that is NOT less than x. Ex: x= 45.23, ceil(x)= 46.0 floor(x) Returns the largest integral value that is NOT greater than x. Ex.: x=45.23, floor(x)= 45.0 sqrt(x) Returns the non-negative square root of x for x >= 0.0. Ex.: x=25.0, sqrt(x)= 5.0 pow(x,y) Return xy. Ex.: x= 2.0, y=3.0; pow(x,y)=8.0 double, double Dr. Soha S. Zaghloul 20

9. built-in functions (cont’d) Library Purpose Argument(s) Result exp(x) <math.h> Returns ex. double log(x) Returns the natural logarithm of x for x > 0.0 log10(x) Returns the base 10 logarithm. Ex.: x= 100.0, log10(x) = 2.0 cos(x) Returns the cosine of angle x. Ex.: x=0.0, cos(x) = 1.0 (in radians) sin(x) Returns the sine of angle x. Ex.: x=1.5708, sin(x)=1.0 tan(x) Returns the tangent of angle x. Ex.: x=0.0, tan(x)=0.0 Dr. Soha S. Zaghloul 21

10. built-in functions – example (1) Using the C built-in functions, to compute the roots of a quadratic equation in x of the form: ax2 + bx + c = 0. The two roots are defined as: root1 = −𝑏+ 𝑏2−4𝑎𝑐 2𝑎 root2 = −𝑏− 𝑏2−4𝑎𝑐 2𝑎 disc = pow(b, 2.0) – 4.0 * a * c; root1 = (-b + sqrt(disc)) / (2.0 * a); root2 = (-b - sqrt(disc)) / (2.0 * a); Dr. Soha S. Zaghloul 22

11. built-in functions – example (2) Write a complete program that computes the length of a side of a triangle using the following formula: 𝑎2=𝑏2+𝑐2−2𝑏𝑐 𝑐𝑜𝑠∝ The lengths of the sides b and c are known. ∝is given in degrees. To use the cos function of the C library, we must first convert the degrees into radians as follows: Radians = ∝ 𝜋 180 #include <stdlib.h> #include <math.h> #define PI 3.14 Int main (void) { double a, b, c, a2, degrees, radians; printf (“Enter the length of side b”); scanf(“%f”, &b); printf (“Enter the length of side c”); scanf(“%f”, &c); radians = degrees * PI / 180.0; a2 = pow(b, 2.0) + pow(c, 2.0) – 2 * b * c * cos(radians); a = sqrt(a2); printf (“The length of the third side a= %f”, a); } //end main Dr. Soha S. Zaghloul 23

12. self-check exercises (1) Write the following mathematical expressions using C functions: Area =𝜋 𝑟 2 𝑌= 𝑥+𝑎 𝑛 X = 2 sin 1 2 𝛼+𝛽 cos 1 2 𝛼−𝛽 𝑍=𝑙𝑜𝑔𝑒 (𝑥𝑦) 𝑑𝑖𝑠𝑡𝑎𝑛𝑐𝑒= 𝑥1 −𝑥2 2+ 𝑦1 −𝑦2 2 Dr. Soha S. Zaghloul 24

13. self-check exercises (2) Evaluate the following expressions: floor (15.8) floor (15.8 + 0.5) ceil (-7.2) * pow(4.0, 2.0) sqrt (floor (fabs (-16.8))) log10 (1000.0) Dr. Soha S. Zaghloul 25