+ All Categories
Home > Documents > CS 31 Intro to Programming UCLA C++

CS 31 Intro to Programming UCLA C++

Date post: 24-Dec-2015
Category:
Upload: manuel-sosaeta
View: 24 times
Download: 1 times
Share this document with a friend
Description:
In C++
Popular Tags:
42
Wednesday, Oct 6 th You’re gonna learn how to program today! (If you’ve programmed before, then ponder on this brain teaser to relieve your boredom). main() { int a = 5, b = 10; a = <fill this in>; b = <fill this in>; a = <fill this in>; } Using only addition and subtraction, fill in the blanks to swap the values of a and b…
Transcript
Page 1: CS 31 Intro to Programming UCLA C++

Wednesday, Oct 6th

You’re gonna learn how to program today!

(If you’ve programmed before, then ponder on this brain teaser to relieve your

boredom). main(){ int a = 5, b = 10;

a = <fill this in>;

b = <fill this in>;

a = <fill this in>; }

Using only addition and subtraction, fill in the blanks to swap the

values of a and b…

Page 2: CS 31 Intro to Programming UCLA C++

Agenda

• Learn about the programming process

• Questions about Project #1?• Our first C++ programs:

– Learn how to print to the screen– Learn about variables– Learn about mathematical

operators in C++– Learn how to input more than

one number at a time

Page 3: CS 31 Intro to Programming UCLA C++

The Programming ProcessDesign your

program

Edit your program

Compileyour

program

Run andtest your program

Does it compile without errors?Yes

No

Does it work correctly?NoYes

Page 4: CS 31 Intro to Programming UCLA C++

Design

Goal: Figure out how your program is going to work before you write a single line of

logic.

Things to think about:

• What is the problem you’re trying to solve?• What are your requirements? • What are the main tasks required to solve the problem?• How should you organize your program to best address the problem?

Page 5: CS 31 Intro to Programming UCLA C++

Editing Your ProgramGoal: Type in your program source code in a

text editor, word processor or in Visual Studio.

#include <iostream>void main(void){ std::cout << “GO BRUINS!";}

Things to think about:

• Using proper programming style• Make your program easy to read!• Using proper syntax and semantics

Page 6: CS 31 Intro to Programming UCLA C++

Syntax vs. Semantics

Syntax: When you write a program, you have to follow the programming language’s grammar or syntax rules.

If your program has syntax errors, the compiler is unable to translate it into machine language.

Semantics: A program’s logic and behavior when running are called its semantics.

A program with bad semantics (bad logic) will compile and run, but has the wrong behavior.

Page 7: CS 31 Intro to Programming UCLA C++

Syntax Errors vs. Semantic Errors

Question: which is which?

  UCLA students, is smartest, compared of USC students?

 

USC students are smarter than UCLA students.

Page 8: CS 31 Intro to Programming UCLA C++

Compiling your ProgramGoal: Translate your program from C++ source

code into a working program (into machine

code)!

#include <iostream>void main(void){ std::cout << “GO BRUINS!";}

571191046993 …

MyProg.exe

Page 9: CS 31 Intro to Programming UCLA C++

Compiling your ProgramGoal: Translate your program from C++

source code into a working program!

MyProg

GO BRUINS!

(What’s happening under the hood is a bit more

complicated than this, but that’s

the general idea…)

Page 10: CS 31 Intro to Programming UCLA C++

Running and Testing Your Program

Goal: Make sure you don’t have any semantic errors in your program logic.

Things to do:

• Test your program to make sure it works• Make sure your program works properly even if the user doesn’t use it correctly.• Fix any problems you find and then repeat needed testing.

Page 11: CS 31 Intro to Programming UCLA C++

Our First C++ Programs

Goal: Learn about C++ by working through simple examples.

Things to think about:

• Learn proper C++ syntax• Learn proper programming style• Learn how to accomplish certain tasks:

• Printing to the screen• Inputting data from the user• Making decisions

• Learn how to spot errors

Page 12: CS 31 Intro to Programming UCLA C++

// Our first C++ program: Hello world! #include <iostream> int main(void){

std::cout << "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";

 } 

Hello world…Goodbye!

Page 13: CS 31 Intro to Programming UCLA C++

// Our first C++ program: Hello world! #include <iostream> int main(void){

std::cout << "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";

 } 

Everything following the // until the end of the line is called a “comment” and is totally ignored by the compiler.

You can also use the /* comment */ notation.

/* a comment */

Comments are used by the programmer to document how their program works.

Page 14: CS 31 Intro to Programming UCLA C++

// Our first C++ program: Hello world! #include <iostream> int main(void){

std::cout << "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";

 } 

The #include<filename> command basically means: “Hey compiler, the file called “filename” contains important information you’ll need to compile my program.”

iostream is a special file that contains information on how to print information to the computer screen.

#include <cmath>

iostream

Similarly, you could #include<cmath> if your program used math operations like sin/cosine/sqrt.

std::cout << “The cosine of 52 is “ << cos(52);

Page 15: CS 31 Intro to Programming UCLA C++

// Our first C++ program: Hello world! #include <iostream> int main(void){

std::cout << "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";

 } 

All C++ programs have a “main function.”

main function header

main function

body

When you run your program, the computer executes the first instruction in the main program, then the second instruction, etc.

When the computer reaches the last line in the main function, your program is finished.

Page 16: CS 31 Intro to Programming UCLA C++

// Our first C++ program: Hello world! #include <iostream> int main(void){

std::cout << "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";

 } 

Each line in the main function, separated by a semicolon ; is called a statement.

A statement can span one or more lines, as required.

std::cout << “Goodbye!"; // this is just fine!

A statement performs one or more operations in a program.Good style hint: indent your statements with a tab.

#include <iostream>int main(void){std::cout<< "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";return(0);}

Page 17: CS 31 Intro to Programming UCLA C++

// Our first C++ program: Hello world! #include <iostream> int main(void){

std::cout << "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";

 } 

To print text to the screen, use the std::cout command. std::cout prints the data following the << to the screen.

Any text enclosed in double “quotation marks” is called a string.

Think of this line as: Send “Hello” to the screen (i.e. cout).

Page 18: CS 31 Intro to Programming UCLA C++

// Our first C++ program: Hello world! #include <iostream> int main(void){

std::cout << "Hello ";std::cout << “world...\n ";std::cout << “Goodbye!";

 

Hello world…Goodbye!

The \n means “newline” and causes the computer to stop printing text on the current line, and advance to the next line.

Page 19: CS 31 Intro to Programming UCLA C++

// What’s it going to print??? 

#include <iostream>

 int main(void){

std::cout << "Hello world!\n";std::cout

<< "Good\nbye!\n"; } Hello world!

Goodbye!

You may sometimes see the: “using namespace std;” command in a program.

using namespace std;

This lets you remove the std:: from your cout statements.

(This makes your C++ code look

prettier)

Page 20: CS 31 Intro to Programming UCLA C++

// printing to the screen with other escape codes #include <iostream> int main(void){

std::cout << "Hello world!\n";std::cout << "Good\tbye!\n";

 }

Just like \n, there are other escape codes, such as \t and \a. Can anyone guess what these do?

Question: How can you print out a backslash in a string? How can you print out a quotation mark?

Your C++ program is case sensitive. So be careful!

STD::cout << "Hello world!\n"; // SYNTAX ERROR!

Page 21: CS 31 Intro to Programming UCLA C++

#include <iostream> int main(void){ int years_old, num_hairs;  std::cout <<"How old’s Carey?"; std::cin >> years_old;  num_hairs = 100 - years_old;  std::cout << “Carey has " << num_hairs << " hairs left." << std::endl; }

How old’s Carey? 33Carey has 67 hairs left.

years_old

num_hairs

33

100 - 33

67

Sometimes you need to store data you get from the user in your program.

A variable is a reserved slot of the computer’s memory that can be used to hold data. You must declare a variable before you use it in your program.

The std::cin command is used to get information from the user and store it into a variable.

Page 22: CS 31 Intro to Programming UCLA C++

How old’s Carey? 33Carey has 67 hairs left.

years_old

num_hairs

3367

#include <iostream> int main(void){ int years_old, num_hairs;  std::cout <<"How old’s Carey?"; std::cin >> years_old;  num_hairs = 100 - years_old;  std::cout << “Carey has " << num_hairs << " hairs left." << std::endl; }

std::endl is another way to write “\n”

Notice how you can print multiple items out by using more than one set of << in a single std::cout command.

Variables are case sensitive too! Make sure you use the same case when you declare your variable as when you use it in your program!

Num_Hairs

Page 23: CS 31 Intro to Programming UCLA C++

years_old

num_hairs

#include <iostream> int main(void){ int years_old, num_hairs;  std::cout <<"How old’s Carey?"; std::cin >> years_old;  num_hairs = 100 - years_old;  std::cout << “Carey has " << num_hairs << " hairs left." << std::endl; }

When you declare a new variable, it has a random value stored in it until you assign one.

Never assume a variable is initialized automatically!

?

?

-7269

479

How old’s Carey? 33

33

Page 24: CS 31 Intro to Programming UCLA C++

More on Variables We must explicitly declare variables to hold data for our

program. This reserves memory in the computer for them.

int main(void){

int boogies; // this “declares” a new integer variable

boogies = 100; std::cout << “You got “ << boogies << “ boogers.”;

boogies ???

To declare a variable, we first specify the variable’s type, and then its name.

If we like, we can define multiple variables at the same time.

int goblins, goobers, burps;

And we can initialize variables when we declare them if we like.

int noogie = 7, farts;

Page 25: CS 31 Intro to Programming UCLA C++

Variable Names 1. Variable names may have letters,

numbers and underscores _’s but no other symbols.

2. Variable names may not begin with a number.

3. Variable names are case sensitive.aGoodVariable15Amount$Made31CSROSTERANICE*VARIABLENum Goats_EarWaxVolume

Good or bad?

Page 26: CS 31 Intro to Programming UCLA C++

Types of Variables

In the previous example, we declared two integer variables:#include <iostream> int main(void){ int years_old, num_hairs; // two integers  std::cout <<"How old’s Carey?"; std::cin >> years_old;  num_hairs = 100 - years_old;  std::cout << “Carey has " << num_hairs << " hairs left." << std::endl; }

An integer (int) variable can hold:

• both positive and negative whole numbers

• any value between -2147483648 to 2147483647Now lets learn about other types of variables we

can use in our programs…

Page 27: CS 31 Intro to Programming UCLA C++

Floating-point VariablesAs we’ve seen,

integer variables can only hold whole

number values.

What if we want to perform

calculations with real numbers?

If you want to store real values in your program, you need to use the float variable

type.int main(void){ float pi; // float variables can hold a real #

pi = 3.14159;

std::cout << “PI times 10 is: “ << pi*10;

}

pi

3.14159

A floating point (float) variable can hold:

• both positive and negative real numbers

• any value between ± 3.4 * 10-38 to ± 3.4 * 1038

Page 28: CS 31 Intro to Programming UCLA C++

Unsigned Variables

In some cases, we want an integer variable to hold only non-negative values.

In this case, we use an unsigned variable.

int main(void){ unsigned int age; // ages can’t be negative!

age = 10;

All you do is place the word “unsigned” in front of the standard type name.

-5; // ERROR!

Page 29: CS 31 Intro to Programming UCLA C++

Unsigned Variables

int main(void){ unsigned int age;

age = 10;

An unsigned integer (unsigned int) variable can hold:

• both zero or positive whole numbers∙ any value between 0 and 4294967296

The unsigned keyword can only be used with whole-number style variables.

float age; // ERROR!

Page 30: CS 31 Intro to Programming UCLA C++

Other Variable Typeslong Variables long variables are the same as int variables on PCs/MACs.

int main(void){

short Variables A short variable is basically a small int and can hold values between -32768 to 32767

unsigned short variables can hold values between 0 and 65535.

long careysEgo; // same as int careysEgo;unsigned long smallbergsAge;

short careysIQ = 32766;unsigned short smallbergsWeight = 65500;

Page 31: CS 31 Intro to Programming UCLA C++

Other Variable Types

double Variables double variables are basically extremely precise float variables. They hold really big values with high precision:

± 1.7 * 10-308 to ± 1.7 * 10308int main(void){

char zits = 120; unsigned char grits = 254;

char Variables char variables are extremely small integer variables. They can hold values between -128 to 127.

unsigned char variables can hold values between 0 and 255.

double big = 3.925e123; // 3.925123

Page 32: CS 31 Intro to Programming UCLA C++

Each Variable Has A…

Type: Describes the type of data a variable holds (e.g. an int, char, short, float, or double).

Size: Each variable occupies a certain number of slots in the computer’s memory…

Value: Every variable has a value. All variables start with a random value until they are initialized.

Name: Every variable has a name that the programmer can use to reference it.

Page 33: CS 31 Intro to Programming UCLA C++

The computer’s memory (RAM) is split

up into slots called bytes.

Every variable occupies one or more slots

(bytes).

char 1 byte short 2 bytes int and long 4 bytes float 4 bytes double 8 bytes

Variables Take Up Space!

} 1 byte

Page 34: CS 31 Intro to Programming UCLA C++

Variables Take Up Space!

char 1 byte short 2 bytes int and long 4 bytes float 4 bytes double 8 bytesint main(void){

short sh = 1927;

float fl = 3.14159;

char ch = 27;

...

sh 19

27

fl 3.1

4159

ch 27

Page 35: CS 31 Intro to Programming UCLA C++

Expressions are evaluated from left to right according to standard precedence rules.

You can use the standard math operators in C++.

// learn how to use math operations in C++#include <iostream> 

int main(void){ int hmm, b; 

hmm = 1 + 2 * 3; std::cout << "result: "<<hmm<< "\n"; hmm = (1 + 2) * 3; std::cout << "result: "<<hmm<< "\n"; 

// how about a unary minus? hmm = -3 * 5; std::cout << "result: "<<hmm<< "\n";}

Order of Operations

1. Parentheses ( and )

2. Unary minus (e.g. –5)

3. *, / and %

4. + and -

Using Math Operators in C++

Page 36: CS 31 Intro to Programming UCLA C++

This holds true for char, int, long and short variables.

Integer Division in C++

Question: What is 20 / 7?

)7 202

14

6

with a remainder of 6.

When you divide two integer numbers, C++ only gives you the whole number result.

int main(void){ int dogs, biscuits, biscuits_per_dog;

dogs = 7; biscuits = 20;

biscuits_per_dog = biscuits / dogs;

std::cout << biscuits_per_dog;

dogs biscuits

biscuits_per_dog

7

20

2

Page 37: CS 31 Intro to Programming UCLA C++

#include <iostream> 

int main(void){ int hmm, b; 

hmm = 7 / 3; std::cout << "result #1: "<<hmm<< "\n";

hmm = 10 * 5 / 3; std::cout << "result #2: "<<hmm<< "\n";

hmm = 5 / 6 * 100; std::cout << "result #3: "<<hmm<< "\n"; // one last thing... hmm = 0; b = 10 / hmm; std::cout << "result #4: "<<b<<"\n";}

Integer Division in C++

Questions:• What does each line

print?• What happens on the last

line?

Page 38: CS 31 Intro to Programming UCLA C++

Instead of using the / you should use a % sign.

Modulo Division in C++

Question: What is the remainder of 20 / 7?

)7 202

14

6

with a remainder of 6.

C++ allows you to use the modulo operator to compute just the remainder part of an

integer division.

int main(void){ int dogs, biscuits, biscuits_left_over;

dogs = 7; biscuits = 20;

biscuits_left_over = biscuits % dogs;

std::cout << biscuits_left_over;

dogs biscuits

biscuits_left_over

7

20

6

Page 39: CS 31 Intro to Programming UCLA C++

// learning the modulo operator #include <iostream> int main(void){ int barf;  barf = 10 % 3; std::cout << "barf: "<<barf<< "\n";  barf = 6 % 18; // be careful! std::cout << "barf: "<<barf<< "\n";  barf = 6 % 0; // hmmmmm!?!? std::cout << "barf: "<<barf<< "\n";  return(0);}

Question:• If we do "N % A", what must

the result be smaller than?

The modulo operator is used to compute the remainder of a division operation.

Page 40: CS 31 Intro to Programming UCLA C++

#include <iostream> 

int main(void){ float hmm; 

hmm = 5.0 / 2.0; std::cout << "result #1: "<<hmm<< "\n";

hmm = 5 / 2; // careful!!! std::cout << "result #2: "<<hmm<< "\n";

hmm = 5.0 / 10.0 * 4.0; std::cout << "result #3: "<<hmm<< "\n";}

Floating Point Division in C++

If you divide two floating point numbers, and store the result in a float or double variable,

you will get a real valued result.

Page 41: CS 31 Intro to Programming UCLA C++

#include <iostream> 

int main(void){ int earWax = 10;

earWax = earWax + 5;

cout << “You have “ << earWax << “ gallons of earwax”;}

Assigning a Variable to Itself

If you’re new to programming, the blue line below may be a bit confusing…

earWax 10

How does this work?

First, C++ evaluates everything to the right of the equal

sign.

10

+ 5

15

Next, C++ stores the result in the variable specified to the left of

the equal sign.

15

Page 42: CS 31 Intro to Programming UCLA C++

 

#include < ... >#include < ... > 

int main(void){ 1. Declare your variable: this

reserves memory cells for your program’s data

 

2. One or more executable statements, follow each by a semicolon ;

 

}

Structure of a C++ Program


Recommended