Person 1 (Apriyanti, Mirna) Translate to Indonesia & presentation. Start Next Week Personal Number 1 & 2 & 3
|
|
- Harold Herbert Nichols
- 6 years ago
- Views:
Transcription
1 Person 1 (Apriyanti, Mirna) Translate to Indonesia & presentation Start Next Week Personal Number 1 & 2 & 3 1
2 Chapter 6 Functions 2
3 6.1 Focus on Software Engineering: Breaking Up Your Programs Programs may be broken up into many manageable functions. 3
4 6.2 Defining and Calling Functions A function call is a statement that causes a function to execute. A function definition contains the statements that make up the function. The line in the definition that reads void main(void) is called the function header. 4
5 Figure 6-1 Return Type Name Parameter List (This one is empty) Body void main(void) cout << Hello World\n ; 5
6 Calling a Function Function Header void displaymessage() Function Call displaymessage(); 6
7 Program 6-1 #include <iostream.h> //****************************************** // Definition of function displaymessage. * // This function displays a greeting. * //****************************************** void displaymessage() cout << "Hello from the function displaymessage.\n"; void main(void) cout << "Hello from main.\n"; displaymessage(); cout << "Back in function main again.\n"; 7
8 Program Output Hello from main. Hello from the function displaymessage. Back in function main again. 8
9 Figure 6-2 void displaymessage() cout << Hello from the function displaymessage.\n ; void main(void) cout << Hello from main.\n ; displaymessage(); cout << Back in function main again.\n ; 9
10 Program 6-2 //The function displaymessage is repeatedly called from a loop #include <iostream.h> //****************************************** // Definition of function displaymessage. * // This function displays a greeting. * //****************************************** void displaymessage() cout << "Hello from the function displaymessage.\n"; void main(void) cout << "Hello from main.\n"; for (int count = 0; count < 5; count++) displaymessage(); // Call displaymessage cout << "Back in function main again.\n"; 10
11 Program Output Hello from main. Hello from the function displaymessage. Hello from the function displaymessage. Hello from the function displaymessage. Hello from the function displaymessage. Hello from the function displaymessage. Back in function main again. 11
12 Program 6-3 // This program has three functions: main, first, and second. #include <iostream.h> //************************************* // Definition of function first. * // This function displays a message. * //************************************* void first(void) cout << "I am now inside the function first.\n"; 12
13 Program continues //************************************* // Definition of function second. * // This function displays a message. * //************************************* void second(void) cout << "I am now inside the function second.\n"; void main(void) cout << "I am starting in function main.\n"; first(); // Call function first second(); // Call function second cout << "Back in function main again.\n"; 13
14 Program Output I am starting in function main. I am now inside the function first. I am now inside the function second. Back in function main again. 14
15 Figure 6-3 void first(void) cout << I am now inside function first.\n ; void second(void) cout << I am now inside function second.\n ; void main(void) cout << I am starting in function main.\n ; first(); second(); cout << Back in function main again.\n 15
16 Person 2 (Ricet, Riyana) 16
17 Program 6-4 // This program has three functions: main, deep, and deeper #include <iostream.h> //************************************** // Definition of function deeper. * // This function displays a message. * //************************************** void deeper(void) cout << "I am now inside the function deeper.\n"; 17
18 Program continues //************************************** // Definition of function deep. * // This function displays a message. * //************************************** void deep() cout << "I am now inside the function deep.\n"; deeper(); // Call function deeper cout << "Now I am back in deep.\n"; void main(void) cout << "I am starting in function main.\n"; deep(); // Call function deep cout << "Back in function main again.\n"; 18
19 Program Output I am starting in function main. I am now inside the function deep. I am now inside the function deeper. Now I am back in deep. Back in function main again. 19
20 Figure 6-4 void deep(void) cout << I am now inside function deep.\n ; deeper(); cout << Now I am back in deep.\n ; void deeper(void) cout << I am now inside function deeper.\n ; void main(void) cout << I am starting in function main.\n ; deep(); cout << Back in function main again.\n 20
21 Person 3 (Krisnawati, Adelia) 21
22 6.3 Function Prototypes A function prototype eliminates the need to place a function definition before all calls to the function. Here is a prototype for the displaymessage function in Program 6-1 void displaymessage(void); 22
23 Program 6-5 // This program has three functions: main, first, and second. #include <iostream.h> // Function Prototypes void first(void); void second(void); void main(void) cout << "I am starting in function main.\n"; first(); // Call function first second(); // Call function second cout << Back in function main again.\n"; Program Continues on next slide 23
24 Program 6-5 Continues // Definition of function first. // This function displays a message. void first(void) cout << I am now inside the function first.\n ; // Definition of function second // This function displays a message. void second(void) cout << I am now inside the function second.\n ; 24
25 Program 6-5 Output I am starting in function main. I am now inside the function first. I am now inside the function second. Back in function main again. 25
26 Person 4 (Yafet, Rian Kalensun) 26
27 6.4 Sending Information Into a Function When a function is called, the program may send values (arguments) into the function. Arguments are passed into parameters. void displayvalue(int num) cout << The value is << num << endl; 27
28 Program 6-6 // This program demonstrates a function with a parameter. #include <iostream.h> // Function Prototype void displayvalue(int) void main(void) cout << "I am passing 5 to displayvalue.\n"; displayvalue(5); //Call displayvalue with argument 5 cout << "Now I am back in main.\n"; Program Continues to next slide 28
29 Program 6-6 //********************************************* // Definition of function displayvalue. * // It uses an integer parameter whose value is displayed. * //********************************************* void displayvalue(int num) cout << The value is << num << endl; 29
30 Program Output I am passing 5 to displayvalue. The value is 5 Now I am back in main. 30
31 Figure 6-5 displayvalue(5); void displayvalue(int num) cout << The value is << num << endl; 31
32 Program 6-7 // This program demonstrates a function with a parameter. #include <iostream.h> // Function Prototype void displayvalue(int); void main(void) cout << "I am passing several values to displayvalue.\n"; displayvalue(5); // Call displayvalue with argument 5 displayvalue(10); // Call displayvalue with argument 10 displayvalue(2); // Call displayvalue with argument 2 displayvalue(16); // Call displayvalue with argument 16 cout << "Now I am back in main.\n"; Program continues on next slide 32
33 Program 6-7 Continued //********************************************************* // Definition of function displayvalue. * // It uses an integer parameter whose value is displayed. * //********************************************************* void displayvalue(int num) cout << "The value is " << num << endl; 33
34 Program Output I am passing several values to displayvalue. The value is 5 The value is 10 The value is 2 The value is 16 Now I am back in main. 34
35 Program 6-8 // This program demonstrates a function with three parameters. #include <iostream.h> // Function prototype void showsum(int, int, int); void main(void) int value1, value2, value3; cout << "Enter three integers and I will display "; cout << "their sum: "; cin >> value1 >> value2 >> value3; showsum(value1, value2, value3); // Call showsum with // 3 arguments 35
36 Program continues //************************************************************ // Definition of function showsum. * // It uses three integer parameters. Their sum is displayed. * //************************************************************ void showsum(int num1, int num2, int num3) cout << (num1 + num2 + num3) << endl; 36
37 Program Output with Example Input Enter three integers and I will display their sum: [Enter] 19 37
38 Figure 6-6 showsum(value1, value2, value3); void showsum(int num1, int num2, int num3) cout << num1 + num2 + num3 << endl; 38
39 Person 5 (Juli, Deasry) 39
40 6.5 Changing the value of a Parameter When an argument is passed into a parameter, only a copy of the argument s value is passed. Changes to the parameter do not affect the original argument. This is called passed by value. 40
41 Program 6-9 // This program demonstrates that changes to a function parameter // have no effect on the original argument. #include <iostream.h> // Function Prototype void changethem(int, float); void main(void) int whole = 12; float real = 3.5; cout << "In main the value of whole is " << whole << endl; cout << "and the value of real is " << real << endl; changethem(whole, real); // Call changethem with 2 arguments cout << "Now back in main again, the value of "; cout << "whole is " << whole << endl; cout << "and the value of real is " << real << endl; 41
42 Program continues //************************************************************** // Definition of function changethem. * // It uses i, an int parameter, and f, a float. The values of * // i and f are changed and then displayed. * //************************************************************** void changethem(int i, float f) i = 100; f = 27.5; cout << "In changethem the value of i is changed to "; cout << i << endl; cout << "and the value of f is changed to " << f << endl; 42
43 Program Output In main the value of whole is 12 and the value of real is 3.5 In changethem the value of i is changed to 100 and the value of f is changed to 27.5 Now back in main again, the value of whole is 12 and the value of real is
44 Figure
45 Person 6 (Stevany Wuaten, Sinska) 45
46 6.6 Focus on Software Engineering: Using Functions in a Menu-Driven Program Functions are ideal for use in menu-driven programs. When the user selects an item from a menu, the program can call the appropriate function. 46
47 Program 6-10 // This is a menu-driven program that makes a function call // for each selection the user makes. #include <iostream.h> // Function Prototypes void adult(int); void child(int); void senior(int); void main(void) int choice, months; 47
48 Program continues cout.setf(ios::fixed ios::showpoint); cout.precision(2); do cout << "\n\t\thealth Club Membership Menu\n\n"; cout << "1. Standard adult Membership\n"; cout << "2. child Membership\n"; cout << "3. senior Citizen Membership\n"; cout << "4. Quit the Program\n\n"; cout << "Enter your choice: "; cin >> choice; 48
49 Program continues if (choice!= 4) cout << "For how many months? "; cin >> months; switch (choice) case 1: adult(months); break; case 2: child(months); break; case 3: senior(months); break; case 4: cout << "Thanks for using this "; cout << "program.\n"; break; 49
50 Program continues default: cout << "The valid choices are 1-4. "; cout << "Try again.\n"; while (choice!= 4); //*********************************************************** // Definition of function adult. Uses an integer parameter, mon. * // mon holds the number of months the membership should be * // calculated for. The cost of an adult membership for that many * // months is displayed. * //****************************************************************** void adult(int mon) cout << "The total charges are $"; cout << (mon * 40.0) << endl; 50
51 Program continues //******************************************************************** // Definition of function child. Uses an integer parameter, mon. * // mon holds the number of months the membership should be * // calculated for. The cost of a child membership for that many * // months is displayed. * //************************************************************* void child(int mon) cout << "The total charges are $"; cout << (mon * 20.0) << endl; 51
52 Program continues //******************************************************************* // Definition of function senior. Uses an integer parameter, mon. * // mon holds the number of months the membership should be * // calculated for. The cost of a senior citizen membership for * // that many months is displayed. * //************************************************************ void senior(int mon) cout << "The total charges are $"; cout << (mon * 30.0) << endl; 52
53 Program Output with Example Input Health Club Membership Menu 1. Standard adult Membership 2. child Membership 3. senior Citizen Membership 4. Quit the Program Enter your choice: 1 For how many months 12 The total charges are $ Health Club Membership Menu 1. Standard adult Membership 2. child Membership 3. senior Citizen Membership 4. Quit the Program Enter your choice: 4 Thanks for using this program. 53
54 Person 7 (Helga, Destyani Maria) 54
55 6.7 The return Statement The return statement causes a function to end immediately. 55
56 Program 6-11 // This program demonstrates a function with a return statement. #include <iostream.h> // Function prototype void halfway(void); void main(void) cout << "In main, calling halfway...\n"; halfway(); cout << "Now back in main.\n"; 56
57 Program continues //********************************************************* // Definition of function halfway. * // This function has a return statement that forces it to * // terminate before the last statement is executed. * //********************************************************* void halfway(void) cout << "In halfway now.\n"; return; cout <<"Will you ever see this message?\n"; 57
58 Program Output In main, calling halfway... In halfway now. Now back in main. 58
59 Program 6-12 // This program uses a function to perform division. If division // by zero is detected, the function returns. #include <iostream.h> // Function prototype. void divide(float, float); void main(void) float num1, num2; cout << "Enter two numbers and I will divide the first\n"; cout << "number by the second number: "; cin >> num1 >> num2; divide(num1, num2); 59
60 Program continues //**************************************************************** // Definition of function divide. * // Uses two parameters: arg1 and arg2. The function divides arg1 * // by arg2 and shows the result. If arg2 is zero, however, the * // function returns. * //**************************************************************** void divide(float arg1, float arg2) if (arg2 == 0.0) cout << "Sorry, I cannot divide by zero.\n"; return; cout << "The quotient is " << (arg1 / arg2) << endl; 60
61 Program Output with Example Input Enter two numbers and I will divide the first number by the second number: 12 0 [Enter] Sorry, I cannot divide by zero. 61
62 Person 8 (Widya, Erni) 62
63 6.8 Returning a value From a Function A function may send a value back to the part of the program that called the function. 63
64 Figure
65 Program 6-13 // This program uses a function that returns a value. #include <iostream.h> //Function prototype int square(int); void main(void) int value, result; cout << "Enter a number and I will square it: "; cin >> value; result = square(value); cout << value << " squared is " << result << endl; 65
66 Program continues //**************************************************** // Definition of function square. * // This function accepts an int argument and returns * // the square of the argument as an int. * //**************************************************** int square(int number) return number * number; 66
67 Program Output with Example Input Enter a number and I will square it: 20 [Enter] 20 squared is
68 Figure 6-11 result = square(value); 20 int square(int number) return number * number; 68
69 Person 9 (Juliano, Kristian) 69
70 6.9 Returning Boolean Values Function may return true or false values. 70
71 Program 6-15 // This program uses a function that returns true or false. #include <iostream.h> // Function prototype bool iseven(int); void main(void) int val; cout << "Enter an integer and I will tell you "; cout << "if it is even or odd: "; cin >> val; if (iseven(val)) cout << val << " is even.\n"; else cout << val << " is odd.\n"; 71
72 Program continues //********************************************************************* // Definition of function iseven. This function accepts an * // integer argument and tests it to be even or odd. The function * // returns true if the argument is even or false if the argument is * // odd. * // The return value is bool. * //********************************************************************* bool iseven(int number) bool status; if (number % 2) status = false; // The number is odd if there's a remainder. else status = true; // Otherwise, the number is even. return status; 72
73 Program Output Enter an integer and I will tell you if it is even or odd: 5 [Enter] 5 is odd. 73
74 Person 10 (Supardi, Yan Makarunggala, Stefanny Tangkuman) 74
75 6.10 Local and Global Variables A local variable is declared inside a function, and is not accessible outside the function. A global variable is declared outside all functions and is accessible in its scope. 75
76 Program 6-16 // This program shows that variables declared in a function // are hidden from other functions. #include <iostream.h> void func(void); // Function prototype void main(void) int num = 1; cout << "In main, num is " << num << endl; func(); cout << "Back in main, num is still " << num << endl; 76
77 Program continues //********************************************************* // Definition of function func. * // It has a local variable, num, whose initial value, 20, * // is displayed. * //********************************************************* void func(void) int num = 20; cout << "In func, num is " << num << endl; 77
78 Program Output In main, num is 1 In func, num is 20 Back in main, num is still 1 78
79 Figure 6-8 Function main num = 1 This num variable is only visible in function main. Function func num = 20 This num variable is only visible in function func. 79
80 Program 6-17 // This program shows that a global variable is visible // to all the functions that appear in a program after // the variable's declaration. #include <iostream.h> void func(void); // Function prototype int num = 2; // Global variable void main(void) cout << "In main, num is " << num << endl; func(); cout << "Back in main, num is " << num << endl; 80
81 Program continues //***************************************************** // Definition of function func. * // func changes the value of the global variable num * //***************************************************** void func(void) cout << "In func, num is " << num << endl; num = 50; cout << "But, it is now changed to " << num << endl; 81
82 Program Output In main, num is 2 In func, num is 2 But, it is now changed to 50 Back in main, num is 50 82
83 Program 6-18 // This program shows that a global variable is visible // to all the functions that appear in a program after // the variable's declaration. #include <iostream.h> void func(void); // Function prototype void main(void) cout << "In main, num is not visible!\n"; func(); cout << "Back in main, num still isn't visible!\n"; 83
84 Program continues int num = 2; // Global variable //***************************************************** // Definition of function func * // func changes the value of the global variable num. * //***************************************************** void func(void) cout << "In func, num is " << num << endl; num = 50; cout << "But, it is now changed to " << num << endl; 84
85 Program Output In main, num is not visible! In func, num is 2 But, it is now changed to 50 Back in main, num still isn't visible! 85
86 Global Variables are Initialized to Zero by Default Unless you explicitly initialize numeric global variables, they are automatically initialized to zero. Global character variables are initialized to NULL, or ASCII code 0. 86
87 Program 6-19 // This program has an uninitialized global variable. #include <iostream.h> int globalnum; // Global variable. Automatically set to zero. void main(void) cout << "globalnum is " << globalnum << endl; 87
88 Program Output globalnum is 0 88
89 Local and Global Variables with the Same Name If a function has a local variable with the same name as a global variable, only the local variable can be seen by the function. 89
90 Program 6-20 // This program shows that when a local variable has the // same name as a global variable, the function only sees // the local variable. #include <iostream.h> // Function prototypes void texas(); void arkansas(); int cows = 10; void main(void) cout << "There are " << cows << " cows in main.\n"; texas(); arkansas(); cout << "Back in main, there are " << cows << " cows.\n"; 90
91 Program continues //****************************************** // Definition of function texas. * // The local variable cows is set to 100. * //****************************************** void texas(void) int cows = 100; cout << "There are " << cows << " cows in texas.\n"; 91
92 Program continues //****************************************** // Definition of function arkansas. * // The local variable cows is set to 50. * //****************************************** void arkansas(void) int cows = 50; cout << "There are " << cows << " cows in arkansas.\n"; 92
93 Program Output There are 10 cows in main. There are 100 cows in texas. There are 50 cows in arkansas. Back in main, there are 10 cows. 93
94 Program 6-21 // This program has local and global variables. In the function // ringupsale, there is a local variable named tax. There is // also a global variable with the same name. #include <iostream.h> void ringupsale(void); // Function prototype // Global Variables const float taxrate = 0.06; float tax, sale, total; void main(void) char again; 94
95 Program continues cout.precision(2); cout.setf(ios::fixed ios::showpoint); do ringupsale(); cout << "Is there another item to be purchased? "; cin >> again; while (again == 'y' again == 'Y'); tax = sale * taxrate; total = sale + tax; cout << "The tax for this sale is " << tax << endl; cout << "The total is " << total << endl; 95
96 Program continues //****************************************************************** // Definition of function ringupsale. * // This function asks for the quantity and unit price of an item. * // It then calculates and displays the sales tax and subtotal * // for those items. * //****************************************************************** void ringupsale(void) int qty; float unitprice, tax, thissale, subtotal; cout << "Quantity: "; cin >> qty; cout << "Unit price: "; cin >> unitprice; thissale = qty * unitprice; // Get the total unit price 96
97 Program continues sale += thissale; // Update global variable sale tax = thissale * taxrate; // Get sales tax for these items subtotal = thissale + tax; // Get subtotal for these items cout << "Price for these items: " << thissale << endl; cout << "tax for these items: " << tax << endl; cout << "subtotal for these items: " << subtotal << endl; 97
98 Program Output with Example Input Quantity: 2 [Enter] Unit Price: [Enter] Price for these items: tax for these items: 2.40 subtotal for these items: Is there another item to be purchased? y [Enter] Quantity: 3 [Enter] Unit Price: [Enter] Price for these items: tax for these items: 2.16 subtotal for these items: Is there another item to be purchased? n [Enter] The tax for this sale is 4.56 The total is
99 Be Careful With Global Variables It is tempting to make all your variables global. But don t do it! Using global variables can cause problems. It is harder to debug a program that uses global variables 99
100 Person 11 (Niksen, Hermawan) 100
101 6.11 Static Local Variables If a function is called more than once in a program, the values stored in the function s local variables do not persist between function calls. To get a variable to keep it s value even after the function ends, you must create static variables 101
102 Program 6-22 // This program shows that local variables do not retain // their values between function calls. #include <iostream.h> // Function prototype void showlocal(void); void main(void) showlocal(); showlocal(); 102
103 Program continues //*********************************************************** // Definition of function showlocal. * // The initial value of localnum, which is 5, is displayed. * // The value of localnum is then changed to 99 before the * // function returns. * //*********************************************************** void showlocal(void) int localnum = 5; // Local variable cout << "localnum is " << localnum << endl; localnum = 99; 103
104 Program Output localnum is 5 localnum is 5 104
105 Program 6-23 //This program uses a static local variable. #include <iostream.h> void showstatic(void); // Function prototype void main(void) for (int count = 0; count < 5; count++) showstatic(); //************************************************************* // Definition of function showstatic. * // statnum is a static local variable. Its value is displayed * // and then incremented just before the function returns. * //************************************************************* void showstatic(void) static int statnum; cout << "statnum is " << statnum << endl; statnum++; 105
106 Program Output statnum is 0 statnum is 1 statnum is 2 statnum is 3 statnum is 4 106
107 Program 6-24 // This program shows that a static local variable is only // initialized once. #include <iostream.h> void showstatic(void); // Function prototype void main(void) for (int count = 0; count < 5; count++) showstatic(); 107
108 Program continues //*********************************************************** // Definition of function showstatic. * // statnum is a static local variable. Its value is displayed // and then incremented just before the function returns. * //*********************************************************** void showstatic() static int statnum = 5; cout << "statnum is " << statnum << endl; statnum++; 108
109 Program Output statnum is 5 statnum is 6 statnum is 7 statnum is 8 statnum is 9 109
110 Person 12 (Korinus, Eka P. Paputungan) 110
111 6.12 Default Arguments Default arguments are passed to parameters automatically if no argument is provided in the function call. A function s default arguments should be assigned in the earliest occurrence of the function name. This will usually mean the function prototype. 111
112 Program 6-25 // This program demonstrates default function arguments. #include <iostream.h> // Function prototype with default arguments void displaystars(int = 10, int = 1); void main(void) displaystars(); cout << endl; displaystars(5); cout << endl; displaystars(7, 3); 112
113 Program continues //************************************************************** // Definition of function displaystars. * // The default argument for cols is 10 and for rows is 1. * // This function displays a rectangle made of asterisks. * //************************************************************** void displaystars(int cols, int rows) // Nested loop. The outer loop controls the rows // and the inner loop controls the columns. for (int down = 0; down < rows; down++) for (int across = 0; across < cols; across++) cout << "*"; cout << endl; 113
114 Program Output ********** ***** ******* ******* ******* 114
115 Default Argument Summary The value of a default argument must be a constant (either a literal value of a named constant). When an argument is left out of a function call (because it has a default value), all the arguments that come after it must be left out too. When a function has a mixture of parameters both with and without default arguments, the parameters with default arguments must be declared last. 115
116 Person 13 (Yuyun, Ukasiah) 116
117 6.13 Using Reference Variables as Parameters When used as parameters, reference variables allow a function to access the parameter s original argument, changes to the parameter are also made to the argument. 117
118 Example: void doublenum(int &refvar) refvar *= 2; // The variable refvar is called // a reference to an int 118
119 Program 6-26 // This program uses a reference variable as a function // parameter. #include <iostream.h> // Function prototype. The parameter is a reference variable. void doublenum(int &); void main(void) int value = 4; cout << "In main, value is " << value << endl; cout << "Now calling doublenum..." << endl; doublenum(value); cout << "Now back in main. value is " << value << endl; 119
120 Program continues //************************************************************ // Definition of doublenum. * // The parameter refvar is a reference variable. The value * // in refvar is doubled. * //************************************************************ void doublenum (int &refvar) refvar *= 2; 120
121 Program Output In main, value is 4 Now calling doublenum... Now back in main. value is 8 121
122 Program 6-27 // This program uses reference variables as function // parameters. #include <iostream.h> // Function prototypes. Both functions use reference variables // as parameters void doublenum(int &); void getnum(int &); void main(void) int value; getnum(value); doublenum(value); cout << "That value doubled is " << value << endl; 122
123 Program continues //************************************************************* // Definition of getnum. * // The parameter usernum is a reference variable. The user is * // asked to enter a number, which is stored in usernum. * //************************************************************* void getnum(int &usernum) cout << "Enter a number: "; cin >> usernum; 123
124 Program continues //************************************************************ // Definition of doublenum. * // The parameter refvar is a reference variable. The value * // in refvar is doubled. * //************************************************************ void doublenum (int &refvar) refvar *= 2; 124
125 Program Output with Example Input Enter a number: 12 [Enter] That value doubled is
126 Reference Argument Warning Don t get carried away with using reference variables as function parameters. Any time you allow a function to alter a variable that s outside the function, you are creating potential debugging problems. Reference variables should only be used as parameters when the situation demands them. 126
127 Person 14 (Serly, Denny) 127
128 6.14 Overloaded Functions Two or more functions may have the same name as long as their parameter lists are different. 128
129 Program 6-28 #include <iostream.h> // Function prototypes int square(int); float square(float); void main(void) int userint; float userfloat; cout.precision(2); cout << "Enter an integer and a floating-point value: "; cin >> userint >> userfloat; cout << "Here are their squares: "; cout << square(userint) << " and " << square(userfloat); 129
130 Program continues // Definition of overloaded function square. // This function uses an int parameter, number. It returns the // square of number as an int. int square(int number) return number * number; // Definition of overloaded function square. // This function uses a float parameter, number. It returns the // square of number as a float. float square(float number) return number * number; 130
131 Program Output with Example Input Enter an integer and floating-point value: [Enter] Here are their squares: 144 and
132 Program 6-29 // This program demonstrates overloaded functions to calculate // the gross weekly pay of hourly-paid or salaried employees. #include <iostream.h> // Function prototypes void getchoice(char &); float calcweeklypay(int, float); float calcweeklypay(float); void main(void) char selection; int worked; float rate, yearly; cout.precision(2); cout.setf(ios::fixed ios::showpoint); cout << Do you want to calculate the weekly pay of\n"; cout << (H) an hourly-paid employee, or \n ; cout << (S) a salaried employee?\n ; 132
133 Program continues getchoice(selection); switch (selection) case H : case h : cout << How many hours were worked? ; cin >> worked; cout << What is the hour pay rate? ; cin >> rate; cout << The gross weekly pay is ; cout << calcweeklypay(worked, rate); break; case S : case s : cout << What is the annual salary? ; cin >> yearly; cout << The gross weekly pay is ; cout << calcweeklypay(yearly); break; 133
134 Program continues //*********************************************************** // Definition of function getchoice. * // The parameter letter is a reference to a char. * // This function asks the user for an H or an S and returns * // the validated input. * //*********************************************************** void getchoice(char &letter) do cout << Enter your choice (H or S): ; cin >> letter; while (letter!= H && letter!= h && letter!= S && letter!= s ); 134
135 Program continues //*********************************************************** // Definition of overloaded function calcweeklypay. * // This function calculates the gross weekly pay of * // an hourly-paid employee. The parameter hours hold the * // hourly pay rate. The function returns the weekly salary. * //*********************************************************** void calcweekly(int hours, float payrate) return hours * payrate; 135
136 Program continues //*********************************************************** // Definition of overloaded function calcweeklypay. * // This function calculates the gross weekly pay of * // a salaried employee. The parameter holds the employee s * // annual salary. The function returns the weekly salary. * //*********************************************************** void calcweekly(float annsalary) return annsalary / 52.0; 136
137 Program Output with Example Input Do you want to calculate the weekly pay of (H) an houly-paid employee, or (S) a salaried employee? H[Enter] How many hours were worked? 40[Enter] What is the hour pay rate? 18.50[Enter] The gross weekly pay is Program Output with Other Example Input Do you want to calculate the weekly pay of (H) an houly-paid employee, or (S) a salaried employee? S[Enter] What is the annual salary? [Enter] The gross weekly pay is
138 Person 15 (Relvando, Gladis Ansiga) 138
139 6.15 The exit() Function The exit() function causes a program to terminate, regardless of which function or control mechanism is executing. 139
140 Program 6-30 // This program shows how the exit function causes a program // to stop executing. #include <iostream.h> #include <stdlib.h> // For exit void function(void); // Function prototype void main(void) function(); 140
141 Program continues //*********************************************************** // This function simply demonstrates that exit can be used * // to terminate a program from a function other than main. * //*********************************************************** void function(void) cout << "This program terminates with the exit function.\n"; cout << "Bye!\n"; exit(0); cout << "This message will never be displayed\n"; cout << "because the program has already terminated.\n"; 141
142 Program Output This program terminates with the exit function. Bye! 142
143 Program 6-31 // This program demonstrates the exit function. #include <iostream.h> #include <stdlib.h> // For exit void main(void) char response; cout << "This program terminates with the exit function.\n"; cout << "Enter S to terminate with the EXIT_SUCCESS code\n"; cout << "or f to terminate with the EXIT_FAILURE code: "; cin >> response; 143
144 Program continues if (response == 'S') cout << "Exiting with EXIT_SUCCESS.\n"; exit(exit_success); else cout << "Exiting with EXIT_FAILURE.\n"; exit(exit_failure); 144
145 Program Output with Example Input This program terminates with the exit function. Enter S to terminate with the EXIT_SUCCESS code or f to terminate with the EXIT_FAILURE code: s [Enter] Exiting with EXIT_SUCCESS. Program Output With Other Example Input This program terminates with the exit function. Enter S to terminate with the EXIT_SUCCESS code or f to terminate with the EXIT_FAILURE code: f [Enter] Exiting with EXIT_FAILURE. 145
146 Person 16 (Johra, Andika) 146
147 6.16 Stubs and Drivers Stubs and drivers are very helpful tools for testing and debugging programs that use functions. A stub is a dummy function that is called instead of the actual function it represents. A driver is a program that tests a function by simply calling it. 147
148 // Stub for the adult function. void adult(int months) cout << "The function adult was called with " << months; cout << " as its argument.\n"; // Stub for the child function. void child(int months) cout << "The function child was called with " << months; cout << " as its argument.\n"; // Stub for the senior function. void senior(int months) cout << "The function senior was called with " << months; cout << " as its argument.\n"; 148
149 Person 17 (Kevin, Jonathan Tompodung, Abdulharis) 149
150 Functions and subprograms The Top-down design appeoach is based on dividing the main problem into smaller tasks which may be divided into simpler tasks, then implementing each simple task by a subprogram or a function A C++ function or a subprogram is simply a chunk of C++ code that has 150 A descriptive function name, e.g. computetaxes to compute the taxes for an employee isprime to check whether or not a number is a prime number A returning value The computetaxes function may return with a double number representing the amount of taxes The isprime function may return with a Boolean value (true or false)
151 C++ Standard Functions C++ language is shipped with a lot of functions which are known as standard functions These standard functions are groups in different libraries which can be included in the C++ program, e.g. Math functions are declared in <math.h> library Character-manipulation functions are declared in <ctype.h> library C++ is shipped with more than 100 standard libraries, some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeint.h> 151
152 Example of Using Standard C++ Math Functions #include <iostream.h> #include <math.h> void main() // Getting a double value double x; cout << "Please enter a real number: "; cin >> x; // Compute the ceiling and the floor of the real number cout << "The ceil(" << x << ") = " << ceil(x) << endl; cout << "The floor(" << x << ") = " << floor(x) << endl; 152
153 Example of Using Standard C++ Character Functions #include <iostream.h> // input/output handling #include <ctype.h> // character type functions void main() Explicit casting char ch; cout << "Enter a character: "; cin >> ch; cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl; cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl; if (isdigit(ch)) cout << "'" << ch <<"' is a digit!\n"; else cout << "'" << ch <<"' is NOT a digit!\n"; 153
154 User-Defined C++ Functions Although C++ is shipped with a lot of standard functions, these functions are not enough for all users, therefore, C++ provides its users with a way to define their own functions (or user-defined function) For example, the <math.h> library does not include a standard function that allows users to round a real number to the i th digits, therefore, we must declare and implement this function ourselves 154
155 How to define a C++ Function? Generally speaking, we define a C++ function in two steps (preferably but not mandatory) 155 Step #1 declare the function signature in either a header file (.h file) or before the main function of the program Step #2 Implement the function in either an implementation file (.cpp) or after the main function
156 What is The Syntactic Structure of a C++ Function? A C++ function consists of two parts The function header, and The function body The function header has the following syntax <return value> <name> (<parameter list>) The function body is simply a C++ code 156 enclosed between
157 Example of User-defined C++ Function double computetax(double income) if (income < ) return 0.0; double taxes = 0.07 * (income ); return taxes; 157
158 Example of User-defined C++ Function Function header double computetax(double income) if (income < ) return 0.0; double taxes = 0.07 * (income ); return taxes; 158
159 Example of User-defined C++ Function Function header Function body double computetax(double income) if (income < ) return 0.0; double taxes = 0.07 * (income ); return taxes; 159
160 Function Signature The function signature is actually similar to the function header except in two aspects: The parameters names may not be specified in the function signature The function signature must be ended by a semicolon Example Unnamed Parameter Semicolon ; 160 double computetaxes(double) ;
161 Why Do We Need Function Signature? For Information Hiding If you want to create your own library and share it with your customers without letting them know the implementation details, you should declare all the function signatures in a header (.h) file and distribute the binary code of the implementation file For Function Abstraction By only sharing the function signatures, we have the liberty to change the implementation details from time to time to Improve function performance make the customers focus on the purpose of the function, not its implementation 161
162 Example #include <iostream> #include <string> using namespace std; // Function Signature double getincome(string); double computetaxes(double); void printtaxes(double); void main() // Get the income; double income = getincome("please enter the employee income: "); // Compute Taxes double taxes = computetaxes(income); // Print employee taxes printtaxes(taxes); 162 double computetaxes(double income) if (income<5000) return 0.0; return 0.07*(income ); double getincome(string prompt) cout << prompt; double income; cin >> income; return income; void printtaxes(double taxes) cout << "The taxes is $" << taxes << endl;
163 Person 18 (Andrew, Desy Kaseger) 163
164 Building Your Libraries It is a good practice to build libraries to be used by you and your customers In order to build C++ libraries, you should be familiar with How to create header files to store function signatures How to create implementation files to store function implementations How to include the header file to your program to use your user-defined functions 164
165 C++ Header Files The C++ header files must have.h extension and should have the following structure #ifndef compiler directive #define compiler directive May include some other header files All functions signatures with some comments about their purposes, their inputs, and outputs #endif compiler directive 165
166 TaxesRules Header file #ifndef _TAXES_RULES_ #define _TAXES_RULES_ #include <iostream> #include <string> using namespace std; double getincome(string); // purpose -- to get the employee income // input -- a string prompt to be displayed to the user // output -- a double value representing the income double computetaxes(double); // purpose -- to compute the taxes for a given income // input -- a double value representing the income // output -- a double value representing the taxes void printtaxes(double); // purpose -- to display taxes to the user // input -- a double value representing the taxes // output -- None #endif 166
167 TaxesRules Implementation File #include "TaxesRules.h" double computetaxes(double income) if (income<5000) return 0.0; return 0.07*(income ); double getincome(string prompt) cout << prompt; double income; cin >> income; return income; 167 void printtaxes(double taxes) cout << "The taxes is $" << taxes << endl;
168 Main Program File #include "TaxesRules.h" void main() // Get the income; double income = getincome("please enter the employee income: "); // Compute Taxes double taxes = computetaxes(income); 168 // Print employee taxes printtaxes(taxes);
169 Inline Functions Sometimes, we use the keyword inline to define user-defined functions 169 Inline functions are very small functions, generally, one or two lines of code Inline functions are very fast functions compared to the functions declared without the inline keyword Example inline inline double degrees( double radian) return radian * / ;
170 Example #1 Write a function to test if a number is an odd number inline bool odd (int x) return (x % 2 == 1); 170
171 Example #2 Write a function to compute the distance between two points (x1, y1) and (x2, y2) Inline double distance (double x1, double y1, double x2, double y2) return sqrt(pow(x1-x2,2)+pow(y1-y2,2)); 171
172 Example #3 Write a function to compute n! 172 int factorial( int n) int product=1; for (int i=1; i<=n; i++) product *= i; return product;
173 173 Example #4 Function Overloading Write functions to return with the maximum number of two numbers An overloaded function is a inline int max( int x, int y) function that is defined more if (x>y) return x; else return y; than once with different data types or inline double max( double x, double y) different number of if (x>y) return x; else return y; parameters
174 Person 19 (Arley, Arthur Toliu) 174
175 Sharing Data Among User-Defined Functions There are two ways to share data among different functions Using global variables (very bad practice!) Passing data through function parameters Value parameters Reference parameters Constant reference parameters 175
176 C++ Variables A variable is a place in memory that has A name or identifier (e.g. income, taxes, etc.) 176 A data type (e.g. int, double, char, etc.) A size (number of bytes) A scope (the part of the program code that can use it) Global variables all functions can see it and using it Local variables only the function that declare local variables see and use these variables A life time (the duration of its existence) Global variables can live as long as the program is executed Local variables are lived only when the functions that define these variables are executed
177 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; 177
178 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; 178 x 0
179 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; x 0 void main() f2(); cout << x << endl ;
180 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; x 04 void f2() x += 4; f1(); void main() f2(); cout << x << endl ;
181 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; 181 x void f1() x++; void f2() x += 4; f1(); void main() f2(); cout << x << endl ;
182 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; 182 x void f1() x++; void f2() x += 4; f1(); void main() f2(); cout << x << endl;
183 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; x 6 45 void f2() x += 4; f1(); void main() f2(); cout << x << endl;
184 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; x 7 45 void main() f2(); cout << x << endl; 184
185 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; x 8 45 void main() f2(); cout << x << endl; 185
186 I. Using Global Variables #include <iostream.h> int x = 0; void f1() x++; void f2() x+=4; f1(); void main() f2(); cout << x << endl; 186
187 What Happens When We Use Inline #include <iostream.h> int x = 0; Inline void f1() x++; Keyword? Inline void f2() x+=4; f1(); void main() f2(); cout << x << endl; 187
188 What Happens When We Use Inline #include <iostream.h> int x = 0; Inline void f1() x++; Keyword? Inline void f2() x+=4; f1(); void main() f2(); cout << x << endl; 1 x 0 The inline keyword instructs the compiler to replace the function call with the function body! void main() x+=4; x++; cout << x << endl; 188
189 What Happens When We Use Inline #include <iostream.h> int x = 0; Inline void f1() x++; Keyword? Inline void f2() x+=4; f1(); void main() f2(); cout << x << endl; 2 x 4 void main() x+=4; x++; cout << x << endl; 189
190 What Happens When We Use Inline #include <iostream.h> int x = 0; Inline void f1() x++; Keyword? Inline void f2() x+=4; f1(); void main() f2(); cout << x << endl; 3 x 5 void main() x+=4; x++; cout << x << endl; 190
191 What Happens When We Use Inline #include <iostream.h> int x = 0; Inline void f1() x++; Keyword? Inline void f2() x+=4; f1(); void main() f2(); cout << x << endl; 4 x 5 void main() x+=4; x++; cout << x << endl; 191
192 What Happens When We Use Inline #include <iostream.h> int x = 0; Inline void f1() x++; Keyword? Inline void f2() x+=4; f1(); void main() f2(); cout << x << endl; 192
193 Person 20 (Masita Adam, Jonathan Tasyam) 193
194 Not safe! What is Bad About Using Global Vairables? If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value! Against The Principle of Information Hiding! Exposing the global variables to all functions is against the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!) 194
195 Local Variables Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit You have to initialize the local variable before using it If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable 195
6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.
6 Functions TOPICS 6.1 Focus on Software Engineering: Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5 Passing Data by Value 6.6 Focus
More informationChapter 6: Functions
Chapter 6: Functions 6.1 Modular Programming Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection of statements to perform
More informationLECTURE 06 FUNCTIONS
PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 06 FUNCTIONS IMRAN
More informationCh 6. Functions. Example: function calls function
Ch 6. Functions Part 2 CS 1428 Fall 2011 Jill Seaman Lecture 21 1 Example: function calls function void deeper() { cout
More informationChapter 2: Basic Elements of C++
Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationObjectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program
Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates
More informationChapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction
Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers
More informationC++ Programming: From Problem Analysis to Program Design, Third Edition
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine
More informationBasic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable
Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is
More informationWeek 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.
Week 3 Functions & Arrays Gaddis: Chapters 6 and 7 CS 5301 Fall 2015 Jill Seaman 1 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where
More information1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.
1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format
More informationObjectives. In this chapter, you will:
Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about
More informationEECS402 Lecture 02. Functions. Function Prototype
The University Of Michigan Lecture 02 Andrew M. Morgan Savitch Ch. 3-4 Functions Value and Reference Parameters Andrew M. Morgan 1 Functions Allows for modular programming Write the function once, call
More informationcalling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!
Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationTutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays
Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing
More informationC++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.
EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic
More informationThe University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.
The University Of Michigan Lecture 02 Andrew M. Morgan Savitch Ch. 3-4 Functions Value and Reference Parameters Andrew M. Morgan 1 Functions Allows for modular programming Write the function once, call
More informationBITG 1233: Introduction to C++
BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token
More informationMultiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationChapter 2. Outline. Simple C++ Programs
Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.
More informationMultiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationName SECTION: 12:45 2:20. True or False (12 Points)
Name SECION: 12:45 2:20 rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationCHAPTER 4 FUNCTIONS. 4.1 Introduction
CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main
More informationWeek 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018
Week 3 Functions & Arrays Gaddis: Chapters 6 and 7 CS 5301 Spring 2018 Jill Seaman 1 Function Definitions l Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements...
More informationProgramming. C++ Basics
Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++
More informationEngineering Problem Solving with C++, Etter/Ingber
Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input
More informationChapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 4 Procedural Abstraction and Functions That Return a Value 1 Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationChapter 2. C++ Basics
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables
More informationLaboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++
Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It
More information5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators
Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;
More informationReview: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements
Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja
More information8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );
- 50 - Control Structures: 8. Functions (II) Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This
More informationChapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationChapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and
More informationFunctions, Arrays & Structs
Functions, Arrays & Structs Unit 1 Chapters 6-7, 11 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where a parameter is: datatype identifier
More informationWARM UP LESSONS BARE BASICS
WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions
More informationCPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)
Name rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables retain their value
More informationIntroduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.
Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and
More informationCSCE Practice Midterm. Data Types
CSCE 2004 - Practice Midterm This midterm exam was given in class several years ago. Work each of the following questions on your own. Once you are done, check your answers. For any questions whose answers
More informationChapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2
More information1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.
1. C++ Overview 1. C++ Overview C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions. Interactive Mode, Batch Mode and Data Files. Common Programming
More informationReviewing all Topics this term
Today in CS161 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for) Functions (pass by value, pass by reference) Arrays (specifically arrays of characters)
More informationChapter 1 INTRODUCTION
Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer
More informationCSCE 206: Structured Programming in C++
CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationLECTURE 02 INTRODUCTION TO C++
PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION
More informationTrue or False (12 Points)
Name True or False (12 Points) 1. (12 pts) Circle T for true and F for false: T F a) A void function call occurs as part of an expression. T F b) Value Returning Functions cannot have reference parameters.
More information6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions
Chapter 6: 6.1 Functions Introduction to Functions What Is A Function? Why Functions? We ve been using functions ( e.g. main() ). C++ program consists of one or more functions Function: a collection of
More informationCS242 COMPUTER PROGRAMMING
CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationCS2141 Software Development using C/C++ C++ Basics
CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short
More informationQuiz Determine the output of the following program:
Quiz Determine the output of the following program: 1 Structured Programming Using C++ Lecture 4 : Loops & Iterations Dr. Amal Khalifa Dr. Amal Khalifa - Spring 2012 1 Lecture Contents: Loops While do-while
More informationCSCI 1061U Programming Workshop 2. C++ Basics
CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output
More informationGovernment Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING
Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++
More informationProgramming Language. Functions. Eng. Anis Nazer First Semester
Programming Language Functions Eng. Anis Nazer First Semester 2016-2017 Definitions Function : a set of statements that are written once, and can be executed upon request Functions are separate entities
More informationFunctions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92
L E S S O N S E T 6.2 Functions that Return a Value PURPOSE PROCEDURE 1. To introduce the concept of scope 2. To understand the difference between static, local and global variables 3. To introduce the
More informationC++ Basics. Lecture 2 COP 3014 Spring January 8, 2018
C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing
More informationName Section: M/W or T/TH. True or False (14 Points)
Name Section: M/W or T/TH True or False (14 Points) 1. (14 pts) Circle T for true and F for false: T F a) In C++, a function definition should not be nested within another function definition. T F b) Static
More informationPage. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team
Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10
More informationCS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil
CS 1428 Review CS 2308 :: Spring 2016 Molly O Neil Structure of a C++ Program Hello world // This program prints a greeting to the screen #include using namespace std; int main() { cout
More informationFunctions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single
Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationLecture # 6. Repetition. Review. If Else Statements Comparison Operators Boolean Expressions Nested Ifs. Switch Statements.
Lecture # 6 Repetition Review If Else Statements Comparison Operators Boolean Expressions Nested Ifs Dangling Else Switch Statements 1 While loops Syntax for the While Statement (Display 2.11 - page 76)
More informationCSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure
Learning Objectives At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable () Use increment (++) and decrement ( ) operators Program
More informationcs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).
cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion
More informationLooping. Arizona State University 1
Looping CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 5 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationProgramming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1
300580 Programming Fundamentals 3 With C++ Variable Declaration, Evaluation and Assignment 1 Today s Topics Variable declaration Assignment to variables Typecasting Counting Mathematical functions Keyboard
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationFunctions, Arrays & Structs
Functions, Arrays & Structs Unit 1 Chapters 6-7, 11 Function Definitions l Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where a parameter is: datatype identifier
More informationC++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay
C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming
More informationStandard Version of Starting Out with C++, 4th Edition. Chapter 6 Functions. Copyright 2003 Scott/Jones Publishing
Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions Copyright 2003 Scott/Jones Publishing Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes
More informationOther Loop Options EXAMPLE
C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you
More informationLab Instructor : Jean Lai
Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.
More informationBy the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program
1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize
More informationWeek 2. Muhao Chen.
Week 2 Muhao Chen Email: muhaochen@ucla.edu 1 Outline Variables and operators Undefined behaviors If-else (conditional statements) Loops Characters String 2 Variables and operators 3 Variables and Operators
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationIntroduction to Programming using C++
Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know
More informationc++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.
Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object
More informationChapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016
Chapter 6: User-Defined Functions Objectives In this chapter, you will: Learn about standard (predefined) functions Learn about user-defined functions Examine value-returning functions Construct and use
More informationFundamentals of Programming CS-110. Lecture 2
Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout
More informationA SHORT COURSE ON C++
Introduction to A SHORT COURSE ON School of Mathematics Semester 1 2008 Introduction to OUTLINE 1 INTRODUCTION TO 2 FLOW CONTROL AND FUNCTIONS If Else Looping Functions Cmath Library Prototyping Introduction
More informationFunctions. Arizona State University 1
Functions CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 6 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More information6. C++ Subprograms David Keil CS I slides 7/03 1
6. C++ Subprograms David Keil CS I slides 7/03 1 Topic: Subprograms for modularity Modular decomposition Defining C/C++ functions Local variables and scope Value parameters Reference parameters Return
More informationChapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design.
Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationCSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions
CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić 01-22-2018 Predefined Functions C comes with libraries of predefined functions E.g.:
More informationChapter 4. Procedural Abstraction and Functions That Return a Value
Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationA First Program - Greeting.cpp
C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationChapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1
Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)
More informationCAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE
CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE a) Mention any 4 characteristic of the object car. Ans name, colour, model number, engine state, power b) What
More informationWhy Is Repetition Needed?
Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable
More informationChapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School Objectives To understand the concepts of modularity and bottom up testing. To be aware of the use of structured
More informationDHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++
DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++ Objective: To Learn Basic input, output, and procedural part of C++. C++ Object-orientated programming language
More information