Professional Documents
Culture Documents
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++ Environment
1. Window System
This 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.
• 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
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 System
The 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.
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
____________________________________________
Item Purpose
Run Compiles, links, and runs the program currently loaded in the environment
Compile Compiles the program currently in the environment
Debug Sets various debugger options, including the setting of
breakpoints
Project Manages multifile projects
Options Sets various compiler, linker, and environmental options
Window Control the way various windows are displayed
Help Activates the context-sensitive help system
____________________________________________
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
These are words that can’t be declared as variables or constants because it already
performs a special function.
Examples:
char scanf
int printf
float gets
double puts
void gotoxy
Identifier Names
In C, the names that are used to reference variables, functions, and various other
user-defined objects are called identifiers.
Examples:
Character Sets
1. Preprocessor directives
The first part of the C++ program performs a task. These directives instruct the
compiler to perform certain tasks before program compilation begins.
#include file
It is the most common preprocessor directive. This directive instructs the compiler to
include another C source file before compilation begins.
#define macro
Another 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.
2. Global declaration
The 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.
Prepared by: Mrs. R. Bautista Page 4
Programming 1 & 2 – C++
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.
4. User-defined functions
The 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.
#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
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();
}
{ } – 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: “;
cin >> num2;
}
void main()
{
int “ num2 ” ;
cout << “Input a number: “;
cin >> “ num2 ” ; }
Variables
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.
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:
or to simplify it more
float P, M, F, A;
float thisisavariabletobeusedinprelimgrade
1 2 3 4 5 6 7 8 9 10 11 121314151617181920 2122 23242526 2728293031
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?
float a,b,c; or
float x,y,z; or
float 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?
Make the name easier to read by using the underscore character to separate
parts of the name.
In following example,
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:
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];
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.
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.
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.
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.
PROGRAM OUTPUT
#include <conio.h>
#include<iostream.h> Initial run of the
program: (Ctrl – F9)
int number;
Input a number: __
void main()
{
clrscr(); User inputs a number:
cout<< “Input a
number:”; Input a number: 5
cin>>number;
cout<< “You
entered:”<<number; User pressed enter
after inputting a
getch(); number:
}
Input a number: 5
You 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.
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,
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.
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.
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: char
Size: -128 to 127
Examples:
char address[50];
char name[35], status[15];
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: int
Size: -32,768 to 32,767
Examples:
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: float
Size: 3.4 E – 38 to 3.4 E + 38
Examples:
5 Double type of variables is similar to float but can handle greater amount of value
Keyword: double
Size: 1.7 E –308 to 1.7 E + 308
Examples:
double population;
double sales;
5. void (0)
Examples:
void main()
void sample()
Terms
1. 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.
Constants
Constants 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.
Operators
1. Mathematical
2. Relational
3. Logical
Relational Operators
In the term relational operator the word relational refers to the relationships values
can have with one another.
Operator Action
A. 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:
P q p && q p !! q !p
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 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 ||
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
Example:
x = x + 10 ;
c=a*b;
variable=value;
Example:
age=20;
mi= ‘A’;
grade=1.75;
The C++ preprocessor as defined by the ANSI standard contains the following
directives:
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++.
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:
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
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
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:
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 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:
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.
The printf( ) statement is one of several commands in C that can be used to output
or display information.
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
% 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);
Format: puts(string);
where:
String is a variable, a constant or expression
Example:
puts(“SSCR”);
puts(“Michael Jordan”);
puts(“Steve Vai”);
Example:
cout << “Nelson”;
cout << “\t\t Hello”;
cout << “Name” << name;
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);
printf(“Enter 2nd no.:”);
scanf(“%f”,&n2);
Format:
gets (variable);
Example:
char name[30];
printf(“Name:”);
gets(name);
Example:
int n1;
cout<<“Enter 1st no:”;
cin>>n1;
These code formats your output. These are used with the printf ( ) and fprintf ( )
statements.
\n new line Insertion point moves to the beginning of the next line
__________________________________________________
Syntax:
variable = getchar ( );
Example:
choice=getchar ( );
Syntax:
Example:
putchar(letter);
Syntax:
Example:
puts(“Sample”);
puts(Empname);
CONSOLE I/O’s
Syntax:
variable = getche ( );
Example:
choice = getche ( );
Syntax:
variable= getch ( );
Example:
choice = getch ( );
Syntax:
Example:
putch ( a );
Syntax: toupper(var);
Example:
ans=toupper(ans);
Syntax: tolower(var);
Example:
ans=tolower (ans);
Gotoxy moves the cursor to the given position in the current text window.
Syntax:
Example:
Syntax:
textbackground ( color );
Example:
textbackground ( GREEN );
textbackground ( 2 );
Syntax:
textcolor ( color );
Example:
textcolor (CYAN);
textcolor ( 5);
Syntax:
Example:
Mathematical functions
Syntax:
sqrt (variable);
Example:
double x=4.0;
printf(“The square root of %.2f is %.2f \ n”, x, sqrt(x));
Syntax:
log (variable);
Example:
do{
textcolor(random(15) );
gotoxy(random(80),random(25)); putch(03);
}while(!kbhit( ));
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.
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 statement
if ( relational_expression )
{ statement; }
if-else statement
if ( relational_expression )
{ statements; }
else
{ statements; }
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”);
else
printf(“X is less than Y”);
if (x > y )
printf(“X is greater than Y”);
else if ( x < y )
printf(“X is lesser than Y”);
else
printf(“X is equal to Y”);
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;
case ‘B’ : correct_spelling( );
break;
default: display_error( );
}
Loop-control statements
These are statements that causes actions to be repeated while certain condition
exist.
Syntax:
while ( condition )
{
statement;
}
Example:
ctr=1;
while ( ctr <=5 )
{printf (“SSCR\n” );
ctr++;}
Syntax:
do{
statement;
}while ( condition );
Example:
ctr=1;
do{
printf (“SSCR\n” );
ctr++;
}while ( ctr<=5 );
Syntax:
Initialization
Execution 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.
Conditional
Execution continues with the conditional clause. The for loop continues to execute as long
as the conditional clause is true.
Increment/Decrement
After 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>
Output
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:
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.
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();
getch();
}
OUTPUT
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.
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.
Functions are the building blocks of C++ programs. In C++, function is a module or
subprogram created to perform specific tasks.
Declaring a function
where:
type - specifies the type of value that the function will return to the calling program.
Use void if the function will not return any value to the calling 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
Add 2 Nos.
Array
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:
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”;
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
Hence, to declare a two-dimensional integer array d of size 10,20, you would write:
Unlike some computer languages, which use commas to separate the array dimensions, C
places each dimension in its own set of brackets.
d [3] [5]
Second index
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.
#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);
}
Example:
Example:
Syntax: strrev(variable);
Example:
Syntax: strcat(destination,source);
Example:
strcat(name,sname);
printf(“%s”, name);
Pointers
A 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
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.
There is a close relationship between pointers and arrays. Consider this fragment:
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
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
323
2323232323
Function Purpose
clreol ( ) Clears from the cursor to the end of the current line
Function Purpose
Function Purpose
textattr ( ) Sets both the color of the text and the color of the
background at the same time
BLACK 0
BLUE 1
GREEN [ 2
CYAN 3
RED 4
MAGENTA 5
BROWN 6
LIGHTGRAY 7
DARKGRAY 8
LIGHTBLUE 9
LIGHTGREEN 10
LIGHTCYAN 11
LIGHTRED 12
LIGHTMAGENTA 13
YELLOW 14
WHITE 15
BLINK 128
Cursor Commands
Command Action
CTRL-A Moves to the start of the word to the left of the cursor
CTRL-F Moves to the start of the word to the right of the cursor
Command Action
Command Action
Cursor Commands
Command Action
CTRL-W Scrolls up
Cursor Commands
Command Action
Insert Commands
Command Action
Delete Commands
Command Action
Block Commands
Command Action
Block Commands
Command Action
Find Commands
Command Action
CTRL-Q F Finds
Find Commands
Command Action
Pair Commands
Command Action
Miscellaneous Commands
Command Action
CTRL-U Aborts
Miscellaneous Commands
Command Action
F2 Saves
F3 Loads a file