Chapter 2: The Basics of C++ Programming



Intro. to 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

Programming - The mechanics

[pic]

"Bug"(s)

Bug. n. An unwanted and unintended property of a program or piece of hardware, esp. one that causes it to malfunction. Antonym of feature. Examples: "There's a bug in the editor: it writes things out backwards." "The system crashed because of a hardware bug." "Fred is a winner, but he has a few bugs" (i.e., Fred is a good guy, but he has a few personality problems).

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

The .c, 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 coding.

2. .h file:

The .h, short for header, always accompanies a .c file. It DOES NOT WORK by itself. It must have a .c file to “Drive” it.

It contains:

a. declarations of functions created in the .c 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 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 |

| |

|#include |

|… |

|scanf(… |

|printf(… |

| |

|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 days_in_year = 365; |

|define int months_in_year = 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(int num1, int 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()

|int |void |

|// opening |// opening |

| | |

|int main( ) // no void inside ( )’s |void main( ) // no void inside ( )’s |

|{ // brace to open code block |{ // brace to open code block |

|… |… |

|… |… |

|… |… |

| | |

|// closing |// closing |

|return 0; | |

|} // brace to close code block |} // brace to close code block |

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

• void

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

• int

o notice “return 0” at end – MUST HAVE

o need to use if compiling using Linux system

o returns an actual ‘0’ when program is completed

Data types

|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

o holds ONE value of that type

o 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

scanf printf

Printing a Line of Text

|C Version |

|// Mr. Lupoli |

|// 1st program |

|#include |

|void main() |

|{ |

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

|printf(“Welcome ”); |

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

|} |

What will this look like??

Using printf/scanf

• to display to the screen

o printf(

• to read from the keyboard

o scanf(

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

|char string[20] = “Lupoli”; // string AHEAD OF GAME HERE!! |

|printf |scanf |

|printf(“x is = %d \n”, x); // int |scanf(“%d”, &x); // int |

|printf(“y is = %f \n”, y); // double |scanf(“%f”, &y); // double |

|printf(“z is = %c \n”, z); // char |scanf(“%c”, &z); // char |

|printf(“a is = %hd \n”, a); // short int |scanf(“%hd”, &a); // short int |

|printf(“b is = %Ld \n”, b); // long int |scanf(“%Ld”, &b); // long int |

|printf(“c is = %Lf \n”, c); // long double |scanf(“%Lf”, &c); // long double |

|printf(“String is = %s \n”, string); // string |scanf(“%s” , string); // string |

|printf(“X is: %d and Y is: %f\n”, x, y); \\ 2 displ |scanf(“%d %f”, &x, &y); // 2 done |

• Things to notice

o both are vary similar

o on a scanf, DO NOT USE \n !!!

o in a scanf, make sure you have &variable

o BE CAREFUL WITH QUOTES!!!

Input/Output Homework Exercise

char name[20], address[20]; // declare ALL variables before you use them

// string is used for STRING text

YOU DO NOT NEED TO CODE ANY INCLUDES, MAIN, ETC...

Just code the input/output lines of code.

1. ) LITERALLY display YOUR name, and address (No variables yet.)

2.) Ask for user’s name and address, USE THE VARIABLE DECLARED FOR YOU ALREADY!!

3. display their name and address

cls/clrscr() - Clears the text window

cls/clrscr( ) clears the current text window and places the cursor in the upper left-hand corner (position 1,1).

place in first line of printing the menu options

VISUAL C/C++ (Microsoft)

#include

system(“cls” ); // are CALLED in the main( )

BORLAND

#include

clrscr( ); // are CALLED in the main( )

TURBO C

#include

clrscr( );

Getchars – a pause for a menu

#include // has getchar()

• getchar( )

o is a pause, the user must hit a button to continue the program

displayVector(x); // some function

getchar( ); // our pause

WARNING!! – make sure that there are several lines separating your getchar( ) command from other lines of code (sometimes interferes with code surrounding it)

|Getchar and clrscr example |

|#include |

|#include |

| |

|void main() |

|{ |

|printf("Mr. L is da bomb"); |

|getchar(); // pause |

|clrscr(); |

|} |

literal escape constants/command constants

- used with printf

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

What will these display??

printf( “Hi Class! \a\n” );

printf( “Good Luck!!! \n”);

printf( “\t \t You’ll need it!!!\n” );

Use of Comments

|// |/* … code … */ |

|// Mr. Lupoli |/* |

|// Project 1 |Mr. Lupoli |

|// 6/22/03 |Project 1 |

|// Period 1 |6/23/03 |

| |Period 1 |

|// ( “//”reserves whole line for a // comment |*/ |

| | |

| |/* |

| | |

|// used for ONE line comments |“ /* ” reserves whole block until you end it with a “ */ “ |

| | |

| |used for MULTIPLE lined comments |

| |*/ |

Why use comments?

• For notes

o to yourself

o to me!!

• For commenting out unfinished lines of code

o 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

printf

scanf

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

o used for

▪ compound statements

▪ iteration (repeating loops of code)

▪ conditional (if (x < 10)…)

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

// Functions

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

void main( )

{

// variables

char user;

printf( “Will I do my work in Mr. Lupoli’s Class??\n” );

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

scanf(“%c” , &user;) // reads what user typed

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

{ printf( “Then I will pass C, and take C++ next year!\n” ); }

// ONE LINE

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

{

printf( “Then I will not pass Mr. Lupoli’s class.\n” );

printf( “And my parents will be upset!\n” );

// TWO LINES OR MORE

}

}

Include Statements

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

• namespace

o package of library files that Visual Studio uses

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

|Differences in using Namespace |

|using namespace |not using namespace |

|#include // for cin/cout |#include // for cin/cout |

|#include // for strings variables |#include // for strings variables |

| | |

|using namespace std; // MUST HAVE | |

| | |

|// rest of code below |// 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 |

|[pic] |Terminal |used to represent the beginning (START) or end (END) of|

| | |a task |

|[pic] |Input/Output |used for input and output operations, such as reading |

| | |in from the keyboard (user input) or outputting to the |

| | |screen |

|[pic] |Processing |used for arithmetic, code, and data manipulations. |

| | |Multiple lines can be placed in one of these. |

|[pic] |Decision |used for ANY logical comparison like if/else, , &&,|

| | |||, !, etc… |

|[pic] |Connector |if you have multiple pages, place a number inside this |

| | |symbol so it can match another with the same number |

|[pic] |Predefined Process/Function |used to represent a function call, or variables are |

| | |sent to another function to return data or an answer |

|[pic] |Note/Annotation |used to add personal notes to your project |

• ALL IN MICROSOFT WORD!!!

o 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

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

-----------------------

keyboard

( stream (

Computer

Age Program

int age;

int new age

// declare all variables

1. Ask for user’s age

2. Get users age, put into “age”

new age = 2 * age;

display “new age”

End of program

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download