Download presentation
Presentation is loading. Please wait.
1
FUNCTIONS EXAMPLES
2
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 == ) break; grade = GetGrade (score); printf (“Grade = %c”, grade); } while (score != ); } // end main Dr. Soha S. Zaghloul 2
3
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
4
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 == ) break; grade = GetGrade (score); if (grade != ‘X’) printf (“Grade = %c”, grade); else printf (“Invalid Input”); } while (score != ); } // end main Dr. Soha S. Zaghloul 4
5
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 == ) break; grade = GetGrade (score); if (grade != ‘X’) printf (“Grade = %c”, grade); else printf (“Invalid Input”); } while (score != ); } // 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
6
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
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
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
15
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
16
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
17
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
18
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
19
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
20
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
21
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
22
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
23
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
24
12. self-check exercises (1)
Write the following mathematical expressions using C functions: Area =𝜋 𝑟 2 𝑌= 𝑥+𝑎 𝑛 X = 2 sin 𝛼+𝛽 cos 𝛼−𝛽 𝑍=𝑙𝑜𝑔𝑒 (𝑥𝑦) 𝑑𝑖𝑠𝑡𝑎𝑛𝑐𝑒= 𝑥1 −𝑥2 2+ 𝑦1 −𝑦2 2 Dr. Soha S. Zaghloul 24
25
13. self-check exercises (2)
Evaluate the following expressions: floor (15.8) floor ( ) ceil (-7.2) * pow(4.0, 2.0) sqrt (floor (fabs (-16.8))) log10 (1000.0) Dr. Soha S. Zaghloul 25
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.