cs351 – week 1

28
CS351 – Week 1

Upload: nara

Post on 24-Feb-2016

30 views

Category:

Documents


0 download

DESCRIPTION

CS351 – Week 1. Topics. Native Types Memory representation Variable initialization declaration and allocation. Previous knowledge. How to select variable type (string, integer, float, or boolean ) Concept of capturing external files for use in programming (import or include) - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS351 – Week  1

CS351 – Week 1

Page 2: CS351 – Week  1

Topics

• Native Types• Memory representation• Variable initialization declaration and

allocation

Page 3: CS351 – Week  1

Previous knowledge

• How to select variable type (string, integer, float, or boolean)

• Concept of capturing external files for use in programming (import or include)

• Reading strings from standard input and parsing for numeric types if needed

• Converting and concatenating strings for output to screen

• Compute and save numerical results• Understanding of how to use a randomize function

Page 4: CS351 – Week  1

Objectives• Identify native types in C++ that are generally available• Understand how to declare, allocate and initialize a

variable• Declare variables in global or local scope• Create a basic C++ program that takes input from standard

in, computes a value and prints the value to the screen– Using constant values– Appropriately including needed files– Correctly coding the main signature– Using object for inputting and outputting values

Page 5: CS351 – Week  1

Including files

• Reusing code from a library– Python import math– C #include <math.h>

• Differences between C and Python?• How do you find what file has the function

you want?

Page 6: CS351 – Week  1

Computer memory

Conceptually the memory in a computer is very much like building lots laid out by lot number on a map of the streets of a city before any houses have been built.

Page 7: CS351 – Week  1

Computer memory

Lots can be used individually or as groupsAlthough memory has a basic unit, units can be used together to represent more complex data

Page 8: CS351 – Week  1

Data for variables

• “Jane Doe”• $475.24• 123-45-6789• 26 years of age• January

Page 9: CS351 – Week  1

Native types in C++• char – typically holds data encoded to represent written

character sets• integer types – whole numbers; can be signed or unsigned;

variations represent integers that use from 8 bits to 64 bits• float types – Stores numbers as fraction, exponent and sign;

not precise• boolean – true or false• Reference (pointer) – location that refers to another location• strings – usually as array of characters; have special handling

in the language; variable name refers to first location

Size of types is implementation dependentResources: http://en.wikipedia.org/wiki/Primitive_data_type, http://www.cplusplus.com/doc/tutorial/variables/

Page 10: CS351 – Week  1

Sample program

#include <iosteam>using namespace std;int main() {

cout<<“sizeof(int) is ”<<sizeof(int)<<“ bytes”<<endl;return 0;

}

Needed for cout and endl

Like java packagesWill discuss later

sizeof give the size in bytes of a type or variableNeeded since sizes vary

String literal

** What are the non-reserved words?

//size.cc

wget http:/bama.ua.edu/~anderson/size.cc

Page 11: CS351 – Week  1

Sample program

//size.cc#include <iosteam>using namespace std;int main() {

cout<<“sizeof(int) is ”<<sizeof(int)<<“ bytes”<<endl;

return 0;}

Page 12: CS351 – Week  1

Other general rules• Everything is case sensitive• These identifiers are

reserved (can’t be used as variable names)

What does it mean to be a reserved word?

http://en.cppreference.com/w/cpp/keyword

Page 13: CS351 – Week  1

Other syntax• semicolons are used to denote the end of a statement except

– after the #include statement– before a block

• Whitespace is not part of syntax //size.cc#include <iosteam>using namespace std;int main() {

cout<<“sizeof(int) is ”<<sizeof(int)<<“ bytes”<<endl;return 0;

}

Page 14: CS351 – Week  1

Programmed Example - 10 minWork in pairs (only pairs)

• Create a C++ program that prints out the size of the following variables– char– int– unsigned int– short– long– long long– float– double

• Fix w1ex1.cc so that it compiles and prints Hello World

Turning in programsPut both names at top Comments start with //cat <program name> |mailx –s “<lastname 1> <lastname2> Week # Date” [email protected]:cat w1ex1.cc |mailx –s “hong anderson Week 1 011414” [email protected]

Page 15: CS351 – Week  1

User input form keyboard//cin.cc#include <iosteam>using namespace std;int main() {

int value;cin >>value;cout<<“The user entered” <<value<<endl;cout<<“value * 3 ==<<” <<value*3<<endl;return 0;

}

Page 16: CS351 – Week  1

1st assignment – 5 minWork in pairs (only pairs)

• Fix w1ex2.cc so that it calculates the user’s mileage reimbursement

Turning in programsPut both names at top Comments start with //cat w1ex2.cc|mailx –s “Week 1: 011414” [email protected]

Page 17: CS351 – Week  1

C++ variables

• Declaration – Give variable a name and a type• Allocation – Identify location where variable

will be stored• Initialization – Set variable to appropriate

initial value

When this happens depends on scope…

Page 18: CS351 – Week  1

Variable scope

• A scope is a region of the program and broadly speaking there are three places, where variables can be declared:– Inside a function or a block which is called local

variables,– In the definition of function parameters which is

called formal parameters.– Outside of all functions which is called global

variables.

Page 19: CS351 – Week  1

C++ native type rules

• For local variables – <type> <identifier>; will only declare and allocate– <type> <identifier>=<value>; will declare, allocate

and initialize

Page 20: CS351 – Week  1

Local variable declaration#include <iostream> using namespace std; int main () {

// Local variable declaration: int a, b; int c;

// actual initialization a = 10; b = 20; c = a + b; cout << c; return 0;

}

Page 21: CS351 – Week  1

C++ native type rules

• For global declarations– <type> <identifier>; will declare, allocate and

initialize– <type> <identifier>=<value>; will declare,

allocate and initialize

Page 22: CS351 – Week  1

Mixed declaration#include <iostream> using namespace std; int g;

int main () { // Local variable declaration/allocation: int a, b;

// actual initialization a = 10; b = 20; g = a + b; cout << g; return 0;

}

cout <<a; //not guaranteed to be coherent

//mixed.cc

Page 23: CS351 – Week  1

Same variable in two scopes#include <iostream> using namespace std;

// Global variable declaration: int g = 20;

int main () { // Local variable declaration: int g = 10; cout << g; return 0;

}

Is this an error? If not, what prints here?

The enclosing scope has precedence

//twoscopes.cc

Page 24: CS351 – Week  1

Variable scope matters• If the scope of a variable is global (defined outside of braces),

– Can be used throughout a program (any function or code; even in other source files

– Memory is know to be needed at compile time– Compiler can designate a place for this memory as part of the program

setup• If a variable has scope local to some block

– it can only be used by statements in that block– compiler knows about it *but* we don’t know when functions will be

run; – To conserve memory, we reused the memory when it is not needed (out

of scope)

Memory in these two different cases are allocated in different places in the process space (program)

Page 25: CS351 – Week  1

C++ constants

• Uses const modifier in front of variable declaration• Value cannot be changed (compiler code will not

be generated)• Allows compiler to optimize access• Acts as a semantic check• Better than #define because the type is specified

(allows type checking by compiler)• #define is a macro; replaces text before compiling

Page 26: CS351 – Week  1

Constants#include <iostream> using namespace std;

// Global variable declaration: const int monthsInYear = 12;

int main () { cout<<monthsInYear<<endl;int age;cin>>age; //what happens if you put in a floating poitn number?cout<<“Entered age “<<age<<endl;monthsInYear=0; //error lineint totalMonths = monthsInYear*age;count<<totalMonths<<endl;return 0;

}

//const.cc

Page 27: CS351 – Week  1

C++ reference types

• Strings, objects, arrays, and structures are not native types but are reference types

• Composed of primitive types• Different rules for declaration, allocation and

initialization• For all types, if you initialize, you automatically

allocate

Page 28: CS351 – Week  1

2nd Assignment

• Fix w1ex3.cc so that it:– prints prompts for user input– prints out the number of weeks in the current month– Calculates the current weekly salary based on monthly

salary input and weeks in the current month• Write a program that takes an angle in degrees from

the user and converts it to radians. Use a constant for π

• Consult instructions for submission• Quiz online on this material posted Monday;

complete before class on Tuesday