CPCS 202 LAB 4 Enum Char Functions Math
CPCS 202 - LAB 4 Enum , Char Functions& Math Library Functions I. Mona Alshehri
Character functions toupper function: Header file: ctype. h Syntax: toupper(ch) Where ch is a character literal or variable Job: translates character • into upper case check other function tolower from Help
Character functions toascii function: Header file: ctype. h Syntax: toascii(ch) Where ch is a character literal or variable Job: • translates character to ascii format • to see ascii code, define integer variable
Character functions isdigit function: Header file: ctype. h Syntax: isdigit(ch) Where ch is a character literal or variable Job: returns nonzero if c is a digit. Check other function isalpha, isupper, islower from Help Example: cout <<isdigit(‘F’)<<endl << isdigit(‘ 8’); // print 0 // print any nonzero number
Enumeration Data Type: Syntax: enum model_name { value 1, value 2, value 3, . . } ; Example: enum colors {black, blue, green, cyan, red, purple, yellow, white}; colors mycolor; mycolor = blue; • In fact our enumerated data type is compiled as an integer and its possible values are any type of integer constant specified. If it is not specified, the integer value equivalent to the first possible value is 0 and the following ones follow a +1 progression. Thus, in our data type colors that we defined before, black would be equivalent to 0, blue would be equivalent to 1, green to 2 and so on.
Math Library Functions : Header file is: # include <math. h> sqrt(n) abs(n) pow(b, n) n n b^n
Math Library Functions : Syntax: function_name (argument); Data types of arguments and returned value: Function sqrt(n) Arguments + number Return value + number ± integer number + integer number Ex: sqrt(16) 4 abs(n) Ex: abs(-6) 6 pow(b, n) Ex: pow(3, 2) 9 b: ± number n: ± integer number ± number
Math Library Functions : Syntax: function_name (argument); Arguments can be variables or numbers. Example 1: int x= 4; cout<<sqrt(x); Example 2: int y; y = pow(2, 3); cout<<y; Example 3: int x, y; x = -3; y = 6; cout<<abs(x); cout<<abs(y); 2 8 3 6
Math Library Functions : We can use nested functions for example: sqrt ( pow ( abs (-4), 3) ) sqrt ( pow ( 4 , 3) ) sqrt ( 64) =8
Math Library Functions : #include <iostream. h> #include<conio. h> #include <math. h> // needed for the pow function void main() { int x; cout<<"Enter a number : "; cin>>x; cout<<endl<<x<<"t"<<pow(x, 2)<<"t"<<pow(x, 3) getch(); } Or { int x, y, z; cout<<"Enter a number : "; cin>>x; y= pow(x, 2) ; z= pow(x, 3) ; cout<<endl<<x<<"t"<<y<<"t"<<z; }
Example: Calculate and display the area of a circle and the circumference. Start Input radius Area of circle = 3. 14 * r 2 Circumference = 3. 14 * 2 * r Area = 3. 14 * r 2 Circumference = 3. 14 * 2 * r output where r is the radius Area, Circumference End
- Slides: 11