Turbo C++ Module
Turbo C++ Module
LESSON 1
Objectives:
INTRODUCTION
WHAT IS PROGRAM?
ICCT COLLEGES 1
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Compiler characteristics:
• Spends a lot of time analyzing and processing the program
• The resulting executable is some form of machine- specific binary
code
• The computer hardware interprets (executes) the resulting code
• Program execution is fast
Interpreter characteristics:
• Relatively little time is spent analyzing and processing the program
• The resulting code is some sort of intermediate code
• The resulting code is interpreted by another program
• Program execution is relatively slow
PROGRAMMING PROCESS
ICCT COLLEGES 2
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Types of Errors
30
1. Compile-time error or syntax errors
ICCT COLLEGES 3
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
2. Runtime Errors
Compilers aren't perfect and so can't catch all errors at compile
time.
This is especially true for logic errors such as infinite loops. This
type of error is called runtime error
DEFINITION OF TERMS
ICCT COLLEGES 4
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
LESSON 2
Objectives:
Background:
ICCT COLLEGES 5
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
How c ++ evolved?
In 1983, the name of the language was changed from C with Classes to
C++. The ++ operator in the C language is an operator for incrementing
a variable, which gives some insight into how Stroustrup regarded the
language. Many new features were added around this time, the most
notable of which are virtual functions, function overloading, references
with the & symbol, the const keyword, and single-line comments using
two forward slashes (which is a feature taken from the language BCPL).
In 1990, The Annotated C++ Reference Manual was released. The same
year, Borland's Turbo C++ compiler would be released as a commercial
product. Turbo C++ added a plethora of additional libraries which would
have a considerable impact on C++'s development. Although Turbo
C++'s last stable release was in 2006, the compiler is still widely used.
ICCT COLLEGES 7
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
PARTS FUNCTION/USAGE
2 Close box Found at the upper left corner of the screen that is used for
closing active window.
3 Title bar Located below menu bar, and is used to display the name
of the active window.
7 Message lies beneath the edit window and is used to display various
Compiler compiler or linker messages
Window
8 Status Area Found at the bottom part of the screen that contains lists of
shortcut keys. It also serves as a source of user’s help.
9 Window number It identifies the number of your window.
ICCT COLLEGES 8
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
How to : Method
Activate the menu bar Press F10
Method 1: Press F10
Use the arrow keys to select the menu
Select a menu from the
Press the ENTER key and the submenu appears
menu bar
Method 2: Press ALT + the highlighted key of choice
in the menu ( ex. ALT + F for File menu )
Select a command from the Press ALT + the highlighted key of choice in the menu
submenu Use the arrow keys to select a command,
press ENTER key
Cancel a command Press ESC key
note: Pressing the ESC keys cancels any selection in a
submenu and returns to the previous menu
Create a program Press ALT + F
(to activate file menu, sub-menu appears)
Choose the NEW option
Press the ENTER key
Type your program
Save a new program Press ALT + F
Use the ARROW keys to go to the SAVE AS command
Press the ENTER key (A SAVE AS dialog box appears)
Press TAB key until you reach the input box
From the input box, type your program name
Press TAB key again until you reach the OK button,
press the ENTER key
Save an edited program Method 1: Press ALT + F
Use the ARROW keys to go to the SAVE command, press
the ENTER key
Method 2: Press F2
Open a program Method 1: Press ALT + F
Use the ARROW keys to go to the OPEN command
Press ENTER key (an OPEN dialog box appears
Press TAB until you reach the input box
From the input box, type your program name
Press TAB until you reach the OK button, press the
ENTER key
Method 2: Press F3
(an OPEN dialog box appears)
Use ARROW keys to go to the program name you
want to open, press ENTER key
Compile a program Method 1: Press ALT + C (to activate the COMPILE
menu) Use the ARROW keys to go to the COMPILE
command, press ENTER key
Method 2: Press ALT + F9
Run a program Method 1: Press ALT + R
(to activate the RUN command)
Use the ARROW keys to go to the RUN command, press
the ENTER key
Method 2: Press CTRL + F9
Quit Turbo C++ Method 1: Press ALT + F
(to activate the FILE menu)
Use the ARROW keys to go to the QUIT command, press
ENTER key
Method 2: Press ALT + X (a confirmation dialog box
appears)
ICCT COLLEGES 9
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
LESSON 3
Objectives:
KEYWORDS
Reserved words
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor,
xor_eq
Your compiler may also include some additional specific reserved keywords .
ICCT COLLEGES 10
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
IDENTIFIERS
Defines as the set of values that a variable can store along with a set
of operations that can be performed on that variable.
Type Description
bool Stores either value true or false.
char Typically a single octet (one byte). This is an integer
type. It represents the character on your keyboard –
letters of the alphabet, numbers or special character
int The most natural size of integer for the machine. It is a
whole number or a series of decimal digits which can be
preceded by a positive or negative sign.
float A single-precision floating point value. A number with
decimal part
double A double-precision floating point value. a special float
which can store more significant digits and take up
more memory space.
long a large whole number
Table 1. Commonly used data types.
ICCT COLLEGES 11
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Typical range
The following table shows the variable type, how much memory it
takes to store the value memory and what is maximum and minimum vaue
which can be stored in such type of variables.
Note The values of the columns Size and Range depend on the system the
program is compiled for. The values shown above are those found on most 32-bit
systems. But for other systems, the general specification is that int has the
natural size suggested by the system architecture (one "word") and the four
integer types char, short, int and long must each one be at least as large as the one
preceding it, with char being always one byte in size. The same applies to the floating point
types float, double and long double, where each one must provide at least as much
precision as the preceding one.
#include<iostream.h>
CODE MEANING #include<conio.h>
main()
\a alert (bell) {
\n newline cout<<”H\nE\nL\nL\nO”;
\b backspace cout<<”\t\”WORLD\””;
getch();
\f formfeed
}
\r carriage return
\t tab Output
\v vertical tab
H
\\ backslash
E
\’ single quote mark L
\” double quote mark L
\0 null O
“WORLD”
ICCT COLLEGES 12
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
DATA VALUES
VARIABLES - identifiers that can store value that can be changed and can
store literals or some type of structured data.
Variable declaration
For example:
If you are going to declare more than one variable of the same type, you
can declare all of them in a single statement by separating their identifiers
with commas. For example:
int a, b, c;
ICCT COLLEGES 13
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
SCOPE OF VARIABLES
Global variables can be referred from anywhere in the code, even inside
functions, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({})
where they are declared. For example, if they are declared at the beginning
of the body of a function (like in function main) their scope is between its
declaration point and the end of that function. In the example above, this
means that if another function existed in addition to main, the local variables
declared in main could not be accessed from the other function and vice versa.
ICCT COLLEGES 14
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
CONSTANTS
2. #define DIRECTIVE
Sample code
int a, b; char a;
#define a 1; #define a ”HELLO WORLD”;
#define b 2; cout<<”The Sum is : “<<a;
cout<<”The Sum is : “<<a+b;
Output
ICCT COLLEGES 15
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
TYPES OF DATA
LITERALS are the most obvious kind of constants. They are used to
express particular values within the source code of a program. We have
already used these previously to give concrete values to variables or to
express messages we wanted our programs to print out, for example, when
we wrote:
A. Numeric Literals
Can be further sub divided into Whole Numbers and Real Numbers.
In addition to decimal numbers (those that all of us are used to using every
day), C++ allows the use of octal numbers (base 8) and hexadecimal
numbers (base 16) as literal constants. If we want to express an octal
number we have to precede it with a 0 (a zero character). And in order to
express a hexadecimal number we have to precede it with the
characters 0x (zero, x). For example, the following literal constants are all
equivalent to each other:
All of these represent the same number: 75
1 75 // decimal
(seventy-five) expressed as a base-10 numeral,
2 0113 // octal
octal numeral and hexadecimal numeral,
3 0x4b // hexadecimal
respectively.
Literal constants, like variables, are considered to have a specific data type.
By default, integer literals are of typeint. However, we can force them to
either be unsigned by appending the u character to it, or long by
appending /:
ICCT COLLEGES 16
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
The default type for floating point literals is double. If you explicitly want to
express a float or a long doublenumerical literal, you can use
the f or l suffixes respectively:
Note:
B. Non-Numeric Literals
May be in the form of a character or a series of characters(Strings).
Note:
Character literals are enclosed in single quotes. If the literal begins with L
(uppercase only), it is a wide character literal (e.g., L'x') and should be stored
in wchar_t type of variable . Otherwise, it is a narrow character literal (e.g., 'x')
and can be stored in a simple variable of char type.
String literals are enclosed in double quotes. A string contains characters that are similar
to character literals: plain characters, escape sequences, and universal characters. You can
break a long lines into multiple lines using string literals and separating them using
whitespaces.
ICCT COLLEGES 17
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
STRUCTURE OF A PROGRAM
Probably the best way to start learning a programming language is by
writing a program. Therefore, here is our first program:
We are going to look line by line at the code we have just written:
This is a comment line. All lines beginning with two slash signs (//)
are considered comments and do not have any effect on the behavior of the
program. The programmer can use them to include short explanations or
observations within the source code itself. In this case, the line is a brief
description of what our program is.
#include<iostream.h>
Lines beginning with a hash sign (#) are directives for the
preprocessor. They are not regular code lines with expressions but
indications for the compiler's preprocessor. In this case the
directive #include <iostream>tells the preprocessor to include the
iostream standard file. This specific file (iostream) includes the declarations
of the basic standard input-output library in C++, and it is included because
its functionality is going to be used later in the program.
ICCT COLLEGES 18
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
int main ()
Right after these parentheses we can find the body of the main
function enclosed in braces ({}). What is contained within these braces is
what the function does when it is executed.
cout is the name of the standard output stream in C++, and the
meaning of the entire statement is to insert a sequence of characters (in
this case the Hello World sequence of characters) into the standard output
stream (cout, which usually corresponds to the screen).
Notice that the statement ends with a semicolon character (;). This
character is used to mark the end of the statement and in fact it must be
included at the end of all expression statements in all C++ programs (one
of the most common syntax errors is indeed to forget to include some
semicolon after a statement).
You may have noticed that not all the lines of this program perform
actions when the code is executed. There were lines containing only
comments (those beginning by //). There were lines with directives for the
compiler's preprocessor (those beginning by #). Then there were lines that
began the declaration of a function (in this case, the main function) and,
finally lines with statements (like the insertion into cout), which were all
included within the block delimited by the braces ({}) of the main function.
ICCT COLLEGES 19
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
1 int main ()
2{
3 cout << " Hello World!";
4 getch();
5}
All in just one line and this would have had exactly the same meaning as
the previous code.
Gender : Male
Course : BSIT
Height : 5’11
Weight : 60 kgs
ICCT COLLEGES 20
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
What is comments?
1 // line comment
2 /* block comment */
Example:
Note:
ICCT COLLEGES 21
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
LESSON 4
Objectives:
Any place you can put a single statement, you can put command
statement, also called a block statement. A block begins with an
opening brace ({) and ends with a closing brace (}).
Sample:
{
temp = a; This block of code acts as one
a = b; statement and swaps the values in the
b = temp; variables a and b.
}
EXPRESSIONS
ICCT COLLEGES 22
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Using the standard input and output library, we will be able to interact
with the user by printing messages on the screen and getting the user's
input from the keyboard.
The standard C++ library includes the header file iostream, where
the standard input and output stream objects are declared.
The << operator inserts the data that follows it into the stream
preceding it. In the examples above it inserted the constant string Output
sentence, the numerical constant 120 and variable x into the standard
output stream cout. Notice that the sentence in the first instruction is
enclosed between double quotes (") because it is a constant string of
characters. Whenever we want to use constant strings of characters we
must enclose them between double quotes (") so that they can be clearly
distinguished from variable names. For example, these two sentences have
very different results:
ICCT COLLEGES 23
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
The insertion operator (<<) may be used more than once in a single
statement:
cout << "Hello, " << "I am " << "a C++ statement";
Additionally, to add a new-line, you may also use the endl manipulator. For
example:
Would print out:
1 cout << "First sentence." << endl;
2 cout << "Second sentence." << endl;
First sentence.
Second sentence.
cin can only process the input from the keyboard once
the RETURN key has been pressed. Therefore, even if you request a single
character, the extraction from cin will not process the input until the user
presses RETURN after the character has been introduced.
You must always consider the type of the variable that you are using
as a container with cin extractions. If you request an integer you will get
an integer, if you request a character you will get a character and if you
request a string of characters you will get a string of characters.
ICCT COLLEGES 24
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Sample
1 // i/o example
2
3 #include <iostream.h>
4 #include <conio.h>
5
6 int main ()
7 {
8 int i;
9 cout << "Please enter an integer value: ";
10 cin >> i;
11 cout << "The value you entered is " << i;
12 cout << " and its double is : " << i*2 << ".\n";
13 getch();
14 }
Output:
The user of a program may be one of the factors that generate errors
even in the simplest programs that use cin(like the one we have just seen).
Since if you request an integer value and the user introduces a name (which
generally is a string of characters), the result may cause your program to
misoperate since it is not what we were expecting from the user. So when
you use the data input provided by cin extractions you will have to trust
that the user of your program will be cooperative and that he/she will not
introduce his/her name or something similar when an integer value is
requested. A little ahead, when we see the stringstream class we will see a
possible solution for the errors that can be caused by this type of user
input.
You can also use cin to request more than one datum input from the user:
In both cases the user must give two data, one for variable a and
another one for variable b that may be separated by any valid blank
separator: a space, a tab character or a newline.
ICCT COLLEGES 25
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
OPERATORS
You do not have to memorize all the content of this page. Most details
are only provided to serve as a later reference in case you need it.
o mathematical operators (+ , - , / , * )
o relational operators ( true or false statement)
o logical operators ( and, or, not )
This statement assigns the integer value 5 to the variable a. The part
a = 5; at the left of the assignment operator (=) is known as the lvalue (left
value) and the right one as the rvalue (right value).
The lvalue has to be a variable whereas the rvalue can be either a constant,
a variable, the result of an operation or any combination of these.
The most important rule when assigning is the right-to-left rule: The
assignment operation always takes place from right to left, and never the
other way:
Consider also that we are only assigning the value of b to a at the moment
of the assignment operation. Therefore a later change of b will not affect
the new value of a.
ICCT COLLEGES 26
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
% modulo
#include<iostream.h>
#include<conio.h>
main()
{
int a, b;
a = 53;
b = 5;
clrscr();
cout<<”QUOTIENT IS : <<a/b;
cout<<”REMAINDER IS : ”<<a%b
getch();
}
ICCT COLLEGES 27
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Compound Assignments
(+=,-=, *=, /=, %=, <<=, >>=, &=, ^=, |= )
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
1 c++; are all equivalent in its functionality: the three of them increase by
2 c+=1; one the value of c.
3 c=c+1;
Both the increment operator (++) and the decrement operator (--) come in
two varieties:
ICCT COLLEGES 28
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B contains 4
#include<iostream.h>
#include<conio.h>
main()
{
int myage = 40;
int yourage = 40;
cout<<”\nMY AGE IS : “<<myage;
cout<<”\nYOUR AGE IS : “<<yourage;
cout<<”\n ******POSTFIX AND PREFIX*********”;
myage++;
++yourage;
cout<<”\nONE YEAR PASSES…….”
cout<<”\nMY AGE IS : “<<myage;
cout<<”\nYOUR AGE : ”<<yourage;
cout<<”\n++++++++ANOTHER YEAR PASSED+++++;
cout<<”\nMY AGE IS : “<<myage++;
cout<<”\n YOUR AGE IS : “<<++yourage;
cout<<”\n++++++++++LETS PRINT
AGAIN++++++++++++”;
cout<<”\nMY AGE IS : ”<<myage;
cout<<’\nYOUR AGE IS : “<<yourage;
getch();
}
ICCT COLLEGES 29
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Precedence of Operators
a = 5 + 7 % 2
1 a = 5 + (7 % 2) // with a result of 6, or
2 a = (5 + 7) % 2 // with a result of 0
The correct answer is the first of the two expressions, with a result
of 6. There is an established order with the priority of each operator, and
not only the arithmetic ones (those whose preference come from
mathematics) but for all the operators which can appear in C++. From
greatest to lowest priority
ICCT COLLEGES 30
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Be careful! The operator = (one equal sign) is not the same as the
operator == (two equal signs), the first one is an assignment operator
(assigns the value at its right to the variable at its left) and the other one
(==) is the equality operator that compares whether both expressions in the
two sides of it are equal to each other. Thus, in the last expression ((b=2)
== a), we first assigned the value 2 to b and then we compared it to a, that
also stores the value 2, so the result of the operation is true.
Logical Operators
The logical operators && and || are used when evaluating two
expressions to obtain a single relational result.
&& OPERATOR
|| OPERATOR
The operator || corresponds with Boolean logical
a b a || b
operation OR. This operation results true if either
true true true
one of its two operands is true, thus being false
true false true
only when both operands are false themselves
false true true
false false false
ICCT COLLEGES 31
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
EXPRESSION EVALUATION
1 ( a > b ) || ( c ! = c )
2 ( c != 4 ) && (b < a )
3 ( a == 2 ) || ( ! ( c > c)
4 ( b != b ) && ( c>c)
5 ( c <6) || (a==a)
6 ( b >=b) || (c !=b)
7 ( 6 >= 6 ) && ( a == 1 )
8 ( 9 == b ) || ( ! (c = 9 )
9 ( c <= 5 ) && ( c!=b )
10 ! (a==b) || ( b >=5)
ICCT COLLEGES 32
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
LESSON 5
Objectives:
Control Strucuture
Most of the control structures that we will see in this section require a
generic statement as part of its syntax. A statement can be either a simple
statement (a simple instruction ending with a semicolon) or a compound
statement (several instructions grouped in a block), like the one just
described. In the case that we want the statement to be a simple
statement, we do not need to enclose it in braces ({}). But in the case that
we want the statement to be a compound statement it must be enclosed
between braces ({}), forming a block.
SEQUENCE STRUCTURE
The instructions are executed sequentially starting from the first
instruction up to the last instruction in the program.
Entry S1 S2 S3 S4 Exit
ICCT COLLEGES 33
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
a. If Statement
Syntax:
if (condition) statement
int grade;
clrscr();
cout<<” Enter a grade: “
cin>> grade;
Write the output 2 here
If ( grade >=75)
cout << “ PASSED”;
If ( grade <75)
cout << “FAILED”;
getch ();
}
ICCT COLLEGES 34
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
`
b. If Else Statement
Syntax: if (condition)
statement 1;
else
statement 2;
For example:
int num;
clrscr();
If ( num > 0)
cout << “Positive Number”;
else If ( grade < 0)
cout << “Negative Number”;
Write the output 3 here (input zero )
else
cout<<”That is 0”;
getch ();
}
ICCT COLLEGES 35
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
c. Else If Statement
1 if (x > 0)
2 cout << "x is positive";
3 else if (x < 0)
4 cout << "x is negative";
5 else
6 cout << "x is 0";
note
Remember that in case that we want more than a single statement to
be executed, we must group them in a block by enclosing them in
braces { }.
int grade;
clrscr();
cout <<“ Enter a grade:!\n“;
cin >>> grade;
else If
(grade>=97&&grade<=100)
cout <<“1.00”;
else if (grade>=94
&&grade<=96)
cout <<“ 1.25”;
else if (grade>=91 &&
grade <=93)
cout <<“1.50”;
else if ( grade==75)
cout <<“3.00”;
else if ( grade<75)
cout <<“5.00”;
else
cout <<“Invalid
entry”;
getch();
}
ICCT COLLEGES 36
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Create a program that will compute Enter Your Birth Year : 1990
your age and will display if you are a Enter Present Year : 2012
minor or a legal age. Refer your source
code on the given output. Write your Your age is : 22 years old
program on the box below Your are in Legal age
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
________________________________________________
PROBLEM 2 :
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
Create a program that will ________________________________________________
input a number and will
____________________________________________________________________________________
________________________________________________
display the number is odd
____________________________________________________________________________________
________________________________________________
or an even number
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
_______________________________________________
SAMPLE OUTPUT
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
________________________________________________
Enter a number : 5
____________________________________________________________________________________
________________________________________________
That is odd number
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
________________________________________________
________________________________________________
________________________________________________
ICCT COLLEGES 37
__________________________
________________________________________________
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
switch(x) {
case If (x == 1)
cout<<”x is 1”; {
break; Cout<<”x is 1”;
}
case Else if (x == 2)
cout<<”x is 2”; {
break Cout<<”x is 2”;
}
default: Else
cout<<”value of x {
is unknown”; Cout<<”value of x
} is unknown”;
}
ICCT COLLEGES 38
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Create a source code of the following output. Write you program on the box
below.
SAMPLE OUTPUT
[A] – ADDITION [A] – ADDITION [A] – ADDITION
[S] – SUBTRACTION [S] – SUBTRACTION [S] – SUBTRACTION
[M] – MULTIPLICATION [M] – MULTIPLICATION [M] – MULTIPLICATION
[D] – DIVISION [D] – DIVISION [D] – DIVISION
ENTER OPERATION : A ENTER OPERATION : M ENTER OPERATION : W
ENTER NUM 1 : 12 ENTER NUM 1 : 5 INVALID ENTRY
ENTER NUM 2 : 13 ENTER NUM 2 : 10
THE SUM IS : 25 THE PRODUCT IS : 50
SOURCE CODE:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
_________________________
____________________________________________________________________________
________
ICCT COLLEGES
____________________________________________________________________________ 39
________
____________________________________________________________________________
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
LESSON 6
Objectives:
What is Iteration?
It means doing the same thing again and again. The principal method of
iteration is the loop. Loops have as purpose to repeat a statement a certain
number of times or while a condition is fulfilled.
GOTO STATEMENT
NOTE. Use of goto is almost a sign of bad design. The advice is avoid using it
ICCT COLLEGES 40
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
The purpose of exit is to terminate the current program with a specific exit
code. Its prototype is:
2. The body of the loop - the step or steps of the algorithm that are
repeated within the loop. This may be only one action, or it may
include almost all of the program statements. Important note: some
action must occur within the body of the loop that will affect the loop
termination decision at some point.
1. While Loop
2. Do Loop
3. For Loop
ICCT COLLEGES 41
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
and its functionality is simply to repeat statement while the condition set in
expression is true.
For example
When the program starts the user is prompted to insert a starting number
for the countdown. Then the while loop begins, if the value entered by the
user fulfills the condition n>0 (that n is greater than zero) the block that
follows the condition will be executed and repeated while the condition
(n>0) remains being true.
Condition is any C++ Boolean expression and Statement is any valid C++
statement or a block of statements. When condition evaluates to TRUE (1)
statement is executed. And then the condition is tested again, this continues until
condition tests FALSE (0) at which time the while loop terminates and execution
continues on the first line below statement.
ICCT COLLEGES 42
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
1. The while condition is checked (n>0). At this point there are two
possibilities:
* condition is true: statement is executed (to step 3)
* condition is false: ignore statement and continue after it (to step 5)
2. Execute statement:
cout << n << ", ";
--n;
(prints the value of n on the screen and decreases n by 1)
3. End of block. Return automatically to step 2
4. Continue the program right after the block: print FIRE! and end
program.
This will eventually make the condition (n>0) to become false after a
certain number of loop iterations: to be more specific, when n becomes 0,
that is where our while-loop and our countdown end.
ICCT COLLEGES 43
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
ICCT COLLEGES 44
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Note: The do-while loop is usually used when the condition that has to
determine the end of the loop is determinedwithin the loop statement itself, like
in the previous case, where the user input within the block is what is used to
determine if the loop has to end. In fact if you never enter the value 0 in the
previous example you can be prompted for more numbers forever.
and its main function is to repeat statement while condition remains true,
like the while loop. But in addition, thefor loop provides specific locations to
contain an initialization statement and an increase statement. So this
loop is specially designed to perform a repetitive action with a counter
which is initialized and increased on each iteration.
ICCT COLLEGES 45
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
The initialization and increase fields are optional. They can remain
empty, but in all cases the semicolon signs between them must be written.
For example we could write: for (;n<10;) if we wanted to specify no
initialization and no increase; or for (;n<10;n++) if we wanted to include
an increase field but no initialization (maybe because the variable was
already initialized before).
Optionally, using the comma operator (,) we can specify more than one
expression in any of the fields included in afor loop, like
in initialization, for example. The comma operator (,) is an expression
separator, it serves to separate more than one expression where only one is
generally expected. For example, suppose that we wanted to initialize more
than one variable in our loop:
This loop will execute for 50 times if neither n or i are modified within the
loop:
ICCT COLLEGES 46
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
n starts with a value of 0, and i with 100, the condition is n!=i (that n is
not equal to i). Because n is increased by one and i decreased by one, the
loop's condition will become false after the 50th loop, when
both n and i will be equal to 50.
Create the source code of the sample output below, the program should
accept a name and enter how many times you want to display your name.
Use any type of looping in creating your program.
Source code :
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________
ICCT COLLEGES 47
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
LESSON 7
THE ARRAY
Objectives:
What is Array?
That means that, for example, we can store 5 values of type int in an
array without having to declare 5 different variables, each one with a
different identifier. Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique identifier.
where type is a valid type (like int, float...), name is a valid identifier and
the elements field (which is always enclosed in square brackets []),
specifies how many of these elements the array has to contain.
ICCT COLLEGES 48
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
NOTE: The elements field within brackets [] which represents the number of
elements the array is going to hold, must be a constant value, since arrays are
blocks of non-dynamic memory whose size must be determined before
execution. In order to create arrays with a variable length dynamic memory is
needed, which is explained later in these tutorials.
Initializing arrays
The amount of values between braces { } must not be larger than the
number of elements that we declare for the array between square
brackets [ ]. For example, in the example of array CARLOS we have
declared that it has 5 elements and in the list of initial values within
braces { } we have specified 5 values, one for each element.
After this declaration, array CARLOS would be 5 ints long, since we have
provided 5 initialization values.
ICCT COLLEGES 49
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
name[index]
For example, to store the value 75 in the third element of CARLOS, we could
write the following statement:
CARLOS[2] = 75;
and, for example, to pass the value of the third element of CARLOS to a
variable called a, we could write:
a = CARLOS[2];
ICCT COLLEGES 50
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
If you read carefully, you will see that a type specifier always precedes a
variable or array declaration, while it never precedes an access.
1 CARLOS[0] = a;
2 CARLOS[a] = 75;
3 b = CARLOS [a+2];
4 CARLOS[CARLOS[a]] = CARLOS[2] + 5;
ICCT COLLEGES 51