Download presentation
Presentation is loading. Please wait.
1
Fundamentals of structural programming
Dr. Mohamed Khafagy
2
Scope A sequence of statements within { … } is considered a block of code. The part of the program where you can use a certain identifier is called the scope of that identifier. The scope of an identifier starts immediately after its declaration and ends when the “innermost” block of code within which it is declared ends. It is possible to declare the same identifier in another block within the program.
3
Scope The scope of an identifier does not apply if the same identifier is declared in an inner block. A global declaration of an identifier is made outside the bodies of all functions, including the main function. It is normally grouped with the other global declarations and placed at the beginning of the program file. A local declaration of an identifier is made inside a block of code which could be the body of a function. Globally declared identifiers can be accessed anywhere in the program. Locally declared identifiers cannot be accessed outside of the block they were declared in.
4
Scope: Example 1 scope of y scope of fun scope of z scope of a
int y = 38; void fun(int, int); int main( ){ int z=47; while(z<400){ int a = 90; z += a++; z++; } y = 2 * z; fun(1, 2); return 0; void fun(int s, int t){ int r = 12; s = r + t; int i = 27; s += i; scope of y scope of fun scope of z scope of a scope of s & t scope of r scope of i
5
Example 2:Global Constants
#include <math.h> #include <iostream> using namespace std; const double PI = ; double area(double radius); //Returns the area of a circle with the specified radius. double volume(double radius); //returns the volume of a sphere with the specified radius. int main(){ double radius_of_both, area_of_circle, volume_of_sphere. cout << " Enter a radius to use for both a circle " << " and a sphere (in inches): “ cin >> radius_of_both; area_of_circle = area(radius_of_both); volume_of_sphere = volume(radius_of_both);
6
Example 2:Global Constants
cout << "Radius = " << radius_of_both << " inches \n" << "Area of circle = " << area_of_circle <<" square inches\n" <<"Volume of sphere = " << volume_of_sphere <<" cubic inches\n"; return 0; } double area(double radius) { return(PI * radius * radius); double volume(double radius) return((4.0/3.0)* PI * radius * radius * radius);
7
Scope: Example 3 #include <iostream>
Number in Increment() is the global variable. #include <iostream> using namespace std; int Number; //global variable void Increment(int IncNum) { IncNum = IncNum + 3; cout << IncNum << endl; Number = Number + 1; } int main() { Number = 1; Increment(Number); cout << Number << endl; return 0; }
8
Scope: Example 4 int Number; //global variable void Increment(int& IncNum) { IncNum = IncNum + 3; cout << IncNum << endl; Number = Number + 1; } int main() { Number = 1; Increment(Number); cout << Number << endl; return 0; When Increment is called, IncNum refers to global variable Number. Number = Number + 1 also refers to global variable Number.
9
Scope: Example 5 int Number; //global variable
void Increment(int Number) { Number = Number + 1; cout << Number << endl; } int main() { Number = 1; Increment(Number); cout << Number << endl; return 0; } The scope of the global variable Number does not include Increment(), because Increment() already has a local parameter of the same name. Thus, the changes made to Number are lost when control returns to the main program.
10
Scope: Example 6 int A,B,C,D; void Two(int A, int B, int& D) {
B = 21; D = 23; cout << A << " " << B << " " << C<< " " << D << endl; } void One(int A, int B, int& C) { int D; // Local variable A = 10; B = 11; C = 12; D = 13; cout << A << " " << B<< " " << C<< " " << D << endl; Two(A,B,C); int main() { A = 1; B = 2; C = 3; D = 4; One(A,B,C); cout << A << " " <<B << " " << C << " " << D << endl; return 0;
11
Scope: Example 6 Output: ABCD in One = 10 11 12 13
ABCD in Two = ABCD in Main = ABCD in Two =
12
Return Value A function normally returns a single result, if it is not a void function. At least one of the statements in the function body should have the form: return <expression>; The value passed back by the return statement should have the same type as the function.
13
Pass by Value The arguments of a function retain their original values after the function’s execution.
14
Pass by Value: Example 1 For example, consider the following code:
int sum(int num_1, int num_2){ num_1 = num_1 + num_2; return num_1; } int main(){ int var_x, var_y, var_z; var_x = 3; var_y = 5; var_z = sum(var_x, var_y); cout << var_z << endl; return 0; What are the values of var_x, var_y, and var_z at the end of the main() program?
15
Pass by Value: Example 1 The answer: 3, 5, and 8.
Even though the value of parameter num_1 is changed, the corresponding value in argument var_x does not change. The value of the argument is copied to the parameter, but changes to the value of the parameter do not affect the argument. In fact, all information in local variables declared within the function will be lost when the function terminates.
16
Pass by Value: Example 2 #include <iostream>
An example to show how the function does not affect a variable which is used as a parameter: // Test the effect of a function // on its parameter #include <iostream> using namespace std; void Increment(int Number) { Number = Number + 1; cout << "The parameter Number is: " << Number << endl; }
17
Pass by Value: Example 2 int main() { int I = 10;
//argument is a variable Increment(I ); cout << "The variable I is: " <<I << endl; //argument is a constant Increment(35); cout << "The variable I is: " <<I<< endl; //argument is an expression Increment(I +26); return 0; }
18
Pass by Value: Example 2
19
Pass by Value: Example 3 void PrintSumAve ( double, double );
// Print the sum and average of two numbers // Input: two numbers x & y // Output: sum - the sum of x & y // average - the average of x & y #include <iostream> using namespace std; void PrintSumAve ( double, double ); int main ( ) { double x, y; cout << "Enter two numbers: "; cin >> x >> y; PrintSumAve ( x , y ); return 0; }
20
Pass by Value: Example 3 void PrintSumAve (double no1, double no2) {
double sum, average; sum = no1 + no2; average = sum / 2; cout << "The sum is " << sum << endl; cout << "The average is " << average << endl; }
21
Pass by Value: Example 3 Data areas after call to PrintSumAve() :
22
Pass by Value: Example 4 double new_balance(double, double);
//Compute new balance at a certain interest rate //Inputs: A positive balance and // a positive interest rate //Output: The new balance after interest was posted #include <iostream> using namespace std; double new_balance(double, double); /* Returns the balance in a bank account after adding interest. For example, if rate is 5.0, then the interest rate is 5% and so new_balance(100, 5.0) returns */
23
Pass by Value: Example 4 int main(){ double interest, balance;
cout << "Enter balance (positive number): "; cin >> balance; if (balance <= 0.0) cout <<"Balance not positive; stopping" << endl; else { cout <<"Enter interest rate (positive number): "; cin >> interest; if (interest <= 0.0) cout <<"Interest not positive; stopping"<< endl; else cout <<"New balance = $" << new_balance(balance, interest)<< endl; } return 0;
24
Pass by Value: Example 4 // New balance is computed as balance + // balance * rate/100 double new_balance(double balance, double rate) { double interest_fraction, interest; interest_fraction = rate / 100; interest = interest_fraction * balance; return (balance + interest); } /* New balance is computed as balance * (1 + rate/100) double interest_fraction, updated_balance; updated_balance = balance * (1 + interest_fraction); return updated_balance; } */
25
Pass by Value: Example 5 // Input: inches // Output: feet and inches
#include <iostream> using namespace std; // Function prototypes int feet(int); int remain_inches(int);
26
Pass by Value: Example 5 int main() { int inches; // Number of inches
cout << "Enter number of inches to convert:"; cin >> inches; cout << "Result is " << feet(inches) << " feet " << remain_inches(inches) << " inches" << endl; return 0; } int feet(int input_inches) { return input_inches / 12; } int remain_inches(int input_inches) { return input_inches % 12; }
27
Pass by Value: Example 6 // File main.cpp // Input inches
// Output feet and inches #include <iostream> #include "i2f.h" using namespace std; int main() { int inches; // Number of inches cout << "Enter number of inches to convert:"; cin >> inches; cout << "Result is "<< feet(inches)<<" feet " << remain_inches(inches) << " inches" << endl; return 0; }
28
Passing Parameters by Reference
To have a function with multiple outputs, we have to use pass by reference. We use & to denote a parameter that is passed by reference: <type>& <variable> Examples: void Increment(int& Number); void SumAve (double, double,double&, double&);
29
Passing Parameters by Reference
The corresponding argument must be a variable. Increment(Inc); SumAve (2.5, y+3, sum, mean); The address (reference) of that variable is passed to the function, instead of its value. If the function changes the parameter value, the change will be reflected in the corresponding argument, since they share the same memory location.
30
Pass by Reference: Example 1
To show how the function affects a variable which is used as an argument: #include <iostream> using namespace std; void Increment(int& Number){ Number = Number + 1; cout << "The parameter Number: " << Number << endl; } int main(){ int Inc = 10; Increment(Inc); // parameter is a variable cout << "The variable Inc is: "<<Inc<<endl; return 0; }
31
Pass by Reference: Example 2
It is possible to use both pass by reference and pass by value parameters in the same function. // Print the sum and average of two numbers // Input: two numbers num_1 and num_2 // Output: sum of num_1 and num_2 // average of num_1 and num_2 #include <iostream> using namespace std; void SumAve (double, double, double&, double&);
32
Pass by Reference: Example 2
int main ( ) { double x, y, sum, mean; cout << "Enter two numbers: "; cin >> x >> y; SumAve (x, y, sum, mean); cout << "The sum is " << sum << endl; cout << "The average is " << mean << endl; return 0; } void SumAve(double no1, double no2, double& sum, double& average) { sum = no1 + no2; average = sum / 2; }
33
Pass by Reference: Example 2
Data areas after call to SumAve:
34
Pass by Reference: Example 3
// Compare and sort three integers #include <iostream> using namespace std; void swap (int&, int&); int main ( ) { int first, second, third;// input integers // Read in first, second and third. cout << "Enter three integers: "; cin >> first >> second >> third; if (first > second) swap (first, second); if (second > third) swap (second, third); cout << "The sorted integers are " << first <<" , "<<second<<" , "<<third << endl; return 0; }
35
Pass by Reference: Example 3
// Function for swapping two integers void swap (int& num_1, int& num_2) { int temp; temp = num_1; num_1 = num_2; num_2 = temp; }
36
Pass by Reference: Example 4
// Pass-by-reference versus pass-by-value example #include <iostream> using namespace std; void One (int a, int b, int& c) { int d; a = 10; b = 11; c = 12; d = 13; cout<<"The values of a, b, c, and d in One:\n"; cout << a << " " << b << " " << c << " " << d << endl; } void Two (int a, int b, int& d) { int c = 0; cout<<"The values of a, b, c, and d in Two:\n"; << d << endl; }
37
Pass by Reference: Example 4
int main () { int a = 1, b = 2, c = 3, d = 4; cout<<"The original values of a,b,c,and d:\n"; cout << a << " " << b << " " << c << " " << d << endl << endl; One(a, b, c); cout<<"The values of a,b,c,and d after One:\n"; << d << endl; Two(a, b, d); cout<<"The values of a,b,c,and d after Two:\n"; return 0; }
38
Pass by Reference: Example 4
Output: The original values of a,b,c,and d: The values of a, b, c, and d in One: The values of a, b, c, and d after One: The values of a, b, c, and d in two: The values of a, b, c, and d after two:
39
Testing and Debugging Functions
One major advantage of functions is that they can be designed, coded and tested separately from the rest of the program. Use a "driver" program to test a function with several inputs: int main( ) { for (int count = 1; count <= 13; count++){ diamond(count); cout << " Calling diamond with size " << count <<endl; } return 0;
40
Testing and Debugging Functions
If a yet-to-be written function is needed in testing a program, replace it with a "stub" for testing. A stub has the same interface as the original function, but not the full implementation. Oftentimes, a stub contains just a simple return or cout command. void diamond(int size) { cout << " diamond is called with size " << size <<endl; }
41
Example: A Simple Math Learning Tool
This example creates a program for a first grader to practice subtractions. The program randomly generates two single-digit integers number1 and number2 with number1 > number2 and displays a question such as “What is 9 – 2?” to the student, as shown in the sample output. After the student types the answer, the program displays a message to indicate whether the answer is correct.
42
Random function: rand()
#include <iostream> #include <ctime> // for time function #include <cstdlib> // for rand and srand functions using namespace std; int main() { // 1. Generate two random single-digit integers srand(time(0)); int number1 = rand() % 10; int number2 = rand() % 10; // 2. If number1 < number2, swap number1 with number2 if (number1 < number2) int temp = number1; number1 = number2; number2 = temp; }
43
Random function: rand()
// 3. Prompt the student to answer cout << "What is " << number1 << " - " << number2 << "? "; int answer; cin >> answer; // 4. Grade the answer and display the result if (number1 - number2 == answer) cout << "You are correct!"; else cout << "Your answer is wrong.\n" << number1 << " - " << number2 << " should be " << (number1 - number2) << endl; return 0; }
44
Generating Random Characters
Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. Since every character has a unique ASCII code between 0 and To generate a random character is to generate a random integer between 0 and 127. We already learn how to generate random number from last example. Basically it is to use the srand(seed) function to set a seed and use rand() to return a random integer. You can use it to write a simple expression to generate random numbers in any range. For example,
45
Case Study: Generating Random Characters,
46
Random function: rand()
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; // Generate a random character between ch1 and ch2 char getRandomCharacter(char ch1, char ch2) { return static_cast<char>(ch1 + rand() % (ch2 - ch1 + 1));} // Generate a random lowercase letter char getRandomLowerCaseLetter() { return getRandomCharacter('a', 'z');} // Generate a random uppercase letter char getRandomUpperCaseLetter() { return getRandomCharacter('A', 'Z');} // Generate a random digit character char getRandomDigitCharacter() { return getRandomCharacter('0', '9');} // Generate a random character char getRandomCharacter() { return getRandomCharacter(0, 127);} Random function: rand()
47
Random function: rand()
int main() { const int NUMBER_OF_CHARS = 175; const int CHARS_PER_LINE = 25; srand(time(0)); // Set a new seed for random function // Print random characters between '!' and '~', 25 chars per line for (int i = 0; i < NUMBER_OF_CHARS; i++) char ch = getRandomLowerCaseLetter(); if ((i + 1) % CHARS_PER_LINE == 0) cout << ch << endl; else cout << ch; } return 0;}
48
Global Variables Undisciplined use of global identifiers may lead to confusion and debugging difficulties. Instead of using global variables, you should communicate values between functions through the arguments in function calls.
49
Local Variables Variables declared in a function:
Are local to that function, they cannot be used from outside the function Have the function as their scope Variables declared in the main part of a program: Are local to the main part of the program, they cannot be used from outside the main part Have the main part as their scope
50
Global Constants Global Named Constant
Available to more than one function as well as themain part of the program Declared outside any function body Declared outside the main function body Declared before any function that uses it Example: const double PI = ;double volume(double);intmain(){…} PI is available to the main function and to function volume
51
Global Variables Global Variable --rarely used when morethan one function must use a common variable Declared just like a global constant except const is not used Generally make programs more difficult to understand and maintain
52
Formal Parametersare Local Variables
Formal Parameters are actually variables that arelocal to the function definition They are used just as if they were declared in the function body Do NOT re-declare the formal parameters in the function body, they are declared in the functiondeclaration The call-by-value mechanism When a function is called the formal parameters are initialized to the values of thearguments in the function call
53
Overloading Function Names
C++ allows more than one definition for the same function name Very convenient for situations in which the “same”function is needed for different numbers or typesof arguments Overloading a function name means providing more than one declaration and definition using the same function name
54
Overloading Examples
55
Overloading Details Overloaded functions
Must have different numbers of formal parametersAND / OR Must have at least one different type of parameter Must return a value of the same type
56
Overloading Example intmaximum(intdigit1, intdigit2); // prototype
intmaximum(intdigit1, intdigit2, intdigit3); // prototype intmain() { cout<< "Finding the max from 23, 0, 88\n"; intmax = maximum(23, 0, 88); cout<< "The max value is " << max << endl; return 0; } intmaximum(intdigit1, intdigit2) { double max = 0; if(digit1 < digit2) return digit2; else return digit1;
57
intmaximum(intdigit1, intdigit2, intdigit3) {
if(digit1 < digit2) max = digit2; else max = digit1; if(max < digit3) max = digit3; return max; }
58
Automatic Type Conversion
Given the definitiondouble mpg(double miles, double gallons){return (miles / gallons);}what will happen if mpg is called in this way?cout << mpg(45, 2) << “ miles per gallon”; The values of the arguments will automatically beconverted to type double (45.0 and 2.0)
59
intmaximum(intdigit1, intdigit2, intdigit3) {
if(digit1 < digit2) max = digit2; else max = digit1; if(max < digit3) max = digit3; return max; } /************************************************************************/ /* THIS IS ILLEGAL */ /************************************************************************ double maximum(intdigit1, intdigit2, intdigit3) { double max = 0.0; max = static_cast<double>(digit2); max = static_cast<double>(digit1); max = static_cast<double>(digit3);
60
void‐Functions In top‐down design, a subtask might produce
No value (just input or output for example) One value More than one value We have seen how to implement functions that return one value A void‐function implements a subtask that ret urns no value or more than one value
61
void‐Function Definition
Two main differences between void‐function definitions and the definitions of functions t hat return one value Keyword void replaces the type of the value returnedvoid means that no value is returned by the function The return statement does not include an expression or value Example:void promptForLowerChar() { cout<< "Please type a lowercase character "; cout<< "and I will make it uppercase.\n"; Return; }
62
Using a void‐Function void‐function calls are executable statements They do not need to be part of another sta tement They end with a semi‐colon Example: promptForLowerChar(); cin>> theChar; outputUpperCase(theChar); NOT: cout<< promptForLowerChar(); May accept parameters or not
63
void‐Function Calls Mechanism is nearly the same as the functio calls we have seenArgument values are substituted for the formal parameters It is fairly common to have no parameters in void‐functionsIn this case there will be no arguments in the function call Statements in function body are executed Optional return statement ends the function Return statement does not include a value to return Return statement is implicit if it is not included
64
Multiple Returns void fixACar(intnumberOfCarsToFix) {
if(numberOfCarsToFix> 1) return; intcarsCounter= 1; cin>> hours; cout<< “Your current charges are: “; cout<< calculateCharges(hours) << endl; }
65
void‐FunctionsWhy Use a Return?
Is a return‐statement ever needed in avoid‐function since no value is returned?Yes!What if a branch of an if‐else statement requires that the function ends to avoid producing more output, or creating a mathematical error? void‐function in next example, avoids division by zero with a return statement
66
void outputDivide(intop1, intop2) {
if(op2 == 0) return; else cout<< (op1/op2) << endl; }
67
The Main Function The main function in a program is used like av oid function…do you have to end the program with a return‐statement?Because the main functi on is defined to return a value of type int, the return is needed C++ standard says the return 0 can be omitted, but many compilers still require it
68
Can youDescribe the differences between void‐fu nctions and functions that return one value?
Tell what happens if you forget the return‐statem ent in a void‐function? Distinguish between functions that are used as expressions and those used as statements? Return value the other returns void or nothing
69
Call‐by‐Reference Parameters
Call‐by‐value is not adequate when we need a sub ‐task to obtain input values Call‐by‐value means that the formal parameters r eceive the values of the arguments To obtain input values, we need to change the variables that are arguments to the functionR call that we have changed the values of formal parameters in a function body, but we have not changed the arguments found in the function call Call‐by‐reference parameters allow us to changet he variable used in the function callArguments f or call‐by‐reference parameters must be variables, not numbers
70
Call‐by‐Reference Example
void square(int& aVar) { aVar*= aVar; cout<< "\tinside" << aVar<< endl; } ‘&’ symbol (ampersand) identifies “a” as a c all‐by‐reference parameterUsed in both decla ration and definition! The book places the ‘&’ at the end of the formal parameters type, but it may be placed at the beginning of the variable name I like the book’s style
71
Call‐By‐Reference Details
Compare what happens with pass‐by‐value to what happens with pass‐by‐reference Call‐by‐reference works almost as if the argument variable is substituted for the for malparameter, not the argument’s value In reality, the memory location of the arg umentvariable is given to the formal para meterWhatever is done to a formal para meter in the function body, is actually do ne to the value at the memory location of the argument variable
72
Call ComparisonsCall By Reference vsValue
73
Example: swap void swap(int& variable1, int& variable2) {inttemp = v ariable1;variable1 = variable2;variable2 = temp;} If called with swap(num1, num2); num1 is substituted for variable1 in the parameter list num2 is substituted for variable2 in the parameter list temp is assigned the value of variable1 (num1) sinc e the next line will loose the value in num1 variable1 (num1) is assigned the value in variable2 (num2) variable2 (num2) is assigned the original value of vari able1 (num1) which was stored in temp
74
Mixed Parameter Lists Call‐by‐value and call‐by‐reference parameters can be mixed in the same function Example:void getSubmarines(int& submarines, int& torpedos, intdepthCharges); submarinesand torpedoesare call‐by‐reference formal parametersChanges in submarinesand torpedoschange the argument variable depthChargesis a call‐by‐value formal parameterChanges in depthChargesdo not change the argument variable Side Note: One disadvantage of pass‐by‐value is that, if a large data item is being passed, copying that data can take a considerable amount of execution time and memory space.
75
Choosing Parameter Types
How do you decide whether a call‐by‐referenceor call‐by‐value formal parameter is needed?Does the f unction need to change the value of the variable u sed as an argument? Yes? Use a call‐by‐reference formal parameter No? Use a call‐by‐value formal parameter
76
Inadvertent Local Variables
If a function is to change the value of a variablethe corresponding formal parameter must be a call‐by‐ref erence parameter with an ampersand (&) attached Forgetting the ampersand (&) creates a call‐by‐value parameter The value of the variable will not be changed The formal parameter is a local variable that has n oeffect outside the function Hard error to find…it looks right!
77
Can youWrite a void‐function definition for a funct ion calledzeroBoththat has two reference parameter s, bothof which are variables of type int, and sets the valuesof both variables to 0. Write a function that returns a value and has a ca ll‐by‐reference parameter? Write a function with both call‐by‐value and call‐by ‐reference parameters
78
Functions Calling Functions
A function body may contain a call to anotherfunctionThe called function declaration must still appearbefore it is calledFunctions cannot be defined in the body of another function Example: void setDepthCharges(int& submarines, int& torpedoes, intdepthC harges) { getSubsAndTorpedoes(submarines, torpedoes); for(inti= 0; i< depthCharges; i++) { inthitSub= 1 + rand() % (submarines * 2); if(hitSub<= submarines) { cout<< "Submarine " << hitSub<< " has been hit by "; cout<< "a depth charge\n"; } else { cout<< "Depth charge " << (i+1) << " missed.\n"; } } }
79
Case StudyGarage Pricing
Problem definitionDetermine the parking charge for 3 cars parked Flat fee of $2.00 for up to and including 3 hour of parking Flat fee $10.00 for a car parked for 24 hoursNo car will exceed 24 hours $0.50 charge for each hour or part of an hour in excess of three hours InputThe hours that each car was parked in the garage OutputThe hours for each car, the charge, the total hours and the total charges for the day
80
Garage Pricing:Problem Analysis
Three main subtasks Input the data Compute the charges based on the hours Output the results Each task can be implemented with a functionNotic e the use of call‐by‐value and call‐by‐reference para meters in the following function declarations
81
Garage Pricing:The main function
With the functions declared, we can write the main function: intmain() { double hours1; double hours2; double hours3; getHoursForCars(hours1, hours2, hours3); setDecimalFormat(); outputCharges(hours1, hours2, hours3); }
82
Algorithm Design calculateCharges
pseudocodefor the price function if hours <= 3 return $2.00 if hours == 24 return $10.00 otherwise return 2.00 + roundup (hours‐3)*0.50;
83
Coding The calculateChargesFunction
The body of the price function double calculateCharges(double hours) { if(hours <= 3) { return 2.0; } else if(hours == 24) { return 10.0; } else { return 2.0 + ceil(hours‐3.0)*.50; }
84
Garage Pricing :Program Testing
Testing strategiesUse data that tests both the high and low markup cases Test boundary conditions, where the program is ex pected to change behavior or make a choice 3 hours, 4 hours and 24 hours Test for exactly 4.5 hours make sure your program is rounding up 3 = 2.00 4.5‐3 = 1.5 2*.5 = 1.00 Total 3.00
85
Can youDefine a function in the body of another function?
Call one function from the body of another functi on? Give preconditions and postconditions for the pred efined function sqrt?
86
Testing and Debugging Functions
Each function should be tested as a separate unit Testing individual functions facilitates finding mistakes Driver programs allow testing of individual functions Once a function is tested, it can be used in the driver program to test other functions Function getSubsAndTorpedoesis tested in the driver program
87
void getSubsAndTorpedoes(int& submarines, int& torpedoes) ;
intmain() { intsubmarines = 0; inttorpedoes = 0; intdepthCharges= 10; char again = 'Y'; while(toupper(again) != 'N') { cout<< "Type integers for subs and torpedoes\n"; getSubsAndTorpedoes(submarines, torpedoes); cout<< "Subs set by the user " << submarines << endl; cout<< "Torpedoes set by the user " << torpedoes << endl; cout<< "Would you like to continue?\n"; cout<< "Y for yes and N for no\n"; cin>> again; } return 0; }
88
void getSubsAndTorpedoes(int& submarines, int& torpe does) {
cin>> submarines; cin>> torpedoes; cout<< "You have typed "; cout<< submarines << " submarines and "; cout<< torpedoes << " torpedoes\n"; }
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.