You are on page 1of 42

Wednesday, Oct 6th

Youre gonna learn how to program today!


(If youve 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

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

The Programming Process


Design your
program
Edit your
program
Compile
your
program

No

No

Does it compile without errors?


Yes
Run and
test your
program
Does it work correctly?
Yes

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 youre 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?

Editing Your Program


Goal: 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

Syntax vs. Semantics


Syntax: When you write a program, you have to follow the
programming languages grammar or syntax rules.
If your program has syntax errors, the compiler is unable
to translate it into machine language.
Semantics: A programs 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.

Syntax Errors vs. Semantic


Errors
Question: which is which?
UCLA students, is smartest, compared of
USC students?
USC students are smarter than UCLA
students.

Compiling your Program


Goal: Translate your program from C++ source
code into a working program (into machine code)!

#include <iostream>
57119 10 4699 3
void main(void)
{
std::cout << GO BRUINS!";
}

MyProg.exe

Compiling your Program


Goal: Translate your program from C++ source
code into a working program!
MyProg

GO BRUINS!

(Whats
happening
under the
hood is a bit
more
complicated
than this,
but thats
the general
idea)

Running and Testing Your Program


Goal: Make sure you dont 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 doesnt use it correctly.
Fix any problems you find and then repeat
needed testing.

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

// Our first C++ program: Hello world!


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

Hello world
Goodbye!

// Our first C++ program: Hello world!


#include <iostream>
int main(void)
{
/* a comment */
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.
Comments are used by the programmer to document how
their program works.
You can also use the /* comment */ notation.

// Our first C++ program: Hello world!


#include <iostream>
#include <cmath>
int main(void)
{
std::cout << "Hello ";
std::cout << world...\n ";
std::cout << Goodbye!";
iostream
std::cout << The cosine of 52 is << cos(52);
}

The #include<filename> command basically means: Hey compiler,


the file called filename contains important information youll
need to compile my program.
iostream is a special file that contains information on how to print
information to the computer screen.
Similarly, you could #include<cmath> if your program used math
operations like sin/cosine/sqrt.

// Our first C++ program: Hello world!


#include <iostream>

main
int main(void)
{
std::cout << "Hello ";
std::cout << world...\n ";
std::cout << Goodbye!";

function header
main
function
body

All C++ programs have a main function.


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.

// Our first C++ program: Hello world!


#include <iostream>

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

int main(void)
{
std::cout << "Hello ";
std::cout << world...\n ";
std::cout << Goodbye!";
<< Goodbye!"; // this is just fine!
}

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


called a statement.
A statement can span one or more lines, as required.
A statement performs one or more operations in a program.
Good style hint: indent your statements with a tab.

// 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.
Think of this line as: Send Hello to the screen (i.e. cout).
Any text enclosed in double quotation marks is called a
string.

// Our first C++ program: Hello world!


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

The \n means newline


and causes the computer
to stop printing text on
the current line, and
advance to the next line.

Hello world
Goodbye!

// Whats it going to print???


#include <iostream>

using namespace std;

(This makes your


C++ code look
prettier)

int main(void)
{
std::cout << "Hello world!\n";
std::cout
<< "Good\nbye!\n";
}

You may sometimes see the:


using namespace std;
command in a program.
This lets you remove the std::
from your cout statements.

Hello world!
Good
bye!

// printing to the screen with other escape codes


#include <iostream>
int main(void)
{
STD::cout << "Hello world!\n"; // SYNTAX ERROR!
std::cout
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!

#include <iostream>

years_old

int main(void)
{
int years_old, num_hairs;

num_hairs

std::cout <<"How olds Carey?";


std::cin >> years_old;

100 - 33

33
67

How olds Carey? 33


Carey has 67 hairs
left.

num_hairs = 100 - years_old;


std::cout << Carey has "
<< num_hairs <<
" hairs left." << std::endl;
}
Sometimes you need to store data you get from the user in your program.
The
std::cin command is used to get information
A variable
a reserved
of theitcomputers
memory that can be used
from
theis user
andslot
store
into a variable.
to hold data. You must declare a variable before you use it in your
program.

#include <iostream>

years_old

int main(void)
{
int years_old, num_hairs;

num_hairs

std::cout <<"How olds Carey?";


std::cin >> years_old;

33
67

How olds Carey? 33


Carey has 67 hairs
left.

Num_Hairs = 100 - years_old;


num_hairs
std::cout << Carey has "
<< num_hairs <<
" hairs left." << std::endl;
}

std::endl are
is another
way to write
\n sure you use the
Variables
case sensitive
too! Make
same case when you declare your variable as when you use it
how you can print multiple items out by using more
inNotice
your program!
than one set of << in a single std::cout command.

#include <iostream>

years_old -7269
?
33

int main(void)
{
int years_old, num_hairs;

num_hairs 479
?

std::cout <<"How olds Carey?";


std::cin >> years_old;

How olds Carey? 33

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!

More on Variables
We must explicitly declare variables to hold data for our
program. This reserves memory in the computer for them.
To declare a variable, we first specify the variables
type, and then its name.
And
If we
welike,
can initialize
we can define
variables
multiple
whenvariables
we declare
at the
them
same
if we
time.
like.
int main(void)
{
int boogies;

boogies

???

// this declares a new integer variable

int goblins, goobers, burps;


int noogie = 7, farts;
boogies = 100;
std::cout << You got << boogies << boogers.;

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.

Good or bad?

aGoodVariable15
Amount$Made
31CSROSTER
ANICE*VARIABLE
Num Goats
_EarWaxVolume

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 olds Carey?";


Anstd::cin
integer (int)
variable can hold:
>> years_old;

both positive and negative whole numbers

any value between -2147483648 to 2147483647

num_hairs = 100 - years_old;

std::cout << Carey has "


<< num_hairs <<
Now
learn
about
types of
" lets
hairs
left."
<<other
std::endl;
}

variables we can
use in our programs

Floating-point Variables
A floating
point
(float) variable can hold:
As weve
seen,

integer
variables
positive can
and negativeWhat
real numbers
both
if we want to
only hold whole
any value between 3.4perform
* 10-38 tocalculations
3.4 * 1038
number values.
with real numbers?
If you want to store real values in your program,
you need to use the float variable type.
int main(void)
pi 3.14159
{
float pi; // float variables can hold a real #
pi = 3.14159;
std::cout << PI times 10 is: << pi*10;
}

Unsigned Variables
In some cases, we want an integer variable to hold only nonnegative values.
In this case, we use an unsigned variable.
All you do is place the word unsigned in front of the
standard type name.
int main(void)
{
unsigned int age;
age = 10;
-5;

// ERROR!

// ages cant be negative!

Unsigned Variables
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.

int main(void)
{
unsigned float
int
age;
age;
age = 10;

// ERROR!

Other Variable Types


long Variables
long variables are the same as int variables on PCs/MACs.
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.
int main(void)
{

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

short careysIQ = 32766;


unsigned short smallbergsWeight = 65500;

Other Variable Types


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 Variables
double variables are basically extremely precise float
variables. They hold really big values with high precision:

1.7 * 10-308 to 1.7 * 10308


int main(void)
{

char
unsigned char
double

zits = 120;
grits = 254;

big = 3.925e123;

// 3.925123

Each Variable Has A


Name: Every variable has a name that the
programmer can use to reference it.
Type: Describes the type of data a variable holds
(e.g. an int, char, short, float, or double).
Value: Every variable has a value. All variables start
with a random value until they are initialized.
Size: Each variable occupies a certain number of
slots in the computers memory

Variables Take Up Space!


The computers memory
(RAM) is split up into
slots called bytes.
Every variable occupies
one or more slots (bytes).
char
short
int and long
float
double

1 byte
2 bytes
4 bytes
4 bytes
8 bytes

} 1 byte

Variables Take Up Space!

sh
fl

int main(void)
{

float fl = 3.14159;
char
...

ch = 27;

ch

27

short sh = 1927;

3.14159

1 byte
2 bytes
4 bytes
4 bytes
8 bytes

1927

char
short
int and long
float
double

Using Math Operators in C++


You can use the standard math operators in C++.
Expressions are evaluated from left to right
according to standard precedence rules.
// 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 -

Integer Division in C++


Question: What is 20 / 7?
2 with a remainder of 6.
7 ) 20
14
6
int main(void)
dogs 7
{
When
you divide two integer numbers, C++ only
int dogs, biscuits, biscuits_per_dog; biscuits

gives
you the whole number result.
= 7;

dogs
biscuits = 20;

biscuits_per_dog

biscuits_per_dog = biscuits / dogs;

20
2

This holds
true for char, int, long and short variables.
std::cout << biscuits_per_dog;

Integer Division in C++


#include <iostream>
int main(void)
{
int hmm, b;

Questions:
What does each line print?

What happens on the last

line?

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";
}

Modulo Division in C++


Question: What is the remainder of 20 / 7?
2 with a remainder of 6.
7 ) 20
14
6

int main(void)
dogs 7
{
C++
allows you to use the modulo operator to
int dogs, biscuits, biscuits_left_over;
biscuits

20
compute
just
the
remainder
part
of
an
integer
dogs = 7;
biscuits_left_over
6
division.
biscuits = 20;
biscuits_left_over = biscuits

dogs;

Instead
of using the / you should use a % sign.
std::cout << biscuits_left_over;

// learning the modulo operator


#include <iostream>
int main(void)
{
int barf;

Question:
If we do "N % A", what must
the result be smaller than?

barf = 10 % 3;
std::cout << "barf: "<<barf<< "\n";
barf = 6 % 18;
std::cout << "barf: "<<barf<< "\n";

// be careful!

barf = 6 % 0;
std::cout << "barf: "<<barf<< "\n";

// hmmmmm!?!?

return(0);
}

The modulo operator is used to compute the


remainder of a division operation.

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.
#include <iostream>
int main(void)
{
float hmm;
hmm = 5.0 / 2.0;
std::cout << "result #1: "<<hmm<< "\n";
hmm = 5 / 2;
std::cout << "result #2: "<<hmm<< "\n";
hmm = 5.0 / 10.0 * 4.0;
std::cout << "result #3: "<<hmm<< "\n";
}

// careful!!!

Assigning a Variable to Itself


If youre new to programming, the blue line below
may be a bit confusing

#include <iostream>
int main(void)
{
int earWax = 10;

earWax
15

earWax = earWax + 5
5;
cout << You have << earWax
<< gallons of earwax;
}

10

How does
this work?
Next,
C++ stores
the
result
the
variable
First, in
C++
evaluates
specified
toto
the
left
of
everything
the
right
ofthe
theequal
equalsign.
sign.

Structure of a C++ Program


#include < ... >
#include < ... >
int main(void)
{
1. Declare your variable: this
reserves memory cells for your
programs data
2. One or more executable statements,
follow each by a semicolon ;

You might also like