Chapter 2: The Basics of C++...

23
Intro. to C\C++ Programming Programming - The process Understand the problem and requirements Design or select an algorithm to solve it Express (code) the algorithm in a programming language (e.g., C) Test and debug the program until it works and meets the requirements Hats I will wear this semester You Me Programming - The mechanics 1

Transcript of Chapter 2: The Basics of C++...

Chapter 2: The Basics of C++ Programming

Intro. to C\C++ Programming

Programming - The process

· Understand the problem and requirements

· Design or select an algorithm to solve it

· Express (code) the algorithm in a programming language (e.g., C)

· Test and debug the program until it works and meets the requirements

Hats I will wear this semester

You

Me

Programming - The mechanics

No one ever gets it right the first time.

Some kinds of bugs...

· Syntax errors

· Simple bugs

· Logic errors

· Solving the wrong problem

Types of files in a program

(or sections of a program- it depends on your style):

1. .c\.cpp file :

The .c\.cpp, or source file, contains your functions (programming procedures). This is the file you will primarily be writing in, because functions are the bulk of C\C++ coding.

2. .h file:

The .h, short for header, always accompanies a .cpp file.

It contains:

a. declarations of functions created in the .cpp file

b. variables used throughout the program

c. special self-created classes, which are explained later in the year

d. list of reserved command words that you use

e. a “library” of functions, variables, and other functions that you can use in your .c\.cpp file

The SIX sections of a program

Introduction/Name of Program

Include statements/Preprocessor commands

Global Variables

Function Prototypes

Main()

Functions

Part 1: Introduction/Name of Program

Your name, class, and program name and a brief description of the program

Example: //Ryan Dorrill

//C++ AB

//Blackjack

Part 2: Include statements/Preprocessor commands

Commands that include other library files, those files contain commands, functions, etc…

THERE IS A SPECIFIC ORDER THEY MUST RUN IN!!

#include // those that came with comp.

#include // those created by you

#include // those created by you

Example:

C Version

C++ Version

#include

scanf(…

printf(…

#include

using namespace std; // MANDITORY!!!

cin >>

cout <<

MORE ON THIS LATER!!!

Part 3: Globals

Variables that can be accessed by any part of the program.

easy to change since GLOBAL

you can make variables that are global, must make them unchangeable

· const int daysInYear = 365;

· define int monthsInYear = 12;

Part 4: Function Protocols

The declarations of your functions, these would go in a header file in more advanced programs. (Much like a table of Contents)

Examples: void display( );

int AddUp(num1,num2);

Part 5: Main program

The center of your program, where you call functions and display menus.

Example: void main( )

{ …… // WHERE EVERYTHING BEGINS AND ENDS!!!

Part 6: Functions

functions/procedures that help the MAIN program run.

Main calls these functions created here.

Creation of the MAIN()

intvoid

// opening

int main( ) // no void inside ( )’s{ // brace to open code block…

// closing

return 0;

} // brace to close code block// opening

void main( ) // no void inside ( )’s{ // brace to open code block…

// closing

} // brace to close code block

· The difference between the two is slight for now, later will be crucial

· void

· program returns NOTHING when completed (void … get it!!)

· int

· notice “return 0” at end – MUST HAVE· need to use if compiling using Linux system

· returns and actual ‘0’ when program is completed

Data types

Match the variables with their correct datatype. Take a WILD (not) guess.

Variable name and valueDatatype

??? myGPA = 3.79;float

??? myName = “Lupoli”;int (integer)

??? myIQ = 152;char (character)

??? myMiddleInitial = ‘V’String

Type

Examples/Definitions

int

int yards = 202;

a WHOLE number, ranging from -2147483647 to 2147483647

unsigned int

unsigned int feet = 6;

a WHOLE NON-NEGATIVE number ranging from 0 to 2147483647

short

short coordinate = -12;

a WHOLE number, ranging from -32767 to 32767

unsigned short

unsigned short attitude = 32,000;

a WHOLE NON-NEGATIVE number ranging from 0 to 32767

long

long debit = 10000000000;

a WHOLE number, ranging from -2^63 to 2^63-1

unsigned long

unsigned long population = 5000000000;

a WHOLE NON-NEGATIVE number ranging from 0 to 2^63-1

float

float GPA = 3.99;

a real number in a floating point representation

double

double mole = 1.2336483;

a double-precision real number in a floating point representation

long double

long double weight = 7.7493343658792749;

a extended-precision real number in a floating point representation

char

char choice = 'x';

ONE character, or a small INTEGER in the range from -128 to 127

boolean

bool found = true;

a Boolean value can either AND ONLY be true(1) or false(0)

· each variable of NO MATTER what type

· holds ONE value of that type

· variable name should MATCH what it is being used for

· cannot have a number as a first letter in it’s name

Input and Output

I/O stream

cin >>

cout <<

scanf

printf

Printing a Line of Text

C

C++

// Mr. Lupoli

// 1st program

#include

void main()

{

printf(“Welcome to C!\n”);

printf(“Welcome”);

printf(“to Mr. Lupoli’s Class”);

}

// Mr. Lupoli

// 1st program

#include

using namespace std;

void main()

{

cout << “Welcome to C!” << endl;

cout << “Welcome”;

cout << “to Mr. Lupoli’s Class”;

}

// draw what this would look like EXACTLY on a monitor

Difference/Substitutions

1.)#include

#include

2.)printf(

cout <<

3.)\n”

”<< endl;

Using printf/scanf and cout/cin

· to display to the screen

· C ( printf(

· C++ ( cout <<

· to read from the keyboard

· C ( scanf(

· C++ ( cin >>

C and C++ Versions using I/O

// declare your variables first!!!

int x = 10;

double y = 23.3;

char z = ‘A’;

short int a = 12;

long int b = 12857612554;

long double c = 2834892734892.23;

printf

scanf

print(“x is = %d \n”, x); // int

print(“y is = %f \n”, y); // double

print(“z is = %c \n”, z); // char

print(“a is = %hd \n”, a); // short int

print(“b is = %Ld \n”, b); // long int

print(“c is = % Lf\n”, c); // long double

printf(“X is: %d and Y is: %d\n”, x, y); \\ 2 displ

scanf(“%d”, &x); // int

scanf(“%f”, &y); // double

scanf(“%c”, &z); // char

scanf(“%hd”, &a); // short int

scanf(“%Ld”, &b); // long int

scanf(“%Lf”, &c); // long double

scanf(“%d %f”, &x, &y); // 2 done

cout <<

cin >>

cout << “x is = “ << x << endl; // int

cout << “y is = “ << y << endl; // double

cout << “z is = “ << z << endl; // char

cout << “a is = “ << a << endl; // short int

cout << “b is = “ << b << endl; // long int

cout << “c is = “ << c << endl; // long double

cout << “x is =“ << x << “ and y =“ << y << endl;

cin >> x; // int

cin >> y; // double

cin >> z; // char

cin >> a; // short int

cin >> b; // long int

cin >> c; // long double

cin >> x >> y; // 2 done

What is the difference between the 2 x’s??

· Things to notice

· both are vary similar

· on a scanf/cin, DO NOT USE \n or endl!!!

· in a scanf, make sure you have &variable

· BE CAREFUL WITH QUOTES!!!

· can use ‘\n’ in C++ version instead of << endl;

Input/Output Exercise

// Your name here

#include

using namespace std;

void main()

{

string name, address;

// declare ALL variables before you use them

// 1.) Create the CODE to LITERALLY display YOUR name, and address (No variables yet.)

// start below

2.) Create the CODE to ask for user’s first name and address, USE THE VARIABLES

// DECLARED FOR YOU ALREADY!! (hint: use cin>>)

// start below

// 3.) Create the code to display their name and address that THEY typed in. NOT yours!!

// start below

}

literal escape constants/command constants

- used with couting/printf

C/C++ Escape Sequences

\b – backspace

\t – tab

\a – audible alert

\v – vertical tab

\f – form feed

\\ – single backslash character

\n – new line

\” – double quote

\r – carriage return

\? – question mark

examples uses: (what will these display??)

cout << “Hi Class! \a” << endl;

cout << “Good Luck!!! \n”;

cout << “\t \t You’ll need it!!!” << endl;

Use of Comments

//

/* … code … */

// Mr. Lupoli

// Project 1

// 6/22/03

// Period 1

// ( “//”reserves REST of line for a // comment

// used for ONE line comments

void main()

{

int counterValue;// sentinel value

/*

Mr. Lupoli

Project 1

6/23/03

Period 1

*/

/*

“ /* ” reserves whole block until you end it with a “ */ “

used for MULTIPLE lined comments

*/

Why use comments?

· For notes

· to yourself

· to me!!

· For commenting out unfinished lines of code

· skipping unfinished functions

· To understand what the code is doing!!

· watch where you put them!!

Reserved Words

· case sensitive

· can not be used as variable or function names

· ex

cin >>

cout <<

auto break case char

const continue default do

double else enum extern

float for if

int long register return

short signed sizeof static

struct switch typedef union

unsigned void volatile while

Style (like me!!! Stylin’)

· nested blocks

· used for

· compound statements

· iteration (repeating loops of code)

· conditional (if (x < 10)…)

// ******************************

// Functions

// ******************************

void main( )

{

// variables

char user;

cout << “Will I do my work in Mr. Lupoli’s Class??”<

// have user press “Y” or “N”

cin >> user; // reads what user typed

if(user == ‘Y’) // will pass

{ cout << “Then I will pass C++, and take C++ AB next year!” << endl; }

// ONE LINE

if(user == ‘N’) // will fail

{

cout << “Then I will not pass Mr. Lupoli’s class.” << endl;

cout << “And my parents will be upset!” << endl;

// TWO LINES OR MORE

}

}

Include Statements

· become a big problem for professors when they started using namespace

· namespace

· package of library files that Visual Studio uses

· are different than normal library files used in Borland or even VS 6.0

Differences in using Namespace

using namespace

not using namespace (6.0 only??)

#include // for cin/cout

#include // for strings variables

using namespace std; // MUST HAVE

// rest of code below

#include // for cin/cout

#include // for strings variables

// rest of code below

· Use chart below (also on web as Namespace Chart)

Common Library Files Used

using namespace

not using namespace

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

ONLY USE NAMESPACE!!!

#include

#include

#include

#include

Non-Commonly Used Library Files

using namespace

not using namespace

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

Flowcharting

Symbol

Name

Meaning

Flow line

used to connect symbols and indicate the flow of logic

Terminal

used to represent the beginning (START) or end (END) of a task

Input/Output

used for input and output operations, such as reading in from the keyboard (user input) or outputting to the screen

Processing

used for arithmetic, code, and data manipulations. Multiple lines can be placed in one of these.

Decision

used for ANY logical comparison like if/else, <, >, &&, ||, !, etc…

Connector

if you have multiple pages, place a number inside this symbol so it can match another with the same number

Predefined Process/Function

used to represent a function call, or variables are sent to another function to return data or an answer

Note/Annotation

used to add personal notes to your project

· ALL IN MICROSOFT WORD!!!

· Drawing ( Autoshapes ( Flowchart

Example:

Create a flowchart that will ask for a person’s age. Then have the program double it, and display their new age.

· Exercise

· create a flowchart to determine age in Dog years, when given user input

Example If-decisions flowchart setups

YES NO

NO YES NO

YES NO

YES NO

YES NO

Computer

( stream (

keyboard

Age Program

int age;

int new age

// declare all variables

Ask for user’s age

2. Get users age, put into “age”

new age = 2 * age;

display “new age”

End of program

grade > 59

grade > 69

grade > 79

grade > 89

grade > 99

F

D

C

B

A

Pass!!!

Fail!!!

if grade > 59

PAGE

11