Top Banner
Programming 1 & 2 – C++ I. Introduction to C++ Dennis Ritchie developed C for use on and with the Unix Operating System, running on DEC PDP-11 computers at Bell Laboratories in Murray Hill, New Jersey. In 1978, Prentice Hall published The C Programming Language, written by Brian W. Kernighan and Dennis Ritchie, thus begin the C explosion. It all started with Martin Richards who developed a language called BCPL, which in turn strongly influenced the development of the next language, B by Ken Thompson in 1970 for use with the original UNIX on DEC PDP-7. By 1972, Dennis Ritchie (working with Ken Thompson) had expanded B into C. The new C added something that B did not have: data types. To make the story short, C++ comes after the need for a programming language that has flexibility and power at the same time better performance than the ANSI C (C language that was made through the American National Standards Institute which corrected some loopholes and inconsistencies in the previous versions of C). C++ was developed by one man, Bjarne Stroustrup. C++ is not a complete departure from ANSI C, but in fact. ANSI may be regarded as a subset of C++ because the two borrowed heavily of each other ideas and methods. However C+ + definitely goes beyond standard C. It supplies a storehouse of extra tools: encapsulation, data hiding, classes and derived classes, function and operator overloading, and much more. Characteristics of C++ C++ is a general-purpose programming language with a bias towards systems programming that: Is a better C Is a middle-level language Is case sensitive Supports data abstraction Supports object-oriented programming, and Supports generic programming Seven Basic Elements in Programming 1. Get the information into the program 2. Arrange for some place to keep it 3. Give instructions to manipulate it 4. Get it back out of the users instructions 5. Executed only when specific conditions are met 6. Repeated a number of times 7. Broken off into chunks Two types of errors 1. Semantics – non-conformity with problem specification 2. Syntax – non-conformity with rules of the language C++ Environment IDE (Integrated Development Environment) of C++ is composed of three parts: Prepared by: Mrs. R. Bautista Page 1
101
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: complete lecture in C++

Programming 1 & 2 – C++

I. Introduction to C++

Dennis Ritchie developed C for use on and with the Unix Operating System, running on DEC PDP-11 computers at Bell Laboratories in Murray Hill, New Jersey. In 1978, Prentice Hall published The C Programming Language, written by Brian W. Kernighan and Dennis Ritchie, thus begin the C explosion.

It all started with Martin Richards who developed a language called BCPL, which in turn strongly influenced the development of the next language, B by Ken Thompson in 1970 for use with the original UNIX on DEC PDP-7. By 1972, Dennis Ritchie (working with Ken Thompson) had expanded B into C. The new C added something that B did not have: data types.

To make the story short, C++ comes after the need for a programming language that has flexibility and power at the same time better performance than the ANSI C (C language that was made through the American National Standards Institute which corrected some loopholes and inconsistencies in the previous versions of C).

C++ was developed by one man, Bjarne Stroustrup. C++ is not a complete departure from ANSI C, but in fact. ANSI may be regarded as a subset of C++ because the two borrowed heavily of each other ideas and methods. However C++ definitely goes beyond standard C. It supplies a storehouse of extra tools: encapsulation, data hiding, classes and derived classes, function and operator overloading, and much more.

Characteristics of C++

C++ is a general-purpose programming language with a bias towards systems programming that:

Is a better C Is a middle-level language Is case sensitive Supports data abstraction Supports object-oriented programming, and Supports generic programming

Seven Basic Elements in Programming

1. Get the information into the program2. Arrange for some place to keep it3. Give instructions to manipulate it4. Get it back out of the users instructions5. Executed only when specific conditions are met6. Repeated a number of times7. Broken off into chunks

Two types of errors

1. Semantics – non-conformity with problem specification2. Syntax – non-conformity with rules of the language

C++ Environment

IDE (Integrated Development Environment) of C++ is composed of three parts:

1. Window SystemThis is the most visible and used part of the IDE, which offers a variety of windows.

Windows are available for editing a program, debugging a program, and viewing a program’s operation.

The following basic features are found in a Borland C++ window:

Close Box. The close box is located at the upper left corner of the window. Clicking the close box with the mouse closes the window. If a mouse is not

Prepared by: Mrs. R. Bautista Page 1

Page 2: complete lecture in C++

Programming 1 & 2 – C++

present on the system, a window can be closed with the Close command on the Window pull-down menu.

Shortcut key in closing a window: Alt – F3

Title Bar. The title bar, located at the top of the window, displays the window name. Double-clicking the title bar zooms the window; dragging the title bar moves the window.

Window Number. The window number helps you keep track of the open windows. You can get a list of all open windows by pressing Alt-0 (alt-zero) or choosing List from Windows menu.

Zoom Box. The zoom box allows you to zoom the window to its largest size. Clicking the zoom box activates the zoom command. Or if a mouse is not present, zoom can be selected from the Window menu. If a window is already at its maximum size when you click the zoom box, the windows return to its former size.

Shortcut key: F5

Scroll Bars. Vertical and horizontal scroll bars are on the right and bottom sides of the window. Scroll bars are used to view the unseen contents of a window. At each end of the scroll bars are arrows. Clicking the arrows moves the screen on line at a time.

Resize Box. You can drag the resize box to change the size of the window.

2. Menu SystemThe menu system contains the utilities and features necessary for managing

programming tasks efficiently.

1. The first way to enter the menu system by pressing F10 key, then use the arrow keys to move between the menu bar and to highlight a particular command, afterwards press the Enter key to pull-down a menu then select the desired command using again the arrow keys, then press the Enter key.

2. The second way to enter the menu system is to use an Alt-key combination. To select a command, hold down Alt key and press the highlighted letter of the command. When the pull-down menu appears, use the arrow keys to move to the desired command then press the Enter key.

3. The third way to enter the menu system is to click the mouse on a command in the menu bar, then simply point to the desired command and click.

Selecting a command can have three possible outcomes:1. The command is carried out.2. A sub-menu is displayed.3. A dialog box is displayed that contains a menu offering other choices available for

the command picked. Necessary information is then provided before the command can be executed.

In C++, there are 11 menus in the menu bar namely: , File Menu, Edit Menu, Search Menu, Run Menu, Compile Menu, Debug Menu, Project Menu, Options Menu, Window Menu and Help Menu.____________________________________________

Item Purpose

Clears or restores the screen and executes various utility programs

File Loads and saves files, handles directories, invokes DOS, and exits the IDE

Edit Performs various editing functions

Prepared by: Mrs. R. Bautista Page 2

Page 3: complete lecture in C++

Programming 1 & 2 – C++

Search Performs various text searches and replacements____________________________________________

Item Purpose

Run Compiles, links, and runs the program currently loaded in the environment

Compile Compiles the program currently in the environmentDebug Sets various debugger options, including the setting of

breakpointsProject Manages multifile projectsOptions Sets various compiler, linker, and environmental optionsWindow Control the way various windows are displayedHelp Activates the context-sensitive help system

____________________________________________

The File Menu

New. This command open a new Edit window with the default name NONAMExx.CPP (the xx stands for a number from 00 to 31) and automatically makes the new Edit window active.

Open. The open command displays the Open a File dialog box, where a program file can be selected to open in an Edit Window. Short-cut key: F3.

Save. The Save commands saves the file that's in the active Edit window to disk. (This menu item is disabled if there's no active Edit window.

Save As. This command opens up the Save File As dialog box, where a file in the active Edit window can be saved under a different filename, in a different directory, or on a different drive.

Save All. This command works just like the Save command except that it saves the contents of all modified files, not just the file in the active Edit window.

Change Dir. This command brings up the Change Directory dialog box, where you can specify a drive or a directory to make current.

Print. This command prints the contents of the active Edit, Output, or Message window. The Print command is disabled if the active window can't be printed.

DOS Shell. With this command, a user may choose to leave Turbo C++ temporarily to perform a DOS command or enter another program. To return to Turbo C++, type EXIT at the DOS prompt, then press Enter.

Quit. The quit commands exits Turbo C++, removes it from memory, and returns you to DOS/Windows. Short-cut key: Alt-X.The Run Menu

Run. This command runs your program, using any arguments the user pass to it with the Arguments command. If the source code has been modified since the last compilation, the Run command also invokes the Project Manager to recompile and link your program.

3. Status Bar At the bottom of the screen, the status bar displays the shortcut keys for the most

commonly used commands, tells the user what Borland C++ is doing, or gives the user hints about the command that have been chosen.

Reserved words

Prepared by: Mrs. R. Bautista Page 3

Page 4: complete lecture in C++

Programming 1 & 2 – C++

These are words that can’t be declared as variables or constants because it already performs a special function.

Examples:

char scanfint printffloat getsdouble putsvoid gotoxy

Identifier Names

In C, the names that are used to reference variables, functions, and various other user-defined objects are called identifiers.

Rules in Giving Identifier Name

1. An identifier must start with a letter or underscore subsequent characters being letters, digits or underscore.

2. An identifier must have no embedded spaces.3. It must be descriptive.4. An identifier must be declared once.5. An identifier name may not be a reserved word.

Examples:

Valid Identifier Invalid Identifiercount 1counttest23 hi!there

high_balance high…balance

Character Sets

Compose of letters from a-z, A-Z, 0-9 and ASCII characters.

Basic Structure of a C++ program

1. Preprocessor directivesThe first part of the C++ program performs a task. These directives instruct the

compiler to perform certain tasks before program compilation begins.

#include fileIt is the most common preprocessor directive. This directive instructs the compiler to

include another C source file before compilation begins.

e.g. #include <stdio.h>#include <conio.h>

#define macroAnother common preprocessor directive is the #define directive which is macro

definition. Macro definitions supply the replacement text for the macros you use. When you use macro in a program, the preprocessor replaces the macro you entered with replacement text found in a macro definition. #define signals the start of a macro definition.

e.g. #define TRUE 1#define STALL for(i = 1; i < 10000; i++)

Prepared by: Mrs. R. Bautista Page 4

Page 5: complete lecture in C++

Programming 1 & 2 – C++

2. Global declarationThe 2nd major part of a C++ program consists of Global declarations. It tells the

compiler about user-defined functions and about variables that are common to all functions in a source file.

Function declaration – tells the computer about the function and usually found near the top of the program.

Function definition – tells the computer what is in the function, and is usually found near the bottom.

It is possible to skip the function declaration. The user can simply define the function at the top of the source file before any calls are made to the function.

Declaration is a statement that introduces a name into a program. It specifies a type for that name.

3. The main() functionThe third major part of a C++ program. Every C++ program must have a main()

function. Program execution begins in the main() function.

4. User-defined functionsThe fourth part of a C++ program consists of user-define functions – groups of

statements you design to accomplish your programming tasks. User-defined functions can do anything you want them to do.

A typical C++ Program.

#include <stdio.h>#include <conio.h>#include <iostream.h>

#define TRUE 1// define the macro T to equal to 1#define FALSE 0// define the macro F to equal to 0

int i = 0; // global variable

//this is a function declarationvoid put_msg (void);

void main(){ int answer; // local variable

clrscr(); cout << "Do you want to see the message?\n"; cout << "Enter 0 for NO, 1 for YES ==> "; cin >> answer; if(answer == TRUE) put_msg(); else cout << "Goodbye for now."; getch();}

// this is a function definitionvoid put_msg (void){

Prepared by: Mrs. R. Bautista Page 5

Page 6: complete lecture in C++

Programming 1 & 2 – C++

clrscr(); for( i = 0; i <=10; i++) cout << "Test string # " << i << "\n";}

Commonly used symbols in C++ programming

{ } – curly braces expresses grouping in C++. The main program must and always start with an opening ({) and closing (}) braces.

void main(){cout << “The program always start with an open curly bracket or brace and ends with a closing curly bracket or brace.}

// - Double slash, begins a comment/remark that extends to the end of the line.

void main(){cout << “This line would be displayed on the screen using the cout command”;// This line would not be displayed on the screen// since it begins with double slash// meaning it is treated as a comment or remark and// does not affect the program// No need to put a semi-colon at the end}

<< - Shift left ("put to") operator is used as an output operator; cout is the standard output stream.

void main(){cout << “cout command is used in conjunction with the << or the shift left operator”;cout << “It can display anything on the screen as long as it is placed inside an open”;cout << “and closing quotations, and it can also display values of variables”}

>> - Shift right operator ("get from") is used as an input operator; cin is the standard input stream.

void main(){int num1;cout << “Input any number: “;cin >> num1;

// In this program cin together with shift right operator is used to input a value on the variable num1// Notice that the variables names are not enclosed and should not be enclosed in an open and closing quotations }

“ ” - Open and closing quotations. These are used to output any string in a program. It should not be associated with any variable names.

void main(){int num2;

cout << “Input a number: “;

Prepared by: Mrs. R. Bautista Page 6

Page 7: complete lecture in C++

Programming 1 & 2 – C++

cin >> num2;}

void main(){int “ num2 ” ;

cout << “Input a number: “;cin >> “ num2 ” ; }

Variables

Variables are addresses to the computer’s memory. It serves as a temporary storage in your program.

Basic Functions of Variables

1. Receive and store user’s inputs.2. Store processing results.3. Hold constants such as titles and descriptions.

Three Places Where Variables are Declared:

1. Global – outside of all functions, including the main( ) function. These variables may be used in any part of the program.

2. Local – inside any functions. These variables can only be used inside the function where they are declared.

3. As formal parameter of a function – defined within the function heading. They are just treated just like any local variables.

Variable declaration syntax:

variable type varname, varname2, varname3….;

The name of a variable should be somewhat related to the problem.

Create a program that will accept a value for Prelim, Midterm, Final and will compute for the Average of the three grading period.

In this example, we can declare 3 or 4 variables depending on your solution to the given problem. We can declare the variables as:

float prelim, midterm, final, average;

or to simplify it more

float P, M, F, A;

Always remember the ff guidelines in naming variables

1. C identifiers can have no more than 31 significant characters.2. Make the names long enough to mean something to you.3. Make the name easier to read by using the underscore character to separate parts of

the name4. Never duplicate one of C++'s predefined names.5. Never use spaces to separate words nor use special characters other than the

underscore (_)6. Separate multiple variable declarations using a comma (,)7. Variable names can be capitalized but not the variable type

Prepared by: Mrs. R. Bautista Page 7

Page 8: complete lecture in C++

Programming 1 & 2 – C++

C identifiers (variable names) can have no more than 31 significant characters.

float thisisavariabletobeusedinprelimgrade 1 2 3 4 5 6 7 8 9 10 11 121314151617181920 2122 23242526 2728293031

In the given example, float is the variable type and thisisavraibaletobeusedinprelimgrade is the variable name. Note that the significant characters only are those from letter’s t of the word this up to letter m of the word prelim.

Make the names long enough to mean something to you.

Variables names can be short or long, depending on the programmer. But it should be at least long enough to mean something to you. Example, if a problem requires to input a value for Prelim, Midterm & Final, what variables would you use in your program in order to represent Prelim, Midterm and Final?

You could use:

float a,b,c; orfloat x,y,z; orfloat num1,num2,num3;

but is it related?

Why not try variables names that easily relates to the values that would be inputted as stated in the problem?

float prelim, midterm, final;float prel, midt, fin;float prelimgrade, midtermgrade, finalgrade;

Make the name easier to read by using the underscore character to separate parts of the name.

In following example,

float prelimgrade, midtermgrade, finalgrade;

the variable names prelimgrade, midtermgrade and finalgrade are distinct from each other. But it is harder to read since the names are composed of two words. In order to make them readable, you can separate them using the underscore character ( _ ). It should look like these:

float prelim_grade, midterm_grade, final_grade;

Never duplicate one of C++'s predefined names.

Commands and reserves words or more commonly called as C++’s predefined names such as the word void, main, cout, cin cannot be used as a name of a variable nor a name of a function. These should never be duplicated since the compiler would not allow it thus leaving your program full of errors.

float void;int cout, cin;char main[15];

Prepared by: Mrs. R. Bautista Page 8

Page 9: complete lecture in C++

Programming 1 & 2 – C++

Never use spaces to separate words nor use special characters other than the underscore (_)

Spaces and other special characters should not be used in any declaration except for the underscore to separate parts of the names and comma to separate names in declaring multiple variables.

float prelim grade, midterm grade, final grade;

float prel.grade, mid.grade, fin.grade;

float prel:grade, mid:grade, fin:grade;

Separate multiple variable declarations using a comma ( , )

In the preceding examples, several times that prelim_grade, midterm_grade and final_grade was introduced. Actually these variable names can be declared on line at time:

float prelim_grade;float midterm_grade;float final_grade;

or you can just declare the variable names in one line since they have the same type, only to be separated by a comma (,) saving you more spaces and time to type.

float prelim_grade, midterm_grade, final_grade;

Variable names can be capitalized but not the variable type

As a general rule in Turbo C++, it is very case sensitive that commands and predefined functions should be entered in small letters only. But there is an exception: variable names, function names and strings that are enclosed in open and closing quotation can be entered in small case, sentence case or upper case letters. During declaration, only the variable and function names can be capitalized not the type nor the C++’s predefined function or commands.

float PRELIM, MIDTERM, FINAL;float Prelim, Midterm, Final;float prelim, midterm, final;

Note that PRELIM, Prelim and prelim can be written in one program as well as MIDTERM, Midterm and midterm together with FINAL, Final, final for the reason being that C++ treats the mentioned variable separate and distinct from each other. The reason, again C++ compiler is very case sensitive and declaring the same names but with different letter orientation is acceptable and thus different from each other.

Sample Problem:1. Create a program that will accept a value for an integer number then output the value afterwards.

Prepared by: Mrs. R. Bautista Page 9

Page 10: complete lecture in C++

Programming 1 & 2 – C++

PROGRAM

#include <conio.h>#include<iostream.h>

int number;

void main(){clrscr();

cout<< “Input a number:”;cin>>number;

cout<< “You entered:”<<number;

getch();}

OUTPUT

Initial run of the program: (Ctrl – F9)

Input a number: __

User inputs a number:

Input a number: 5

User pressed enter after inputting a number:

Input a number: 5You entered: 5

The program starts with a header file namely, the conio.h and iostream.h. getch() and clrscr() are functions found inside the conio.h header file while the cin and cout commands are found on the iostream.h header file.

It is then followed by a variable declaration, wherein we introduce a variable name as well as the variable type to C++. In the example given,

int number;

int is the variable type integer and number is the variable name. Variable names are temporary storage in your program. It holds the value that you intend to input in a certain variable.

The declaration is made is global since is placed after the header files and before the main program.

#include <conio.h>#include <iostream.h>

int number;

void main()

The main program is started with void main(), with no semi-colon, followed by a { symbol which signifies the start of the main program, then clrscr(); a function used to clear the screen of previous output, then the statement,

cout << “Input a number: “;

wherein cout is the standard output command of the C++ used with the shift left operator <<. It is followed by string constant that is enclosed in an open and closing quotation.

After which, the statement,

cin >> number;

Prepared by: Mrs. R. Bautista Page 10

Page 11: complete lecture in C++

Programming 1 & 2 – C++

wherein cin is the standard input command of C++ used with the shift right operator >>. It is always followed by a variable name that should not be enclosed in an open and closing quotation.

The last part consists of

cout << "You entered: " << number;

getch();}

wherein, cout << again is used to output a string “You entered: “ and the value of the variable number. It is followed by a function getch(); so that the user can see the output screen. The program is ended by a } symbol which signifies the end of the main program.

Data Types

All variables in C++ must be declared prior to their use. In C++, there are five basic data types.

1. char (8 bits)

Character type of variables is used when the value to be inputted or assigned deals with alphanumeric characters. (737 Via Ferrea St.)

Keyword: charSize: -128 to 127

Examples:

char address[50];char name[35], status[15];

2. int (16 bits)

Integer type of variable is used when the value to be inputted or assigned is a whole number. (1,2,3,4 100,200)

Keyword: intSize: -32,768 to 32,767

Examples:

int num1, num2, num3;int num1;int num2;int num3;int x, y;

3. float (32 bits)

Float type of variables is used when the value to be inputted or assigned deals with numbers with decimal or fractional part. (2.3,98.7)

Keyword: floatSize: 3.4 E – 38 to 3.4 E + 38

Examples:

float num1, num2, num3;float num1;float a;float a, b;

4. double (64 bits)

Prepared by: Mrs. R. Bautista Page 11

Page 12: complete lecture in C++

Programming 1 & 2 – C++

Double type of variables is similar to float but can handle greater amount of valueKeyword: doubleSize: 1.7 E –308 to 1.7 E + 308

Examples:double population;double sales;

5. void (0)

Void type of variables is valuelessKeyword: voidSize: 0

Examples:void main()void sample()

Terms1. Bit – representation of 0’s and 1’s. ( abbreviation for “binary digit” )2. Byte – A unit of memory containing 8 bits.3. Word – A unit of memory containing 16 bits ( 2 bytes )4. Doubleword- A unit of memory containing 32 bits (4 bytes; 2 words )5. Quadword – A unit of memory containing 64 bits (8 bytes; 4 words)6. Paragraph – A unit of memory containing 128 bits (16 bytes ; 8 words ) ASCII – Abbreviation for “American Standard Code for Information Interchange.” A standard code, used to store textual characters in memory, in which each character is represented by a unique 8 bit pattern.

ANSI - Abbreviation for “American National Standard Institute.” These are group of persons who designed the ASCII.

ConstantsConstants in C refer to fixed values that may not be altered by the program. They

can be of any data type.C supports one other type of constant in addition to those of the predefined data

types. This is a string. All string constants are enclosed between double quotes, such as “this is a test”. You must not confuse strings with characters. A single character constant is enclosed by single quotes, such as ‘a’. Because strings are simply array of characters.

Data Type Constant Examples

char ‘a’ ‘ \n’ ‘9’int 1 123 21000 -234float 123.23 4.34

Operators

These are symbols that causes arithmetic operations or logical operations to be performed.Types of operators:

1. Mathematical2. Relational3. Logical

A. Mathematical Operators – used for arithmetic operations

Prepared by: Mrs. R. Bautista Page 12

Page 13: complete lecture in C++

Programming 1 & 2 – C++

Operation Operator ExampleAddition +

+=C=4 + D;C+=4; this is the same as C=C+4; meaning that 4 is added to the value of C.

Subtraction --=

C=10-8;C-=5; this is the same as C=C-5; meaning that 5 is subtracted from the value of C.

Multiplication **=

C=A*B;C*=A; this is the same as C=C*A;

Division //=

C=A/B;C/=A; this is the same as C=C/A;

Modulus Division

%%=

C=A%B;C%=2; the same as C=C%2;

Increment ++ C++ means to increment value of C by 1 after using++C means to increment value of C by 1 before using

Decrement -- C- - decrement by 1 after using C.- - C decrement by 1 before using.

B. Relational OperatorsIn the term relational operator the word relational refers to the relationships values

can have with one another.

Operator Action

> Greater than> = Greater than or equal< Less than< = Less than or equal= = Equal! = Not equal

C. Logical Operators

In the term logical operator the word logical refers to the ways these relationships can be connected together using the rules of formal logic.

Operator Action

&& AND| | OR! NOT

Truth table for the logical operators is shown here using 1s and 0s:

Prepared by: Mrs. R. Bautista Page 13

Page 14: complete lecture in C++

Programming 1 & 2 – C++

P q p && q p !! q !p

0 0 0 0 1 0 1 0 1 11 0 0 1 01 1 1 1 0

Both the relational and logical operators are lower in precedence than the arithmetic operators. This means that an expression like 10> 1+12 is evaluated as if it were written 10> (1+12). The result is, of course, false.

The following shows the relative precedence of the relational and logical operators:

highest !> >= < <=== !=&&

lowest ||

Precedence of C++ Operators

Highest () [] - > .

! ~ ++ -- - (type) * & sizeof* / %+ -<< >>< <= > >=== !=&^|&&||?= += -= *= /=

Lowest

C++ Statements According to the C++ syntax, a statement can consist of one of the following: a

single statement, a block of statements, or nothing (in the case of empty statements). In the descriptions presented here, the term statement is used to mean all three of these possibilities.

Expressions

Operators, constants, and variables are the constituents of expressions. An expression in C is any valid combination of those pieces.

Example:

Prepared by: Mrs. R. Bautista Page 14

Page 15: complete lecture in C++

Programming 1 & 2 – C++

x = x + 10 ;

c = a * b ;

Assignment Statements (=)Assign the specified value or expression to a variable.

The general form of the assignment statement is:

variable=value; Example:

age=20;mi= ‘A’;grade=1.75;

The C++ preprocessor as defined by the ANSI standard contains the following directives:

#if #elif #undef#ifdef #endif #line#ifndef #include #error#else #define #pragma

THE #include Preprocessor

This control line allows you to specify the header file ( .h ) that you wishes to include into the program. A header file provides declarations for library functions. Library functions are predefined routines used as a command in C++.

Syntaxes: # include < header_file.h > or# include “directory_path\header_file.h”

The first format is used when the header file can be found in the standard include file subdirectory. If it is not the case, the next format is used.

Examples:

# include < conio.h ># include “c:\tc\conio.h”

The #define Preprocessor

The #define directive is used to define an identifier and a character sequence that will be substituted for the identifier each time it is encountered in the source file. The identifier is called a macro-name and the replacement process is called macro-substitution. The general form of the directive is

#define macro-name character-sequence

Notice that there is no semicolon in this statement. There may be any number of spaces between the identifier and the character sequence, but once it begins, it is terminated only by a new line.

For example, if you wish to use TRUE for the value 1 and FALSE for the value 0, then you would declare two macro #defines:

#define TRUE 1#define FALSE 0

Prepared by: Mrs. R. Bautista Page 15

Page 16: complete lecture in C++

Programming 1 & 2 – C++

This causes the compiler to substitute a 1 or 0 each time the name TRUE or FALSE is encountered in your source file. For example, the following prints “0 1 2” on the screen:

printf(“%d %d %d”, FALSE, TRUE, TRUE+1);

Once a macro-name has been defined, it can be used as part of the definition of other macro-names. For example, this code defines the names ONE, TWO, and THREE to their respective values:

#define ONE 1#define TWO ONE + ONE#define THREE ONE + TWO

The #error Preprocessor

The #error directive forces C++ to stop compilation when it is encountered. It is used primarily for debugging. The general form of the directive is:

#error error-message

The error-message is not between double quotes. When the compiler encounters this directive, it displays the following information and terminates compilation:

Fatal: filename linenum Error directive: error-message

The C++ Library Functions

The ANSI C standard has defined both the content and the form of the C standard library. All Turbo and Borland C and C++ compilers supply all functions defined by the ANSI standard. However, to allow the fullest possible use and control of the computer, Turbo/Borland C/C++ contains many additional functions. For example, a complete set of screen and graphics functions are included even though these functions are not defined by the ANSI standard. As long as you will not be porting the programs you write to a new environment, it is perfectly fine to use these enhanced functions.

Basic Input and Output Statements (Strings and Character functions)

Statement for Output Operation

a) The printf( ) statement <stdio.h>

The printf( ) statement is one of several commands in C that can be used to output or display information.

The general format of printf( ) is:

printf(“control_string”,arguments);

where: control_string is a string of characters containing text or format codes. A format code is a code that specifies how the argument will be displayed. Arguments specify one or more argument separated by a comma. An argument can be a variable, a constant or an expression.

Format Codes:

% d Display/Accept decimal% i Display /Accept integer

Prepared by: Mrs. R. Bautista Page 16

Page 17: complete lecture in C++

Programming 1 & 2 – C++

% f Display/Accept floating-point value% c Display/Accept a character% s Display/Accept string% e Display / Accept scientific notation % o Display/Accept octal% x Display/Accept hexadecimal

Example: 1) int age;

printf(“Age is %d”,age);

2) char mi; mi=’A’; printf(“Initial is %c.”,mi);

3) float grade, pre, mid, fin; pre=85; mid=70; fin=65; grade=(pre+mid+fin)/3; printf(“Prelim:%.2f\n Midterm:%.2f\n Final:%.2f\n”, pre,mid,fin); printf(“Grade:%.2f”,grade);

b) The puts( ) statement <stdio.h>

It works very similar to printf( ) but can only output strings.

Format: puts(string);

where:String is a variable, a constant or expression

Example:puts(“SSCR”);puts(“Michael Jordan”);puts(“Steve Vai”);

c) The cout( ) statement <iostream.h>

It works similar to printf( ) regardless of format codes.

Format: cout <<string << arguments;

Example:cout << “Nelson”;cout << “\t\t Hello”;cout << “Name” << name;

Statement for Input Operation

a.) The scanf( ) statement <stdio.h>

The scanf( ) statement is one of several commands in C++ that can be used to read information from the keyboard.

Format:scanf (“control_string”,argument);

Example:int n1,n2;printf(“Enter 1st no.:”);scanf(“%f”,&n1);

Prepared by: Mrs. R. Bautista Page 17

Page 18: complete lecture in C++

Programming 1 & 2 – C++

printf(“Enter 2nd no.:”);scanf(“%f”,&n2);

b.) The gets( ) statement <stdio.h>

It accepts a string value and assign it to a character array variable. Gets replaces the new line by a null character (\0), it also allows input strings

to contain certain white space characters (spaces, tabs). Gets returns when it encounters a new line.

Format:gets (variable);

Example:char name[30];printf(“Name:”);gets(name);

c.) The cin( ) statement <iostream.h>

It works similar to scanf( ) regardless of format codes.

Format: cin>> arguments;

Example:

int n1;cout<<“Enter 1st no:”;cin>>n1;

The Backslash ( \ ) Codes.

These code formats your output. These are used with the printf ( ) and fprintf ( ) statements.

Backslash code

Meaning Description

\b Backspace Insertion point moves one space to the left

\n new line Insertion point moves to the beginning of the next line

\r carriage returnInsertion point moves to the beginning of the current line

\t tab Insertion point moves to the next tab stop

\’ single quote Single quotation mark is printed

\” Double quote Double quaotation mark is printed

\\ Backslash Backslash is printed

__________________________________________________

The getchar ( ) statement. <stdio.h>

This statement accepts a character value from a standard input/output device.

Prepared by: Mrs. R. Bautista Page 18

Page 19: complete lecture in C++

Programming 1 & 2 – C++

Syntax:

variable = getchar ( );

Example:

choice=getchar ( );

The putchar ( ) statement <stdio.h>

This statement outputs a character value to a standard output device.

Syntax:

putchar ( char / variable );

Example:

putchar(letter);

The puts ( ) statement. <stdio.h>

It outputs a string value into a standard output device.

Syntax:

puts ( string_text / char_array );

Example:

puts(“Sample”);puts(Empname);

CONSOLE I/O’s

Include file: conio.h

The getche ( ) statement <conio.h>

Accepts and echoes a character from the console.

Syntax:

variable = getche ( );

Example:

choice = getche ( );

The getch ( ) statement <conio.h>

Accepts a character but does not echo on the screen.

Syntax:

variable= getch ( );

Example:

Prepared by: Mrs. R. Bautista Page 19

Page 20: complete lecture in C++

Programming 1 & 2 – C++

choice = getch ( );

The putch ( ) statement <conio.h>

Displays a character on the screen.

Syntax:

putch ( char / variable );

Example:

putch ( a );

The toupper ( ) statement; <ctype.h>

Translate characters to uppercase.

Syntax: toupper(var);

Example:

ans=toupper(ans);

The tolower ( ) statement; <ctype.h>

Translate characters to lowercase.

Syntax: tolower(var);

Example:

ans=tolower (ans);

The gotoxy ( ) statement <conio.h>

Positions cursor in text window.

Gotoxy moves the cursor to the given position in the current text window.

Syntax:

gotoxy ( col , row );

Example:

gotoxy ( 10, 20 ); printf (“Nelson”);

The textbackground ( ) statement <conio.h>

Selects a new text background color.

Syntax:

Prepared by: Mrs. R. Bautista Page 20

Page 21: complete lecture in C++

Programming 1 & 2 – C++

textbackground ( color );

Example:

textbackground ( GREEN );textbackground ( 2 );

The textcolor ( ) statement <conio.h>

Selects a new character color in text mode.

Syntax:

textcolor ( color );

Example:

textcolor (CYAN);textcolor ( 5);

The window ( ) statement <conio.h>

Defines active text mode window.

Syntax:

window( left , top , right , bottom );

Example:

window( 30, 5, 60, 15 );

Mathematical functions

The sqrt ( ) statement <math.h>

Calculates square root.

Syntax:

sqrt (variable);

Example:

double x=4.0;printf(“The square root of %.2f is %.2f \ n”, x, sqrt(x));

The log ( ) statement <math.h>

Natural logarithm function

Syntax:

log (variable);

The delay( ) statement <dos.h>

Suspends execution for interval (milliseconds).

Prepared by: Mrs. R. Bautista Page 21

Page 22: complete lecture in C++

Programming 1 & 2 – C++

Syntax: delay( milliseconds);

Note: One thousand milliseconds is equivalent to one second.

The random( ) statement <stdlib.h>

Random returns a random number between 0 and (num-1).

Syntax: random (num);

Example:

do{textcolor(random(15) );gotoxy(random(80),random(25)); putch(03);}while(!kbhit( ));

Program Control Statements

These include the loop constructs while, for, and do/while; the if and switch conditional statements; and the break statements.

Conditional Statements

C++ has two condition statements namely if/else and switch( ). These statements function the same as Pascal’s If-then-else and Case.

The if/else statement.

Evaluates one statement clause when a given condition is true and another when not. An if statement may or may not have an else clause.

Syntaxes:

if statementif ( relational_expression )

{ statement; }

if-else statementif ( relational_expression ) { statements; }else

{ statements; }

nested if-else statement

Prepared by: Mrs. R. Bautista Page 22

Page 23: complete lecture in C++

Programming 1 & 2 – C++

if ( relational_expression ) { statements; }

else if ( relational_expression ) statements;

else statements;

The first format is an if statement without an alternative clause. If there are to be more than one statements to be performed, enclosed the statements with braces({}). The second format is used when there are two alternatives. While the last one is a nested if/else statement.

Examples:

if statement

if ( x > y )printf (“X is greater than Y”);

if-else statement

if ( x > y )printf(“X is greater than Y”);

elseprintf(“X is less than Y”);

nested if-else statement

if (x > y )printf(“X is greater than Y”);

else if ( x < y )printf(“X is lesser than Y”);

elseprintf(“X is equal to Y”);

The switch( ) statement.

This is a multiple-branch decision statement. The switch( ) statement only tests for equivalent values. If no match has been made, the default statement will be executed. Each case clause should end with a break statement.

Syntax:switch( variable ){ case constant_1; statements;

break; case constant_N: statements;

break; default: statements;}

Example:

switch( choice ){ case ‘A’ : check_spelling( ); break;

Prepared by: Mrs. R. Bautista Page 23

Page 24: complete lecture in C++

Programming 1 & 2 – C++

case ‘B’ : correct_spelling( ); break;

default: display_error( );}

The break statement

This statement terminates a case in a switch statement or a looping statement.Syntax:

break;

Loop-control statements

These are statements that causes actions to be repeated while certain condition exist.

1.) The while( ) statement – (pre test)

Syntax:

while ( condition ){

statement;}

Example:

ctr=1;while ( ctr <=5 ){printf (“SSCR\n” ); ctr++;}

2.) The do while( ) statement – (post test)

Syntax:

do{ statement;

}while ( condition );

Example:

ctr=1;do{

printf (“SSCR\n” ); ctr++;}while ( ctr<=5 );

3.) The for( ) statement

Syntax:

for ( initialization; conditional; increment / decrement ) {

// the body of the loop

}

Prepared by: Mrs. R. Bautista Page 24

Page 25: complete lecture in C++

Programming 1 & 2 – C++

InitializationExecution of the for loop begins with the initialization clause. The initialization clause got its name because this is normally where the counting variables are initialized. The initialization clause is only executed once when the for loop is first encountered.

ConditionalExecution continues with the conditional clause. The for loop continues to execute as long as the conditional clause is true.

Increment/DecrementAfter completing the execution of the code in the body of the loop, control passes to the increment/decrement clause before returning to check the conditional, thereby repeating the process.

The increment/decrement clause normally houses the auto increment or auto decrement statements used to update the counting variables.

Sample program

#include <stdio.h>#include <iostream.h>#include <conio.h>

void main(){int x;clrscr(); for (x = 1; x < 11; x++) {cout<<x<<".Turbo C++ is very interesting! \n"; }getch();}

Output

1. Turbo C++ is very interesting!2. Turbo C++ is very interesting!3. Turbo C++ is very interesting!4. Turbo C++ is very interesting!5. Turbo C++ is very interesting!6. Turbo C++ is very interesting!7. Turbo C++ is very interesting!8. Turbo C++ is very interesting!9. Turbo C++ is very interesting!10. Turbo C++ is very interesting!

First, it checks the initial value of x which is 1, then it checks the condition determining whether true or false before making the next move. If the condition is true, it executes the body of the loop. And in the given problem, the command cout << x << ". Turbo C++ is very interesting! \n"; will give an initial output of:

1. Turbo C++ is very interesting!

since the initial value of x is 1. Afterwards, it will increment x by 1 as the command x++ implies, before checking again the condition. Since the result of the condition x < 11 will be true again, it will perform again the command cout << x << ". Turbo C++ is very interesting! \n"; up to which x reached the value of 11. When x reached the value of 11, the looping will terminate since x with the value of 11 is not less than 11.

Prepared by: Mrs. R. Bautista Page 25

252525252525225252525252522525252525252

Page 26: complete lecture in C++

Programming 1 & 2 – C++

Every output proceeds to the beginning of the next line since \n is placed on the output command.

Sample2:

#include <stdio.h>#include <iostream.h>#include <conio.h>

void main(){float x;char *equi[8];

clrscr();

for (x = 1 ; x > 0 && x < 6;){cout << "Enter a number from 1 to 5: ";cin >> x;if (x == 1) *equi = "One"; else if (x == 2) *equi = "Two"; else if (x == 3) *equi = "Three"; else if (x == 4) *equi = "Four"; else if (x == 5) *equi = "Five"; else *equi = "a number not on the list!";

cout << "You entered " << *equi << "\n";}

getch();}

OUTPUT

Enter a number from 1 to 5: 1You entered OneEnter a number from 1 to 5: 2You entered TwoEnter a number from 1 to 5: 3You entered ThreeEnter a number from 1 to 5: 4.4You entered a number not on the list!Enter a number from 1 to 5: 5You entered FiveEnter a number from 1 to 5: 6You entered a number not on the list!

This for loop executes until the user input numbers ranging from 1 to 5, otherwise it will display a message of "You entered a number not on the list", afterwards exiting the for loop statement in case the number inputted exceeds 5; or a negative number. If the numbers from 1 to 5 are entered, its equivalent will be outputted on the screen based on the if else condition on the program.

The for loop checks whether the number being entered is within the prescribed number.

The if else give the equivalent of the number in words based on the condition given.

Prepared by: Mrs. R. Bautista Page 26

Page 27: complete lecture in C++

Programming 1 & 2 – C++

x was declared as a float and not of an integer type so that error will not be encountered in case a user input numbers with decimal.

Dealing with Functions

Functions are the building blocks of C++ programs. In C++, function is a module or subprogram created to perform specific tasks.

Declaring a function

type function_name (parameter_list)statement;

where:type - specifies the type of value that the function will return to the calling program.

types: char, int, float, and void

Use void if the function will not return any value to the calling program.

function_name – specifies the name of the module or program.

parameter_list – specifies one or more variables that will be used to receive data supplied by other modules.

Example:

Write a program that will calculate and print the sum of 2 integers.

Tasks Modules

1. Display Layout disp_scr( )2. Accept 2 integers get_nos( )3. Calculate sum calc_sum( )4. Print sum prt_sum( )5. Check for additional entries main( )

Layout of the Program

Array

Prepared by: Mrs. R. Bautista Page 27

Add 2 Nos.

Enter 1st no.: ____________________

Enter 2nd no.: ____________________

Sum is: _______________

Process Another (Y/N)? _____

Page 28: complete lecture in C++

Programming 1 & 2 – C++

An array is a collection of variables of the same type that are referenced by a common name. A specific element in an array is accessed by an index. In C++, all arrays consist of contiguous memory locations. The lowest address corresponds to the first element; the highest address corresponds to the last element.

The general form of a single-dimension array declaration is:

type var_name[size];

All arrays have 0 as the index of their first element. Therefore, when you write

char p[10];

you are declaring a character array that has 10 elements, p[0] through p[9].

Array Initialization

C++ allows the initialization of global and local arrays at the time of declaration. The general form of array initialization is similar to that of other variables, as shown here:

type-specifier array_name[sizeN]…[size1]={ value-list};

The value-list is a comma-separated list of constants that are type-compatible with type-specifier. The first constant is placed in the first position of the array, the second constant in the second position, and so on. The last entry in the list is not followed by a comma. Note that a semicolon follows the }. In the following example, a 10-element integer array is initialized with the numbers 1 through 10:

int I[10]={1,2,3,4,5,6,7,8,9,10};

This means that i[0] has the value 1 and i[9] has the value 10.

Character arrays that hold strings allow a shorthand initialization in the form:

char array_name[size]=”string”

In this form of initialization, the null terminator is automatically appended to the string. For example, this code fragment initializes str to the phrase “hello”.

char str[6]=”hello”;

This is the same as writing

char str[6] = {‘h’,’e’,’l’,’l’,’o’,’\0’};

Notice that in this version you must explicitly include the null terminator. Because all strings in C end with a null, you must make sure that the array you declare is long enough to include it. This is why str is six characters long even though “hello” is only five characters. When the string constant is used (as in the previous approach), the compiler automatically supplies the null terminator.

Two-Dimensional Arrays

Turbo C++ allows multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. A two-dimensioanl array is, in essence, an array of one-dimensional arrays. Two-dimensional arrays are declared using the general form:

Prepared by: Mrs. R. Bautista Page 28

Page 29: complete lecture in C++

Programming 1 & 2 – C++

type array_name [2nd dimension size] [1st dimension size];

Hence, to declare a two-dimensional integer array d of size 10,20, you would write:

int d [10] [20];

Unlike some computer languages, which use commas to separate the array dimensions, C places each dimension in its own set of brackets.

Similarly, to access point 3,5 of array d, use

d [3] [5]

0,0 0,1 0,2 0.3 0,4 0,5 0,6 0,7

1,0 1,1 1,2 1.3 1,4 1,5 1,6 1,7

2,0 2,1 2,2 2.3 2,4 2,5 2,6 2,7

3,0 3,1 3,2 3.3 3,4 3,5 3,6 3,7

4,0 4,1 4,2 4.3 4,4 4,5 4,6 4,7

A two-dimensional array in memory (loaded with numbers 1 through 12)

In this example, num[0][0] has the value 1; num[0][1], the value 2, num[0][2] the value 3; and so on. The value of num[2][3] is 12.

Two-dimensional arays are stored in a row-column matrix, where the first index indicates the row and the second indicates the column. This means that the rightmost index changes faster than the leftmost when accessing the elements in the array in the order they are actually stored in memory. In essence, the leftmost index can be thought of as a “pointer” to the correct row.

Example: (Multiplication table using two dimensional array)

#include<stdio.h>#include<conio.h>#include<dos.h>

main(){int a,b,multable[11][11];clrscr();for(a=1;a<=10;a++){for(b=1;b<=10;b++){multable[a][b]=a*b; gotoxy(3+a*5,2*b); printf("%d",multable[a][b]);delay(10);}}getch();return(0);}

Prepared by: Mrs. R. Bautista Page 29

First index

Second index

Page 30: complete lecture in C++

Programming 1 & 2 – C++

Common string library function

The strlen ( ) statement <string.h>

Calculates length of a string.

Syntax: strlen (string);

Example:

char *string = “Borland International” ;printf(“%d”, strlen(string));

The strcpy ( ) statement; <string.h>

Copies string source to destination.

Syntax: strcpy (destination, “source string”);

Example:

strcpy (txt, “Nelson D. Cantor”);printf(“%s”, txt);

The strrev ( ) statement; <string.h>

Reverse the string

Syntax: strrev(variable);

Example:

char *name= “Nelson” ;strrev(name);printf(“%s”,name);

The strcat ( ) statement; <string.h>

Appends one string to another

Syntax: strcat(destination,source);

Example:

char *name= “Nelson” ;char *sname= “Cantor” ;

strcat(name,sname);printf(“%s”, name);

The strcmp ( ) statement; <string.h>

Compare two strings

Syntax: strcmp(variable1, variable2);

The strcmpi ( ) statement; <string.h>

Prepared by: Mrs. R. Bautista Page 30

Page 31: complete lecture in C++

Programming 1 & 2 – C++

Compare two strings without case sensitivity

Syntax: strcmpi(variable1, variable2);

PointersA pointer contains a memory address. Most commonly, this address is the location of

another variable in memory. If one variable contains the address of another variable, the first variable is said to point to the second. For example, if a variable at location 1004 is pointed to by a variable at location 1000, location 1000 will contain the value 10004.

Pointer Variables

If a variable is going to hold a pointer, it must be declared as such. A pointer declaration consists of a base type, an *, and the variable name. The general form for declaring a pointer variable is:

type * name;

where type is any C++ type (the pointer’s base type), and name is the name of the pointer variable.

The base type of the pointer defines what type of variables the pointer can point to. Technically, any type of pointer can point anywhere in memory, but C assumes that what the pointer is pointing to is an object of its base type. Also, you will see, all pointer arithmetic is done relative to its base type, so the base type of a pointer is very important.

Pointers and Arrays

There is a close relationship between pointers and arrays. Consider this fragment:

char str[80] , *p1;p1=str ;

Here, p1 has been set to the address of the first element in str. If you wished to access the fifth element in str you could write

str[4]

or

*(p1+4)

Both statements return the fifth element. Remember, arrays start at 0, so a 4 is used to index str. You add 4 to the pointer p1 to get the fifth element because p1 currently points to the first element of str. (Remember that an array name without an index returns the starting address of the array, which is the first element.)

In essence, C++ allows two methods of accessing array elements. This is important because pointer arithmetic can be faster than array-indexing. Since speed is often a consideration in programming, the use of pointers to access array elements is very common to C++ programs.

Initializing Pointers

After a pointer is declared, but before it has been assigned a value, it contains an unknown value. If you try to use the pointer prior to giving it a value, you probably will crash not only your program but also the operating system of your computer.

By convention, a pointer that is pointing nowhere should be given the value null to signify that it points to nothing. However, just because a pointer has a null value does not

Prepared by: Mrs. R. Bautista Page 31

Page 32: complete lecture in C++

Programming 1 & 2 – C++

make it “safe.” If you use a null pointer on the left side of an assignment statement you still risk crashing your program or operating system.

Because a null pointer is assumed to be unused, you can use the null pointer to make many of your pointer routines easier to code and more efficient. For example, you could use a null pointer to mark the end of a pointer array. If this is done, a routine that accesses that array knows that it has reached the end when the null value is encountered.

Appendix

C++ Environment

Prepared by: Mrs. R. Bautista Page 32

Page 33: complete lecture in C++

Programming 1 & 2 – C++

Prepared by: Mrs. R. Bautista Page 33

333

333

Page 34: complete lecture in C++

Programming 1 & 2 – C++

The Standard Header Files

File Name Related Functions

alloc.h Dynamic allocation functions

assert.h Defines the assert ( ) macro (ANSI C)

bcd.h Defines the bcd class (C++)

bios.h ROM-BIOS functions

complex.h Defines the complex number class (C++)

Prepared by: Mrs. R. Bautista Page 34

Page 35: complete lecture in C++

Programming 1 & 2 – C++

conio.h Screen-handling functions

constrea.h Console I / O (C++)

ctype.h Character-handling functions (ANSI C)

dir.h Directory-handling functions

direct.h Directory management (C++)

dirent.h Support for POSIX (C++)

dos.h DOS interfacing functions

Prepared by: Mrs. R. Bautista Page 35

Page 36: complete lecture in C++

Programming 1 & 2 – C++

The Standard Header Files (continued)

File Name Related Functions

errno.h Defines error codes (ANSI C)

fcntl.h Defines constants used by open ( ) function

float.h Defines implementation-dependent floating- point values (ANSI C)

fstream.h File I / O class definitions (C++)

Prepared by: Mrs. R. Bautista Page 36

Page 37: complete lecture in C++

Programming 1 & 2 – C++

generic.h Macros for making generic class declarations (C++)

graphics.h Graphics functions

io.h UNIX-like I / O routines

iomanip.h Defines I / O manipulators (C++)

iostream.h Defines I / O stream class (C++)

limits.h Defines various implementation-dependent limits (ANSI C)

Prepared by: Mrs. R. Bautista Page 37

Page 38: complete lecture in C++

Programming 1 & 2 – C++

Prepared by: Mrs. R. Bautista Page 38

Page 39: complete lecture in C++

Programming 1 & 2 – C++

The Standard Header Files (continued)

File Name Related Functions

locale.h Country and language specific functions (ANSI C)

malloc.h Dynamic allocation

math.h Various definitions used by the math library (ANSI C)

mem.h Memory manipulation functions

memory.h Same as mem.h

Prepared by: Mrs. R. Bautista Page 39

Page 40: complete lecture in C++

Programming 1 & 2 – C++

new.h Allows alternative function to be called when new fails

process.h Spawn ( ) and exec ( ) functions

search.h Searching and sorting

setjmp.h Nonlocal jumps (ANSI C)

share.h File sharing

signal.h Defines signal values (ANSI C)

stdarg.h Variable-length argument lists (ANSI C)

Prepared by: Mrs. R. Bautista Page 40

Page 41: complete lecture in C++

Programming 1 & 2 – C++

The Standard Header Files (continued)

File Name Related Functions

stddef.h Defines some commonly used constants (ANSI C)

stdio.h Declarations for standard I / O streams (ANSI C)

stdiostr.h Stream classes that use FILE structures (C++)

stdlib.h Miscellaneous declarations (ANSI C)

stream.h Defines old stream class (C++)Prepared by: Mrs. R. Bautista Page 41

Page 42: complete lecture in C++

Programming 1 & 2 – C++

string.h String handling (ANSI C)

strstrea.h istrstream and ostrstream class definitions (C++)

sys\locking File locking

sys\stat.h Defines constants for file opening

sys\timeb.h Declarations needed for the ftime ( ) function

Prepared by: Mrs. R. Bautista Page 42

Page 43: complete lecture in C++

Programming 1 & 2 – C++

The Standard Header Files (continued)

File Name Related Functions

sys\types.h Type declarations used with time functions

time.h System time functions (ANSI C)

utime.h Declares the utime ( ) function

values.h Machine-dependent constants

varargs.h Variable length arguments (obsolete)

Prepared by: Mrs. R. Bautista Page 43

Page 44: complete lecture in C++

Programming 1 & 2 – C++

Prepared by: Mrs. R. Bautista Page 44

Page 45: complete lecture in C++

Programming 1 & 2 – C++

C++ Text Screen Manipulation Functions

Function Purpose

clrscr ( ) Clears the active window

Prepared by: Mrs. R. Bautista Page 45

Page 46: complete lecture in C++

Programming 1 & 2 – C++

clreol ( ) Clears from the cursor to the end of the current line

Prepared by: Mrs. R. Bautista Page 46

Page 47: complete lecture in C++

Programming 1 & 2 – C++

C++ Text Screen Manipulation Functions (continued)

Function Purpose

delline ( ) Deletes the line containing the cursor

gettext ( ) Copies part of the screen into a character buffer

gotoxy ( ) Sends the cursor to the specified location

insline ( ) Inserts a blank line below the current cursor position

movetext ( ) Copies text from one part of the screen to another

Prepared by: Mrs. R. Bautista Page 47

Page 48: complete lecture in C++

Programming 1 & 2 – C++

puttext ( ) Copies text from a buffer onto the screen

textmode ( ) Sets the screen’s text mode

Prepared by: Mrs. R. Bautista Page 48

Page 49: complete lecture in C++

Programming 1 & 2 – C++

C++ Text Attribute Functions

Function Purpose

highvideo ( ) Displays text in high intensity

lowvideo ( ) Displays text in low intensity

normvideo ( ) Displays text in the original intensity

textattr ( ) Sets both the color of the text and the color of the background at the same time

Prepared by: Mrs. R. Bautista Page 49

Page 50: complete lecture in C++

Programming 1 & 2 – C++

textbackground ( ) Sets the background color

textcolor ( ) Sets the color of the text

textmode ( ) Sets the video mode

Prepared by: Mrs. R. Bautista Page 50

Page 51: complete lecture in C++

Programming 1 & 2 – C++

The Color Macros and Integer Equivalent for Text

Macro Integer Equivalent

BLACK 0

BLUE 1

GREEN [ 2

CYAN 3

RED 4

Prepared by: Mrs. R. Bautista Page 51

Page 52: complete lecture in C++

Programming 1 & 2 – C++

MAGENTA 5

BROWN 6

LIGHTGRAY 7

DARKGRAY 8

LIGHTBLUE 9

LIGHTGREEN 10

LIGHTCYAN 11

Prepared by: Mrs. R. Bautista Page 52

Page 53: complete lecture in C++

Programming 1 & 2 – C++

The Color Macros and Integer Equivalent for Text (continued)

Macro Integer Equivalent

LIGHTRED 12

LIGHTMAGENTA 13Prepared by: Mrs. R. Bautista Page 53

Page 54: complete lecture in C++

Programming 1 & 2 – C++

YELLOW 14

WHITE 15

BLINK 128

Prepared by: Mrs. R. Bautista Page 54

Page 55: complete lecture in C++

Programming 1 & 2 – C++

Cursor Commands

Command Action

CTRL-A Moves to the start of the word to the left of the cursor

CTRL-S Moves left one character

CTRL-D Moves right one character

CTRL-F Moves to the start of the word to the right of the cursor

Prepared by: Mrs. R. Bautista Page 55

Page 56: complete lecture in C++

Programming 1 & 2 – C++

Prepared by: Mrs. R. Bautista Page 56

Page 57: complete lecture in C++

Programming 1 & 2 – C++

Cursor Commands (continued)

Command Action

CTRL-E Moves the cursor up one line

CTRL-R Moves the cursor up one full screen

CTRL-X Moves the cursor down one line

CTRL-C Moves the cursor down one full screen

CTRL-W Scrolls the screen down

Prepared by: Mrs. R. Bautista Page 57

Page 58: complete lecture in C++

Programming 1 & 2 – C++

CTRL-Z Scrolls the screen up

PGUP Moves the cursor up one full screen

PGDN Moves the cursor down one full screen

HOME Moves the cursor to the start of the line

END Moves the cursor to the end of the line

CTRL-Q E Moves the cursor to the top of the screen

Prepared by: Mrs. R. Bautista Page 58

Page 59: complete lecture in C++

Programming 1 & 2 – C++

Cursor Commands (continued)

Command Action

CTRL-Q X Moves the cursor to the bottom of the screen

CTRL-Q R Moves the cursor to the beginning of the file

CTRL-Q C Moves the cursor to the end of the file

CTRL-PGUP Moves the cursor to the beginning of the file

CTRL-PGDN Moves the cursor to the end of the file

CTRL-HOME Moves the cursor to the top of the screen

CTRL-END Moves the cursor to the bottom of the screen

Prepared by: Mrs. R. Bautista Page 59

Page 60: complete lecture in C++

Programming 1 & 2 – C++

C++ Editor Command Summary by Category

Prepared by: Mrs. R. Bautista Page 60

Page 61: complete lecture in C++

Programming 1 & 2 – C++

Cursor Commands

Command Action

LEFT ARROW or CTRL-S Moves left one character

RIGHT ARROW or CTRL-D Moves right one character

CTRL-A Moves left one word

CTRL-F Moves right one word

UP ARROW or CTRL-E Moves up one linePrepared by: Mrs. R. Bautista Page 61

Page 62: complete lecture in C++

Programming 1 & 2 – C++

DOWN ARROW or CTRL-X Moves down one line

CTRL-W Scrolls up

CTRL-Z Scrolls down

PGUP or CTRL-R Moves up one page

PGDN or CTRL-C Moves down one page

HOME or CTRL-Q S Moves to start of line

END or CTRL-Q D Moves to end of line

Prepared by: Mrs. R. Bautista Page 62

Page 63: complete lecture in C++

Programming 1 & 2 – C++

C++ Editor Command Summary by Category(continued)

Cursor Commands

Prepared by: Mrs. R. Bautista Page 63

Page 64: complete lecture in C++

Programming 1 & 2 – C++

Command Action

CTRL-Q E Moves to top of screen

CTRL-Q X Moves to bottom of screen

CTRL-Q R Moves to beginning of file

CTRL-Q C Moves to end of file

CTRL-Q B Moves to start of block

CTRL-Q K Moves to end of block

CTRL-Q P Moves to last cursor position

Insert Commands

Command Action

INS or CTRL-V Toggles insert mode

ENTER or CTRL-N Inserts a blank line

Prepared by: Mrs. R. Bautista Page 64

Page 65: complete lecture in C++

Programming 1 & 2 – C++

C++ Editor Command Summary by Category(continued)

Prepared by: Mrs. R. Bautista Page 65

Page 66: complete lecture in C++

Programming 1 & 2 – C++

Delete Commands

Command Action

CTRL-Y Deletes entire line

CTRL-Q Y Deletes to end of line

BACKSPACE Deletes character on left

DEL or CTRL-G Deletes character at cursor

CTRL-T Deletes word to the rightPrepared by: Mrs. R. Bautista Page 66

Page 67: complete lecture in C++

Programming 1 & 2 – C++

Block Commands

Command Action

CTRL-K B Marks start of block

CTRL-K K Marks end of block

CTRL-K T Marks a word

CTRL-K C Copies a block

CTRL-K Y Deletes a block

Prepared by: Mrs. R. Bautista Page 67

Page 68: complete lecture in C++

Programming 1 & 2 – C++

C++ Editor Command Summary by Category(continued)

Block Commands

Command Action

CTRL-K H Hides or displays a block

CTRL-K V Moves a block

CTRL-K R Writes a block to disk

Prepared by: Mrs. R. Bautista Page 68

Page 69: complete lecture in C++

Programming 1 & 2 – C++

CTRL-K W Reads a block from disk

CTRL-K I Indents a block

CTRL-K U Exdents a block

CTRL-K P Prints a block

CTRL-INS Copies to clipboard

SHIFT-DEL Cuts to clipboard

Find Commands

Command Action

CTRL-Q F Finds

Prepared by: Mrs. R. Bautista Page 69

Page 70: complete lecture in C++

Programming 1 & 2 – C++

C++ Editor Command Summary by Category(continued)

Prepared by: Mrs. R. Bautista Page 70

Page 71: complete lecture in C++

Programming 1 & 2 – C++

Find Commands

Command Action

CTRL-Q A Finds and replaces

CTRL-Q n Finds a place marker

CTRL-L Repeats find

Pair Commands

Prepared by: Mrs. R. Bautista Page 71

Page 72: complete lecture in C++

Programming 1 & 2 – C++

Command Action

CTRL-Q [ Matches pair forward

CTRL-Q ] Matches pair reverse

Miscellaneous Commands

Command Action

CTRL-U Aborts

CTRL-O I Toggles autoindentation mode

Prepared by: Mrs. R. Bautista Page 72

Page 73: complete lecture in C++

Programming 1 & 2 – C++

C++ Editor Command Summary by Category(continued)

Miscellaneous Commands

Command Action

CTRL-P Control character prefix

F10 Exits editor

F3 Opens new file

CTRL-Q W Restores overwritten error messagePrepared by: Mrs. R. Bautista Page 73

Page 74: complete lecture in C++

Programming 1 & 2 – C++

F2 Saves

CTRL-K n Sets a place marker

CTRL-O T Toggles tab mode

ALT-BACKSPACE Performs an undo

SHIFT-ALT-BACKSPACE Undoes an undo

CTRL-O U Toggles backspace mode

Prepared by: Mrs. R. Bautista Page 74

Page 75: complete lecture in C++

Programming 1 & 2 – C++

The Hot keys

Hot key Purpose

F1 Activates the on-line help system

F2 Saves the file currently being edited

F3 Loads a file

F4 Executes the program until the cursor is reachedPrepared by: Mrs. R. Bautista Page 75

Page 76: complete lecture in C++

Programming 1 & 2 – C++

F5 Zooms the active window

F6 Switches between windows

F7 Traces the program into function calls

F8 Traces the program, skipping function calls

F9 Compiles and links your program

F10 Activates the main menu

The Hot keys (continued)

Prepared by: Mrs. R. Bautista Page 76

Page 77: complete lecture in C++

Programming 1 & 2 – C++

Hot key Purpose

ALT-0 Lists open windows

Alt-n Activates window n (n must be 1 through 9)

ALT-F1 Shows the previous help screen

ALT-F3 Deletes the active window

ALT-F4 Opens an Inspector window

ALT-F5 Toggles between the user screen and the IDEPrepared by: Mrs. R. Bautista Page 77

Page 78: complete lecture in C++

Programming 1 & 2 – C++

ALT-F7 Previous error

ALT-F8 Next error

ALFT-F9 Compiles file to .OBJ

ALT-SPACEBAR Activates the main menu

ALT-C Activates the Compile menu

The Hot keys (continued)

Prepared by: Mrs. R. Bautista Page 78

Page 79: complete lecture in C++

Programming 1 & 2 – C++

Hot key Purpose

ALT-D Activates the Debug menu

ALT-E Activates the editor

ALT-F Activates the File menu

ALT-H Activates the Help menu

ALT-O Activates the Options menu

ALT-P Activates the Project menuPrepared by: Mrs. R. Bautista Page 79

Page 80: complete lecture in C++

Programming 1 & 2 – C++

ALT-R Activates the Run menu

ALT-S Activates the Search menu

ALT-W Activates the Window menu

ALT-X Quits the IDE and returns to DOS

The Hot keys (continued)

Prepared by: Mrs. R. Bautista Page 80

Page 81: complete lecture in C++

Programming 1 & 2 – C++

Hot key Purpose

CTRL-F1 Requests help about the item under the cursor

CTRL-F2 Resets the program

CTRL-F3 Shows the function call stack

CTRL-F4 Evaluates an expression

CTRL-F5 Changes the size or location of the active window

CTRL-F7 Sets a watch expression (debugging)Prepared by: Mrs. R. Bautista Page 81

Page 82: complete lecture in C++

Programming 1 & 2 – C++

CTRL-F8 Sets or clears a break point

CTRL-F9 Executes the current program

Prepared by: Mrs. R. Bautista Page 82

Page 83: complete lecture in C++

Programming 1 & 2 – C++

Prepared by: Mrs. R. Bautista Page 83