300 likes | 311 Vues
Stay updated with CS201 announcements and homework deadlines. Follow submission guidelines for effective coding practices. Prepare for upcoming exams. Learn about C++ basics and modular programming with functions. Stay connected via email and SUCourse.
E N D
Announcements • Homework 1 is due on February 22nd, this Wednesday, at 19:00 • Submit to SUCourse • Strictly follow the submission guideline provided in the homework document • About the homework: • If you run under the debugger (Ctrl+F5), you will get this prompt: • Press any key to continue . . . • If you run with F5 only, you will NOT get this prompt, so it is OK. • You can add the following at the end of your code to get the same effect: cin.ignore(); cin.get(); • Write comments in your program • Homework 2 will be assigned this week
Announcements • Email list is active • CS201-201602@sucourse.sabanciuniv.edu • Your sabanciuniv accounts must be in this list • I’ve already sent some emails to this list. Did you get them? • I will make announcements to the email list and also to SUCourse • Check your emails and SUCourse regularly • Please do not subscribe this list address to some other lists • Office Hours have started, schedule below: • http://myweb.sabanciuniv.edu/gulsend/courses/cs201/assistants/office-hours/
Announcements • First midterm exam will be on Monday, March 27th, 2017, 19:40 – 21:30 • Second midterm exam will be on Tuesday, May 2nd, 2017, 19:40 – 21:30 • For those who have exam collisions with another course: talk with your other instructor immediately! • I cannot change the exam dates anymore but I can work out a solution with them.
Summary of what we learned last week • Basics of C++ • Our first program: “Hello world” • Format of a program • Syntax of literals, keywords, symbols, variables • Data types • int (short, long, unsigned) • float/double • char • Arithmetic operations • Assignment (compound) operators • Standard input (cin) and output (cout) • More complex arithmetic operations and operator precedence
Functions (Chapter 2 – Continued) • Main function – will soon get big • Solution: Divide and Conquer • divide your problem into small ones • write one function for each • combine them in the main program • Advantages: • Main is organized into modular pieces • When you need to change something, you only change that function and not main • Reuse the same code piece several times • e.g. all programs use cin and cout
Functions Without function With function #include <iostream> using namespace std; /* traditional first program */ int main() { cout << "Hello world" << endl; return 0; } #include <iostream> using namespace std; /* traditional first program */ void Hello() { cout << "Hello world" << endl; } int main() { Hello(); return 0; }
Syntax of Functions • A program is a collection of functions and classes • main and other programmer defined functions • only main is executed automatically when the program starts • other functions must be called to be executed • Programmer-defined functions • piece of code to do a specific job • must be declared before using (calling) return-typefunction-name(parameters) { local variables statements } • to execute a function just write its name (and arguments for parameters) • When a function is called, executionordertemporarilyjumpstofunction • after the functionends, execution order goes back to the caller
Syntax for Functions #include <iostream> using namespace std; voidHello() { cout << "Hello world" << endl; } int main() { Hello(); return 0; } return-typefunction-name(parameters) { local-variables statements } • “void” means returns nothing. • no parameters (we will see parametric functions today) • no local variables
Drawing Head – Without functions #include <iostream> using namespace std; int main() { cout << " |||||||||||||||| " << endl; cout << " | | " << endl; cout << " | o o | " << endl; cout << " _| |_ " << endl; cout << "|_ _|" << endl; cout << " | |______| | " << endl; cout << " | | " << endl; return 0; } • Draws a head – but not so modular • To change head style, main needs to change. • Is this so bad? • What if you want to draw several heads like a totem? • You have to duplicate code
Drawing Head – With functions parts.cpp #include <iostream> using namespace std; // functions appear here int main() { Hair(); Sides(); Eyes(); Ears(); Smile(); Sides(); return 0; } • This one is more complicated, but what are the advantages? • Modularity • Change head style just change functions • What about eyeglasses? • Code re-use (not duplicated) • Multiple heads let’s see totem.cpp
Functions with Parameters • You may need to pass data into a function when you call it • Consider a generic function to calculate the area of any circle and display it • how will the function know the radius? • solution: parameters • function is defined without knowing the value of the radius • value of radius is passed to the function when it is called • parameters are defined similar to variables type name Example: double radius return-typefunc-name(type param1,…,type param<n>) { local variables statements }
Area calculation with parameterized function #include <iostream> using namespace std; // area calculation program that employs functions void calculate_area(double radius) { double area; area = 3.14 * radius * radius; cout << "The area of a circle with radius " << radius << " is " << area << endl; } int main() { double r; r = 3; calculate_area(r); calculate_area(2.5); calculate_area(r / 2); return 0; }
Area calculation with parameterized function #include <iostream> using namespace std; // area calculation program that employs functions void calculate_area (double radius) { double area; area = 3.14 * radius * radius; cout << "The area of a circle with radius " << radius << " is " << area << endl; } int main() { double r; r = 3; calculate_area(r); calculate_area(2.5); calculate_area(r / 2); return 0; } radius is 3 Output Screen The area of a circle with radius 3 is 28.26
Area calculation with parameterized function #include <iostream> using namespace std; // area calculation program that employs functions void calculate_area (double radius) { double area; area = 3.14 * radius * radius; cout << "The area of a circle with radius " << radius << " is " << area << endl; } int main() { double r; r = 3; calculate_area(r); calculate_area(2.5); calculate_area(r / 2); return 0; } radius is 2.5 Output Screen The area of a circle with radius 3 is 28.26 The area of a circle with radius 2.5 is 19.625
Area calculation with parameterized function #include <iostream> using namespace std; // area calculation program that employs functions void calculate_area (double radius) { double area; area = 3.14*radius*radius; cout << "The area of a circle with radius " << radius << " is " << area << endl; } int main() { double r; r = 3; calculate_area(r); calculate_area(2.5); calculate_area(r / 2); return 0; } radius is 1.5 Output Screen The area of a circle with radius 3 is 28.26 The area of a circle with radius 2.5 is 19.625 The area of a circle with radius 1.5 is 7.065
Functions with Parameters • Parameters and Arguments • parameter is the generic name used in function • radius in the calculate_area function • argument is the value passed to function while it is called • 2.5 • r (actually current value of r is passed) • r / 2 (actually current value of r / 2 is passed) • Parameter list provides type and name of the parameter • Argument type must match parameter type • Functions may have multiple parameters • corresponding arguments are separated by commas • in the same order of parameter list • be careful about the type matching • Functions may call other functions (have seen in the totem example and will see in the next example)
Functions with Parameters • Parameters versus Local Variables • Parameters are defined and used locally, but their initial value comes from the caller function via arguments • Local variables are defined and used within the function • Initial value does not come from the caller function • While designing your functions, think carefully about local variables and parameters • If you need to pass the initial value from the caller function, then it should be a parameter. • If you won’t pass the initial value, then it should be a local variable. • Example: in calculate_areafunction • areais a local variable since we do not pass its initial value from main • radiusis a parameter since we need to pass its initial value from main • Unnecessary parameters may cause problems and grade reduction (for homework)
Old McDonald’s Farm • Goal is to have a modular program (with functions) to display the song • each verse repeats using a different animal • refrain parts repeat within verses • a partial output (with two animals only) below: Old MacDonald had a farm, Ee-igh, Ee-igh, oh! And on his farm he had a cow, Ee-igh, Ee-igh, oh! With a moo moo here And a moo moo there Here a moo, there a moo, everywhere a moo moo Old MacDonald had a farm, Ee-igh, Ee-igh, oh! Old MacDonald had a farm, Ee-igh, Ee-igh, oh! And on his farm he had a pig, Ee-igh, Ee-igh, oh! With a oink oink here And a oink oink there Here a oink, there a oink, everywhere a oink oink Old MacDonald had a farm, Ee-igh, Ee-igh, oh!
Old McDonald’s Farm (Design of Functions) • Which functions do we need? • a function for only “Ee-igh, Ee-igh, oh!” • a function for the refrain (nakarat) • a function for “And on his farm ...” line • animal is parameter • a function for “With a ...”, “And a ...”, “Here a ...” lines • noise of the animal is a parameter • a function for the whole verse
Old McDonald’s Farm (Program 1) • See oldmac1.cpp • What is the problem? • We need a new function for a new animal (e.g. chicken) • Cow and Pig functions are duplicates of each other. • Solution: Put the common code into a new function for the whole verse
Old McDonald’s Farm (Program 2) • See oldmac2.cpp • Verse does the common work with 2 parameters – first one is for animal, second is for noise • therefore it is called using 2 arguments – first one is for animal, second is for noise • order of arguments is important • Functions call functions • Refrain calls EiEio • Verse calls Refrain • animal is used as parameter name in two functions • Should we need to use the same parameter name in both cases? Or can we use different names in two different functions? • Same questions are valid for noise as well. • Answer is “Yes we can use different names”. • Can we input animal and noise?
Mac Donald’s farm with user input • We want the user to enter/input values for animal and noise Enter the name of an animal: sheep Enter noise that a sheep makes: baah Old MacDonald had a farm, Ee-igh, Ee-igh, oh! And on his farm he had a sheep, Ee-igh, ee-igh, oh! With a baahbaah here And a baahbaah there Here a baah, there a baah, everywhere a baahbaah Old MacDonald had a farm, Ee-igh, Ee-igh, oh! • We’ll pass the user-entered values to the Verse function • The input stream cin takes input from the keyboard using operator >> • Values that are input are stored in variables and then passed to function verse as arguments • see macinput2.cpp
Mac Donald’s farm with user input // other functions goes here (see macinput2.cpp) void Verse(string animal, string noise) { // this function doesn’t change // see the source code for the function code } int main() { string animal; // variable for name of animal string noise; // variable for noise it makes cout << "Enter the name of an animal: "; cin >> animal; cout << "Enter noise that a " << animal << " makes: "; cin >> noise; Verse(animal,noise); return 0; }
Analysis of the Run • input value “sheep” is stored in variable animal • input value “baah” is stored in variable noise • “sheep” and “baah” values are passed to function Verse as arguments as well as used in cout in main
Variables (review from previous lectures) • Variables are used to store values in memory • memory locations that are accessed using a name • Each variable has a type, a name (identifier), and a value • Methods to give values to variables • Assignment, using = • Input, using cin • Definition: typevariable_names_separated_by_comma;
Where to define variables • You can define variables anywhere within a function • as long as it is defined before its first use • Two common places of variable definition • At the beginning of the function in which they’re used: { string animal, noise; cout << "enter animal "; cin >> animal; cout << "enter noise a " << animal << " makes "; cin >> noise; } • Just before the first place they’re used: { cout << "enter animal "; string animal; cin >> animal; cout << "enter noise a " << animal << " makes "; string noise; cin >> noise; }
Where to define variables • NO GLOBAL VARIABLES • A global variable is a variable defined outside the function bodies #include <iostream> using namespace std; int global_number; int main() { cout << "Hello world“ << endl; return 0; } • They can be used in all functions without definition • That is why it is the #1 enemy of parameters • If you use global variables, you violate the independence property of functions and may lose your control in big programs • Thus, IT IS FORBIDDEN TO USE GLOBAL VARIABLES • If you use a global variable in hw and exams, your grade is reduced! • We will revisit the global variable concept towards the end of the course.
Variable Initialization • Variables have garbage (junk values) until • they are assigned a value using assignment operator or • myint = 5; • an input is stored into them (using cin statement) • cin >> myint; • Variables must be given a value before being used for the first time in an expression or an output statement or as an argument to a function • idea behind this rule: you can never know what is inside of an uninitialized variable ! • not a syntax error, compiler may or may not warn you! • You may initialize variables at the declaration int mynumber = 5; • After initialization, you may change the value stored in a variable several times • that is why they are named as “variable”
Scope of a Variable and Parameter • Not explained in the book in this way • RULE 1: A variable or parameter can be referred only within the function in which it is declared • e.g. you cannot refer the variable “animal” in function Eieio • RULE 2: A specific identifier can be used several times in different functions as variable or parameter names. Those are actually different variables/parameters. • e.g. animal and noise are used both in main (as variable) and Verse (as parameter) • RULE 3: A specific identifier must be unique within a function • e.g. you cannot define a local variable “animal” in Verse since there is a parameter named “animal” • Detailed scope rules will be given later in this course
Reading Assignment • Section 3.3 (page 83) • Case Study: Pizza Slices • Similar to circle area calculation program • Run the program pizza.cpp