CS 240: Data Structures Tuesday, June 5 th Programming Semantics, Software Life Cycle.

34
CS 240: Data CS 240: Data Structures Structures Tuesday, June 5 Tuesday, June 5 th th Programming Semantics, Programming Semantics, Software Life Cycle Software Life Cycle
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    214
  • download

    0

Transcript of CS 240: Data Structures Tuesday, June 5 th Programming Semantics, Software Life Cycle.

CS 240: Data StructuresCS 240: Data Structures

Tuesday, June 5Tuesday, June 5thth

Programming Semantics, Programming Semantics, Software Life CycleSoftware Life Cycle

Programming StructureProgramming Structure

To solve a programming problem:To solve a programming problem:Define the problemDefine the problemBreak it up into manageable partsBreak it up into manageable parts

Split up the problem into smaller tasksSplit up the problem into smaller tasksIf a task can be immediately realized, it is small If a task can be immediately realized, it is small

enoughenough

Code the partsCode the parts Integrate parts togetherIntegrate parts together

Converting ideas to code:Converting ideas to code:

Sometimes, the ideas are easy.Sometimes, the ideas are easy.Getting the code down – or approaching Getting the code down – or approaching

the problem – becomes the challenge.the problem – becomes the challenge.Most code revolves around the following Most code revolves around the following

statements:statements:

Common Code StructuresCommon Code Structures Control StructuresControl Structures

ifif elseelse

switchswitch whilewhile do { } while;do { } while; forfor

breakbreak continuecontinue returnreturn

Other manipulatorsOther manipulators

&& ** == ==== &&&& |||| static_cast<type>()static_cast<type>()

When do we use these things?When do we use these things?

ifif

Use if when you have a simple decision to make:Use if when you have a simple decision to make: Is a number negative?Is a number negative?

if(number < 0)if(number < 0)

{{

}}

If the user inputs “y”:If the user inputs “y”:if(userinput == “y”)if(userinput == “y”)

{{

}}

Remember:Number and userinput must be variables of an appropriate type!

ifif

In the previous two In the previous two examples, we run examples, we run additional code if the additional code if the condition is met.condition is met.

Consider this Consider this function:function:

If number is 4, what If number is 4, what makes this inefficient?makes this inefficient?

bool isPositive(int number)bool isPositive(int number)

{{

bool returnvalue = 0;bool returnvalue = 0;

if(number >= 0)if(number >= 0)

{{

returnvalue = 1;returnvalue = 1;

}}

if(number < 0)if(number < 0)

{{

returnvalue = 0;returnvalue = 0;

}}

return returnvalue;return returnvalue;

}}

ifif

Possibility #2Possibility #2 This is better, but we This is better, but we

can do more.can do more. At this point, what can At this point, what can

number be?number be? Then, we don’t need Then, we don’t need

the second if the second if statement!statement!

bool isPositive(int number)bool isPositive(int number){{

if(number >= 0)if(number >= 0){{

return 1;return 1;}}

if(number < 0)if(number < 0){{

return 0;return 0;}}//Compiler may complain if no return is at //Compiler may complain if no return is at the //end of this functionthe //end of this function

}}

ifif

Possibility #2 - Possibility #2 - RevisedRevised

This also gets rid of This also gets rid of the compiler warning.the compiler warning.

We can do this We can do this because of “control because of “control flow”. Let’s try this flow”. Let’s try this with the first code we with the first code we had.had.

bool isPositive(int number)bool isPositive(int number)

{{

if(number >= 0)if(number >= 0)

{{

return 1;return 1; //is positive//is positive

}}

return 0;return 0; //is negative//is negative

}}

ifif

Possibility #2 – Possibility #2 – Revision: Applied to Revision: Applied to earlier code.earlier code.

This doesn’t work the This doesn’t work the way we want!way we want!

What is wrong with What is wrong with this code?this code?

Why isn’t it a problem Why isn’t it a problem on the previous slide?on the previous slide?

bool isPositive(int number)bool isPositive(int number)

{{

bool returnvalue = 0;bool returnvalue = 0;

if(number >= 0)if(number >= 0)

{{

returnvalue = 1;returnvalue = 1;

}}

returnvalue = 0;returnvalue = 0;

return returnvalue;return returnvalue;

}}

If and elseIf and else If we examine what number If we examine what number

can be we know that number is can be we know that number is negative if it failed negative if it failed “if(number>=0)”“if(number>=0)”

Therefore, code after the if is Therefore, code after the if is only reached when we fail the only reached when we fail the first if.first if.

This is because “return 1” This is because “return 1” stops us from progressing stops us from progressing further. further.

Alternatively, we can use else.Alternatively, we can use else. The compiler won’t complain The compiler won’t complain

about a missing return in this about a missing return in this case.case.

bool isPositive(int number)bool isPositive(int number){{

if(number >= 0)if(number >= 0){{

return 1;return 1; //is positive//is positive}}elseelse{{

return 0;return 0; //is negative//is negative}}

}}

Multiple conditionsMultiple conditions

Be careful when testing multiple Be careful when testing multiple conditions:conditions:

If we wanted a program to describe the If we wanted a program to describe the temperature:temperature:

int tempinF;int tempinF;tempinF = gettemperature();tempinF = gettemperature();if(tempinF<32)if(tempinF<32){{

cout << “It is freezing!” <<endl;cout << “It is freezing!” <<endl;}}else if((tempinF>=32) && (tempinF <60))else if((tempinF>=32) && (tempinF <60)){{

cout << “It is cold!” <<endl;cout << “It is cold!” <<endl;}}else if((tempinF>=60) && (tempinF < 80))else if((tempinF>=60) && (tempinF < 80)){{

cout << “It is cozy!” <<endl;cout << “It is cozy!” <<endl;}}else if(tempinF>=80)else if(tempinF>=80){{

cout << “It is hot!” <<endl;cout << “It is hot!” <<endl;}}

//below 32, or [-,32)//below 32, or [-,32)

//32 -> 60, or [32,60)//32 -> 60, or [32,60)

//60 -> 80, or [60,80)//60 -> 80, or [60,80)

//greater than 80, or [80,-]//greater than 80, or [80,-]

Get used to having {} for your if and else Get used to having {} for your if and else and other relevant statements.and other relevant statements.

It makes it easier to read and quicker to It makes it easier to read and quicker to edit later.edit later.

It will make the code longer; but, you don’t It will make the code longer; but, you don’t need to worry about that.need to worry about that.This is part of the reason we separate code This is part of the reason we separate code

out into separate files.out into separate files.

switchswitch

Use switch when you have a bunch of Use switch when you have a bunch of equality decisions to make:equality decisions to make:

switch replaces a set of if statements.switch replaces a set of if statements.

switchswitch

int number;int number;cin >> number;cin >> number;if(number == 5)if(number == 5){{

cout << “apple” <<endl;cout << “apple” <<endl;}}if(number == 7)if(number == 7){{

cout << “tomato” <<endl;cout << “tomato” <<endl;}}if(number == 10)if(number == 10){{

cout << “biscuit” <<endl;cout << “biscuit” <<endl;}}

int number;int number;cin >> number;cin >> number;switch(number)switch(number){{case 5:case 5: cout << “apple” <<endl;cout << “apple” <<endl;

break;break;case 7:case 7: cout << “tomato” <<endl;cout << “tomato” <<endl;

break;break;case 10:case 10: cout << “biscuit” <<endl;cout << “biscuit” <<endl;

break;break;}}

Becomes

switchswitch

Switch isn’t terribly good for a range of Switch isn’t terribly good for a range of values.values.

If you had an if condition:If you had an if condition: if((number > 5) && (number < 10))if((number > 5) && (number < 10))How would you represent this with a switch?How would you represent this with a switch?

However, switch does have an equivalent However, switch does have an equivalent statement to “else”.statement to “else”.

switchswitchint number;int number;cin >> number;cin >> number;if(number == 5)if(number == 5){{

cout << “apple” <<endl;cout << “apple” <<endl;}}else if(number == 7)else if(number == 7){{

cout << “tomato” <<endl;cout << “tomato” <<endl;}}else if(number == 10)else if(number == 10){{

cout << “biscuit” <<endl;cout << “biscuit” <<endl;}}elseelse{{

cout << “Not food!” <<endl;cout << “Not food!” <<endl;}}

int number;int number;cin >> number;cin >> number;switch(number)switch(number){{case 5:case 5: cout << “apple” <<endl;cout << “apple” <<endl;

break;break;case 7:case 7: cout << “tomato” <<endl;cout << “tomato” <<endl;

break;break;case 10:case 10: cout << “biscuit” <<endl;cout << “biscuit” <<endl;

break;break;default:default: cout << “Not food!” <<endl;cout << “Not food!” <<endl;

break;break;}}

Becomes

The cases in a switch isolate the conditions from each other. (unless you forget “break;”

whilewhile

You use a while for the following:You use a while for the following:

Repeat code until some condition is metRepeat code until some condition is metRepeat code forever – need control flow to Repeat code forever – need control flow to

exitexit

Repeat forever:Repeat forever:

while(1)while(1){{

int number;int number;cin >> number;cin >> number;if(number == 10)if(number == 10)

break;break;}}

Repeat condition:Repeat condition:

int counter = 4;int counter = 4;while(counter>0)while(counter>0){{

int number;int number;cin >> number;cin >> number;counter--;counter--;

}}

A “while” is a different form of “for”A “while” is a different form of “for”

for vs whilefor vs while

int conditionvariable = initialvalue;int conditionvariable = initialvalue;while(condition)while(condition){{

//stuff//stuffchange(conditionvariable);change(conditionvariable);

}}

for(int conditionvariable=initialvalue;condition;change(conditionvariable))for(int conditionvariable=initialvalue;condition;change(conditionvariable)){{

//stuff//stuff}}

forfor

““For” is generally used to repeat code a For” is generally used to repeat code a certain number of times (infinite is certain number of times (infinite is possible), or iterate over some data.possible), or iterate over some data.

for(int i=0;i<10;i++)for(int i=0;i<10;i++){{

//stuff//stuff}}

for(;;)for(;;){{

//stuff//stuff}}

string userinput;string userinput;cin >> userinput;cin >> userinput;for(int i=0;i<userinput.size();i++)for(int i=0;i<userinput.size();i++){{

stuff(userinput[i]);stuff(userinput[i]);}}

Control Flow StatementsControl Flow Statements

continue;continue;Ends the current loop.Ends the current loop.

break;break;Terminate the current loop.Terminate the current loop.

return X;return X;Terminate the current function, return X to the Terminate the current function, return X to the

caller.caller.

Using continue:Using continue:

for(int i=0;i<10;i++)for(int i=0;i<10;i++)

{{

cout << i << endl;cout << i << endl;

cout << “I printed!” <<endl;cout << “I printed!” <<endl;

}}

for(int i=0;i<10;i++)for(int i=0;i<10;i++)

{{

cout << i << endl;cout << i << endl;

continue;continue;

cout << “I printed!” <<endl;cout << “I printed!” <<endl;

}}

Using continue:Using continue:

int i=0;int i=0;

while(i<10)while(i<10)

{{

cout << i << endl;cout << i << endl;

cout << “I printed!” <<endl;cout << “I printed!” <<endl;

i++;i++;

}}

int i=0;int i=0;

while(i<10)while(i<10)

{{

cout << i << endl;cout << i << endl;

continue;continue;

cout << “I printed!” <<endl;cout << “I printed!” <<endl;

i++;i++;

}}

This example has problems!

continue, breakcontinue, break

for(int i=0;i<10;i++)for(int i=0;i<10;i++){{

cout << i << endl;cout << i << endl;break;break;cout << “I printed!” <<endl;cout << “I printed!” <<endl;

}}

break leaves the loop.break leaves the loop.Continue and break are useful, just be Continue and break are useful, just be

careful when you use them.careful when you use them.

ReturnReturn

All functions return something (even void All functions return something (even void functions).functions).

Return is how we get stuff done!Return is how we get stuff done!A function completes some work and returns A function completes some work and returns

to its caller whatever it needs to return.to its caller whatever it needs to return.Return ends the current function, no other Return ends the current function, no other

code in that function will be executed!code in that function will be executed!

Some style issuesSome style issues

Indentation:Indentation:Provides readability of the code (required by Provides readability of the code (required by

some languages, namely Python)some languages, namely Python)Generally, 1 tab for each preceding { without Generally, 1 tab for each preceding { without

a }a }For clarity, you can put { and } alone on their For clarity, you can put { and } alone on their

own lineown lineA line with “}” has 1 less tab.A line with “}” has 1 less tab.

int main()int main(){{

int a;int a;{{

int b;int b;{{

int c;int c;{{

int d;int d;{{

int e;int e;}}int f;int f;{{

int g;int g;}}

}}}}int h;int h;{{

int I;int I;}}

}}}}

GlobalsGlobals

Globals aren’t all bad, but they are Globals aren’t all bad, but they are generally bad.generally bad.

There are some reasons to use globals There are some reasons to use globals that we won’t discuss here.that we won’t discuss here.

So, what is wrong with using a global So, what is wrong with using a global variable?variable?

How does it violate information hiding and How does it violate information hiding and encapsulation?encapsulation?

Pointers and referencePointers and reference

double *shorty;double *shorty;

double jimmy;double jimmy;

jimmy = 10;jimmy = 10;

shorty = &jimmy;shorty = &jimmy;

cout << shorty << endl;cout << shorty << endl;

What does this code What does this code output?output?

What does:What does:““cout << *shorty <<endl;”cout << *shorty <<endl;”

output?output?

Pointers and referencePointers and reference

double *shorty;double *shorty;

double jimmy;double jimmy;

jimmy = 10;jimmy = 10;

shorty = &jimmy;shorty = &jimmy;

cout << shorty << endl;cout << shorty << endl;

cout << *shorty << endl;cout << *shorty << endl;

Name: shortyValue: UninitializedLocation: Topmost!

Name: jimmyValue: Uninitialized

Location: The bottom

Name: jimmyValue: 10

Location: The Bottom

Name: shortyValue: The BottomLocation: Topmost!

Output: The Bottom

Output: 10

Other manipulatorsOther manipulators

======&&&& ||||static_cast<type>()static_cast<type>()