C++ Programming Basics
Agenda
Hardware Basics The IDE
My First Program
Its all G(r)eek to me
Anatomy of a Computer
Memory Output
ALU Control Input
The CPU uses machine language
Compilers to the Rescue!
High level languages like C++ allows writing code that is easier to understand and
universally works on any CPU. circle=2.0*radius*pi;
Agenda
Hardware Basics The IDE
My First Program
Its all G(r)eek to me
THE MECHANICS OF WRITING
A PROGRAM
1. Editing -- Writing a program
2. Compiling -- Translating from C++ into machine language 3. Linking -- Combining your program with other libraries 4. Running – Letting the computer execute a program
5. Debugging – Running step by step through a program searching for mistakes
Agenda
Hardware Basics The IDE
My First Program Its all G(r)eek to me
Hello World !
Lets start off the traditional way
Program that prints out “Hello World” on your output console (your screen)
Steps
1. Create new source file 2. Write the code
3. Create a workspace (only in MSVC++) 4. Compile
5. Link
Agenda
Hardware Basics The IDE
My First Program
Its all G(r)eek to me
It’s all G(r)eek to me
… actually, its C++
20,000 ft. above sea level
#include <iostream> using namespace std; int main()
{
// This is my first program
cout << "Hello World" << endl; system("pause");
20,000 leagues under the sea
#include <iostream>
Actually includes some information into your code
Contains some definitions that are needed for your code
22,000 leagues under the sea
using namespace std;
This line refers to a set of standard object name definitions
… deeper….
int main()
• This is the piece of code (function) that is operated on first when a program is executed
• What’s a function ???
… even deeper….
//This is my first program
• This is a comment you write to yourself • Useful when writing large programs
… and deeper…..
Output operator
cout << “Hi”<<endl;
cout is the console monitor (your display)
<< is the output operator. Use to chain together your output message.
“Hi”is a string literal
… getting sleepy?…..
For the Bloodshed environment…Hold the display open so you can read it
(pressing a key will continue)
system("pause");
Finish up this program, return a 0 to operating system (everything ended OK)
… and even deeper ….
{} delineates the code block
Other types of cout statement
cout<< “ my age is” <<endl << 39<<endl; cout<< “ my age is 39”;
cout<< “ what’s your’s”; Escape with \
Tom’s All Purpose Program Shell
#include <iostream> using namespace std; int main()
{
// Your code here ...
system("pause"); return 0;
}
You Do It
Modify your hello world program to print your name, address and phone number (COULD BE FAKE!) on three lines:
Tom Rebold
1600 Pennsylvania Ave 123-456-7890
Lets get moving…..
We’ll learn as we proceed
You’ll be saying “Aha!” or “Oho!” when you hear these terms again
What more ?
Variables and Declarations
Variables represent storage locations in the computer’s memory
variable = expression
Assignment is from right to left
n = 5;
Using int Variables
int main() { int m,n; m = 44; cout << “m = “ << m; n = m + 33;Clearing the haze
int m;
m
int
Want more ?
User Input with
cin
How shall I feed in data ?
Remember cout ?
Meet cin
cin >> m;
User Input with
cin
int main() {
cout << "Enter the value of m:"; cin >> m;
User Input with
cin
int main() {
User Input with
cin
int main() {
int m;
cout << "Enter the value of m:"; cin >> m;
Your turn ()
1. from hello.cpp File>SaveAs age.cpp
2. Delete all the cout statements. Add lines to: a) Declare a variable called age
b) Display a message asking for data (such as “tell me your age”)
c) read the data into age
That’s a wrap !
What we learned so far:
How to write a basic C++ program The structure of a program
Displaying to the console (cout) Variables
C++ Programming Basics
Agenda
Review
An Intermediate Program
Making a Program Interactive Assignment Statements
Standard Program Structure File output
Review –Identify each piece
#include <iostream> using namespace std; int main()
{
// this program stores data in a variable
int m;
cout << “Enter the value of m:”; cin >> m;
cout << “m = “ << m << endl; system(“pause”);
Variables and Assignments
Variables are like small blackboards
We can write a number on them We can change the number
We can erase the number
C++ variables are names for memory locations
We can write a value in them
Review –what does this show?
int x;
x=6;
x=8;
Identifiers
Variable names are called identifiers Choosing variable names
Use meaningful names that represent data to be stored
First character must be
• a letter
• the underscore character _
Remaining characters must be
• letters • Numbers
Which identifiers are legal?
feet Average score
1993tax Average_score
Sum Average.score
Keywords
Keywords (also called reserved words)
Are used by the C++ language
Must be used as they are defined in the programming language
Cannot be used as identifiers Examples (75 altogether):
Declaring Variables
Before use, variables must be declared
Tells the compiler the type of data to store Examples: int one_weight, total_weight;
int represents whole numbers • Could store 1, 4, -345, etc.
Declaring Variables
(Part 2)int main() {
int score1, score2, sum;
cin>> … etc … sum=score1+score2;
… etc …
Declaring Variables
(Part 3)Declaration syntax:
Type_name Variable_1 , Variable_2, . . . ;
Declaration Examples:
int m_score, total_score; float moon_distance;
int age, num_students; char grade;
Agenda
Review
An Intermediate Program Making a Program Interactive Arithmetic
An intermediate C++ program:
// height.cpp
// Convert height in feet to inches. #include <iostream>
using namespace std; int main()
{
int feet, inches; feet = 6;
inches = feet * 12;
cout << "Height is " << inches << " in."; return 0;
Execution – what you see
Execution – what really happens
int feet, inches;
Execution – what really happens
cout << "Height is " << inches << " in.";
feet
int
72 inches
Agenda
Review
An Intermediate Program
Making a Program Interactive Arithmetic
Interactive Program
The previous program always runs exactly the same way (Height is 72 in)
We’d like to be able to “put in” the data we want to process
So we add two more lines. One asking for data:
cout<<“What is height in feet?”<<endl;
The other takes input:
An intermediate C++ program:
// height.cpp
// Convert height in feet to inches. #include <iostream>
using namespace std; int main()
{
int feet, inches;
cout << “What is height in feet?” << endl; //******** cin >> feet; //********
inches = feet * 12; cout << "Height is " << inches << " in."; return 0;
Basic Interactive Program
int main() {
1) Declare Variables
2) Ask (prompt) for data 3) Input data
4) Calculate result
A clever use of comments
Inside Lab1Basics.cpp are 10 programming problems…how to keep separate?
Remember // ignore to end of line
Another type of comment works in “blocks” :
/* start a block comment ignored
Combine the two…
/**** Problem 1 ********
// Here are your instructions
(space for your code)
Agenda
Review
An Intermediate Program
Making a Program Interactive Arithmetic
Assignment Statements
An assignment statement changes the value of a variable
total_weight = one_weight + number_of_bars;
• total_weight is set to the sum one_weight + number_of_bars
Assignment statements end with a semi-colon
The single variable to be changed is always on the left of the assignment operator ‘=‘
On the right of the assignment operator can be
• Constants -- age = 21;
Assignment Statements and Algebra
The ‘=‘ operator in C++ is not an equal sign
The following statement cannot be true in algebra
number_of_bars = number_of_bars + 3;
Initializing Variables
Declaring a variable does not give it a value
Giving a variable its first value is initializing the variable
Variables are initialized in assignment statements int miles, area; // declare the variables
miles = 26; // initialize the variable area=0; // initialize
Declaration and initialization can be combined int miles = 26, area = 0.0;
Arithmetic in C++
Basic operations + - * /
A = pr2 area=radius*radius*3.14; F = (v -a) force=(v-a)/(v+a);
(v+a)
Can you guess what is stored in x?
int a, b=3, c, x; a=b*2;
c=a+3; x=c-2;
Program flow is sequential (top to bottom)
a b c x
? 3 ? ?
6 3 ? ?
6 3 9 ?
Your turn…what is stored in x?
int a, b, c, x=3; a=2;
x=3+a; x=x+a;
Program flow is sequential, order matters!!
Agenda
Review
An Intermediate Program Arithmetic
Standard Program Structure
To solve most problems, your main() program will generally look like this (conceptually) 1. Declare variables for input, result and
intermediate data 2. Ask for data
3. Input data (cin) 4. Calculate result
Another interactive C++ program:
// Convert input number of nickels and dimes // to cents.
#include <iostream> using namespace std; int main()
{
int nickels, dimes, cents;
cout << "Enter number of nickels and dimes: "; cin >> nickels >> dimes;
cents = 5 * nickels + 10 * dimes; cout << nickels << " nickels and "
<< dimes << " dimes " << "= " << cents << " cents " << endl; return 0;
Your Turn
Run the previous code, found in Lab1Basics problem4, and verify it works correctly
Agenda
Review
An Intermediate Program Arithmetic
Syntax Errors
// errors.cpp #include <iostream> using namespace std; int main() { int n;cout << "Hello" << endl; N = 2;
cout << "n eqalls " << n cout << "So long << endl; system("pause");
return 0;
This program has 3 errors
Tracking them down
Syntax—
double click on the first error message it takes you to that line of code
Look at or above that line for possible errors Fix it and try again
Errors often create other errors
That’s a wrap !
What we learned today:
How to write an intermediate C++ program Standard program structure