cs201 introduction to computing @ sabancı university 1 announcements l midterm dates ä first...
TRANSCRIPT
CS201 Introduction to Computing @ Sabancı University 1
Announcements Midterm Dates
First Midterm Exam: November 7, 2015, Saturday, 14:00 – 16:00 Second Midterm Exam: December 5, 2015, Saturday, 10:00 – 12:00
Extra lecture on Wednesday between 17:40 – 19:30 in FASS G062. Same lecture will be repeated on the same day 19:40 – 21:30 in FASS
G062. Office Hours have started, schedule is at the TA web site, which is
reachable from course web site. Anyone who have not formally registered to the course until the end of
add drop should see me during the break. Email list is active
[email protected] Service provided by SUCourse; Your sabanciuniv accounts are
registered We’ve already sent some emails to this list. Did you get them? We will make announcements to the list and sometimes to
SUCourse. Check your emails and SUCourse regularly Please do not subscribe this list address to some other lists
CS201 Introduction to Computing @ Sabancı University 2
Announcements Our development environment is MS Visual Studio/C++ 2012 under MS
Windows. Any Windows is OK but for Visual Studio you have to use 2012. Older or
newer versions may create consistency problems with our grading system. Other C++ compilers and development environments also have the same
potential for inconsistency.• Thus your homework that works in your compiler may not work in ours. • If you have to use another development environment for some reason, you have
to make sure that it also works under Windows and MS Visual Studio 2012 before submission. This is your responsibility.
The "robot" application that we will see next week (and also HW3 and HW5 will be about it) designed only for MS Windows and Visual Studio; you will not be able to use it in another platform.
Any Mac users encountered problem during installation? Windows 8 is no longer available at university's Software server?
• Due to licence restrictions You can get Windows from Microsoft Dreamspark service
• To do so first you have write IT to get an account and then wait for Microsoft for activation. This process may take a couple of days. Details are here http://mysu.sabanciuniv.edu/it/tr/microsoft-software/dreamspark
CS201 Introduction to Computing @ Sabancı University 3
Announcements First homework is due on October 7, Wednesday, 17:00
Submit to SUCourse Strictly follow the submission guideline provided in the homework
specification Write comments in your program (this will affect your grade) Use meaningful identifier names and have a proper indentation (these
will also affect your grade) New (Second) homework will be assigned this week Stopping at the end of the program execution
If you run under the debugger (Ctrl+F5), you will automatically get this prompt at the end of the execution and the program waits there:• Press any key to continue . . .
However, if you run with F5 only, you will NOT get this prompt and the console screen (the black screen) disappears after the execution. This is not a problem of your code.
You can add the following at the end of your code (before return 0;) to get the same effect:cin.ignore();cin.get();
CS201 Introduction to Computing @ Sabancı University 4
Announcements A general question about the first homework
What if the total number of points cannot be reached with integer number of wins and draws?• E.g. if total points is 18, one win is 5 and one draw is 2 points. Max.
number of wins is 3 , but the remaining 3 points cannot be obtained with integer number of draws.
• In the homework specification we explicitly stated that such cases will not happen. Thus you can assume that there always be integer solutions in the test cases.
Another issue about the first homework There must be four inputs only
• First one is the name of the team• Second one is the amount of points given to a win• Third one is the amount of points given to a draw• Fourth one is the total points to be collected
You have to preserve this order No other inputs are allowed. Otherwise, our system cannot process
your homework
CS201 Introduction to Computing @ Sabancı University 5
Chapter 2 – Continued / Functions Main function 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 (this is named as calling a function)
return-type function-name (parameters){ local variables
statements}
to execute a function just write its name (and arguments for parameters)• When a function is called, execution order temporarily jumps to function• after the function ends, execution order goes back to the caller
For the time being• return type is void – that means returns nothing• no parameters (we will see parametric functions today)
CS201 Introduction to Computing @ Sabancı University 6
Functions – A simple example
Without 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;
}
With function
Output is the same in both case
Hello world
CS201 Introduction to Computing @ Sabancı University 7
Why Functions?
Divide and Conquer technique divide your problem into small ones write one function for each combine them in the main program
Provides modularity when you need to replace a piece of code, you just
change a function you may not need to change the main program
Reuse the same code piece several times avoid repeating the same code
CS201 Introduction to Computing @ Sabancı University 8
With no 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;} Prints head, but not so modular
changing the head style requires an update in main. Is this bad? • in this “small” example, need for modularity may not be clear, but
in long programs you will need it. Several heads (like a totem)?
you have to duplicate the same code
CS201 Introduction to Computing @ Sabancı University 9
With FunctionsSee parts.cpp for the entire program
#include <iostream>using namespace std;// functions appear here
int main(){
Hair(); Sides();Eyes(); Ears(); Smile();Sides();return 0;
} Although more complicated, what are advantages of this main over one in
which several output statements appear in main? modularity
• changing the head style = changing function(s)• what about eyeglasses? mustache? (let’s do one)
Code re-use (i.e. NOT duplicating the code unnecessarily)• multiple heads (totem poles)? (let’s do one)
CS201 Introduction to Computing @ Sabancı University 10
Functions with Parameters Functions are useful, parameterized functions might be more useful
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 You may have several
parameters separated by comma
return-type func-name (type param1, type param2,…){ local variables statements}
CS201 Introduction to Computing @ Sabancı University 11
Area calculation using parameterized function
#include <iostream>using namespace std;// area calculation program that employs functions
void calculate_area (float radius){
float area;
area = 3.14*radius*radius;cout << "The area of a circle with radius " << radius << " is " << area << endl;
}
int main(){
float r;r = 3;calculate_area(r);calculate_area(2.5);calculate_area(r/2);
return 0;}
CS201 Introduction to Computing @ Sabancı University 12
Area calculation using parameterized function
#include <iostream>using namespace std;// area calculation program that employs functions
void calculate_area (float radius){
float area;
area = 3.14*radius*radius;cout << "The area of a circle with radius " << radius << " is " << area << endl;
}
int main(){
float r;r = 3;calculate_area(r);calculate_area(2.5);calculate_area(r/2);
return 0;}
radius is 3
The area of a circle with radius 3 is 28.26
Output Screen
CS201 Introduction to Computing @ Sabancı University 13
Area calculation using parameterized function
#include <iostream>using namespace std;// area calculation program that employs functions
void calculate_area (float radius){
float area;
area = 3.14*radius*radius;cout << "The area of a circle with radius " << radius << " is " << area << endl;
}
int main(){
float r;r = 3;calculate_area(r);calculate_area(2.5);calculate_area(r/2);
return 0;}
radius is 2.5
The area of a circle with radius 3 is 28.26
Output Screen
The area of a circle with radius 2.5 is 19.625
CS201 Introduction to Computing @ Sabancı University 14
Area calculation using parameterized function
#include <iostream>using namespace std;// area calculation program that employs functions
void calculate_area (float radius){
float area;
area = 3.14*radius*radius;cout << "The area of a circle with radius " << radius << " is " << area << endl;
}
int main(){
float r;r = 3;calculate_area(r);calculate_area(2.5);calculate_area(r/2);
return 0;}
radius is 1.5
The area of a circle with radius 3 is 28.26
Output Screen
The area of a circle with radius 2.5 is 19.625
The area of a circle with radius 1.5 is 7.065
CS201 Introduction to Computing @ Sabancı University 15
Functions with Parameters (continued) 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 parameters 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
we will see examples later on Functions may call other functions (have seen in the totem
example and will see in the next example)
CS201 Introduction to Computing @ Sabancı University 16
Functions with Parameters (continued) Parameters versus Local Variables
Parameters and defined and used locally, but their initial value comes from the caller function via arguments
Local variables are defined and used in the function locally• But the 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_area function
• area is a local variable since we do not pass its initial value from main• radius is a parameter since we need to pass its initial value from main
Unnecessary parameters may cause problems and grade reduction (for homework)
CS201 Introduction to Computing @ Sabancı University 17
Old McDonald’s Farm Aim 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 hereAnd a moo moo thereHere a moo, there a moo, everywhere a moo mooOld 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 cat, Ee-igh, Ee-igh, oh!With a meow meow hereAnd a meow meow thereHere a meow, there a meow, everywhere a meow meow Old MacDonald had a farm, Ee-igh, Ee-igh, oh!
CS201 Introduction to Computing @ Sabancı University 18
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
in the main program call the verse function with several animal and noise arguments
CS201 Introduction to Computing @ Sabancı University 19
Old McDonald’s Farm (Program) See oldmac2.cpp Remarks
functions call functions• Refrain calls EiEio• Verse calls Refrain
Verse has two parameters• therefore it is called using two arguments –first one is for
animal, second is for noise• order of arguments is important
animal is used as parameter 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”. Let’s do and see.
Can we input animal and noise? of course yes (will do next)
CS201 Introduction to Computing @ Sabancı University 20
Programs that Respond to Input Programs without input always give the same results
values are hardcoded For new values
change the program, compile and run again• not a good programming practice
Allow the user to input values that generate output• from keyboard, using cin • we did this in the first circle area calculation program
Sequential model of programming: input, process, output Input: information provided from the user (outside
world) Process: Information is processed Output: display the result
CS201 Introduction to Computing @ Sabancı University 21
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: sheepEnter noise that a sheep makes: baahOld MacDonald had a farm, Ee-igh, Ee-igh, oh!And on his farm he had a sheep, Ee-igh, ee-igh, oh!With a baah baah hereAnd a baah baah thereHere a baah, there a baah, everywhere a baah baahOld 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
CS201 Introduction to Computing @ Sabancı University 22
Mac Donald’s farm revisited
// 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;}
CS201 Introduction to Computing @ Sabancı University 23
Analysis of the Run1. input value “sheep” is stored in variable animal
2. input value “baah” is stored in variable noise
3. “sheep” and “baah” values are passed to function Verse as arguments as well as used in cout in main
CS201 Introduction to Computing @ Sabancı University 24
Variables (review from previous lectures) Variables are used to store values in memory
memory locations that are accessed using a name in the program
Each variable has a type, a name (identifier), and a value
Methods to give values to variables Assignment, using = Input, using cin
Definition: type variable_names_separated_by_comma;
CS201 Introduction to Computing @ Sabancı University 25
Where to define variables You can define variables anywhere within a function
provided that it is defined before the first use Two common conventions for the place 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 that they’re used: { cout << "enter animal "; string animal; cin >> animal; cout << "enter noise a " << animal << " makes "; string noise; cin >> noise; }
CS201 Introduction to Computing @ Sabancı University 26
Where to define variables NO GLOBAL VARIABLES A global variable is a variable defined outside the
function bodies 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 homework and exams,
your grade will be reduced! At the end of the course, I will formally teach global
variable concept. After that, you will need to know what global variable is and apply them
whenever you are asked for, but not without permission!
CS201 Introduction to Computing @ Sabancı University 27
Variable Initialization Variables have garbage (junk values) until
they are assigned a value using assignment operatormyint = 5;
or an input is stored into them (using cin statement)cin >> myint;
Variables must be given a value before you refer to its value 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 declarationint myint = 5;
After initialization, you may change the value stored in a variable several times that is why they are named as “variable”
CS201 Introduction to Computing @ Sabancı University 28
Scope of a Variable and Parameter
Not explained in the book in this way Complex rules. Now I give a simple version! 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 Detailed scope rules will be given later in this course
CS201 Introduction to Computing @ Sabancı University 29
Reading Assignment
Section 3.3 Case Study: Pizza Slices Similar to circle area calculation program Run the program pizza.cpp