Professional Documents
Culture Documents
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:
Identify the parts of the C++ on-screen editor and know the
basic commands used.
Background:
ICCT COLLEGES 5
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
How c ++ evolved?
Shortly thereafter, he began work on "C with Classes", which as the name
implies was meant to be a superset of the C language. His goal was to
add object-oriented programming into the C language, which was and still
is a language well-respected for its portability without sacrificing speed or
low-level functionality. His language included classes,
basic inheritance, inlining, default function arguments, and strong type
checking in addition to all the features of the C language.
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).
ICCT COLLEGES 6
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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”;
cout<<”\t\”WORLD\””;
\b backspace
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;
num2 = 23;
num3 = tot1 + tot2;
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
ICCT COLLEGES 14
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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.
CONSTANTS
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:
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.
int main ()
ICCT COLLEGES 18
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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
What is comments?
ICCT COLLEGES 20
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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:
{
This block of code acts as one statement
temp = a;
and swaps the values in the variables a
a = b;
b = temp; 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:
First sentence.
Second sentence.
The endl manipulator produces a newline character, exactly as the
insertion of '\n' does, but it also has an additional behavior when it is used
with buffered streams: the buffer is flushed. Anyway, cout will be an
unbuffered stream in most cases, so you can generally use both
the \n escape character and the endl manipulator in order to specify a new
line without any difference in its behavior.
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 )
a = 5; This statement assigns the integer value 5 to the variable a. The part
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
#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();
}
Compound Assignments
(+=,-=, *=, /=, %=, <<=, >>=, &=, ^=, |= )
expression is equivalent to
ICCT COLLEGES 27
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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;
Prefix
Both theand Postfixoperator (++) and the decrement operator (--) come in
increment
two varieties:
Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B contains 4
ICCT COLLEGES 28
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
#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();
}
Precedence of Operators
When writing complex expressions with several operands, we may have some doubts
about which operand is evaluated first and which later. For example, in this expression:
a = 5 + 7 % 2
1 a = 5 + (7 % 2) // with a result of 6, or
ICCT COLLEGES 29
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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 Operator ! is the C++ operator to perform the Boolean operation NOT, it has only
one operand, located at its right, and the only thing that it does is to inverse the value of it,
producing false if its operand is true and true if its operand is false. Basically, it returns the
opposite Boolean value of evaluating its operand. For example:
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
EXPRESSION EVALUATION
ICCT COLLEGES 31
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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)
LESSON 5
Objectives:
ICCT COLLEGES 32
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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 Exit
S1 S2 S3 S4
a. If Statement
Syntax:
if (condition) statement
ICCT COLLEGES 33
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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 ();
}
`
b. If Else Statement
Syntax: if (condition)
statement 1;
else
statement 2;
For example:
1 if (x == 100)
2 cout << "x is 100";
3 else
4 cout << "x is not 100";
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 ();
}
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";
ICCT COLLEGES 35
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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();
}
_____________________________________________________________________________________
___________________________________________________________________________________
PROBLEM 1: SAMPLE OUTPUT
____________________________________________________________________________________
____________________________________________________________________________________
Enter Your Birth Year : 1990
Create a program that will compute
____________________________________________________________________________________
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
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
ICCT COLLEGES 36
____________________________________________________________________________________
_____________________________________________________________________________________
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
________________________________________________
PROBLEM 2 : ________________________________________________
q.
r.
s.
t.
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”;
}
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
ICCT COLLEGES 38
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
SOURCE CODE:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
_________________________
LESSON 6
Objectives:
What is Iteration?
ICCT COLLEGES 39
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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
The purpose of exit is to terminate the current program with a specific exit code. Its prototype
is:
ICCT COLLEGES 40
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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
and its functionality is simply to repeat statement while the condition set in
expression is true.
For example
ICCT COLLEGES 41
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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.
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)
4. Continue the program right after the block: print FIRE! and end
program.
ICCT COLLEGES 42
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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:
n st
ar ts
with a value of 0, and i with 100, the condition is n!=i (that n is not equal
ICCT COLLEGES 46
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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 :
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________
LESSON 7
THE ARRAY
Objectives:
ICCT COLLEGES 47
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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.
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
ICCT COLLEGES 48
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
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.
When an initialization of values is provided for an array, C++ allows the possibility of leaving
the square brackets empty [ ]. In this case, the compiler will assume a size for the array that
matches the number of values included between braces { }:
After this declaration, array CARLOS would be 5 ints long, since we have
provided 5 initialization values.
name[index]
ICCT COLLEGES 49
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
Following the previous examples in which CARLOS had 5 elements and each of those
elements was of type int, the name which we can use to refer to each element is the following:
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];
At this point it is important to be able to clearly distinguish between the two uses that
brackets [ ] have related to arrays. They perform two different tasks: one is to specify the size of
arrays when they are declared; and the second one is to specify indices for concrete array
elements. Do not confuse these two possible uses of brackets [ ] with arrays.
If you read carefully, you will see that a type specifier always precedes a variable or array
declaration, while it never precedes an access.
ICCT COLLEGES 50
INTRODUCTION TO COMPUTER SCIENCE C++ Programming
1 CARLOS[0] = a;
2 CARLOS[a] = 75;
3 b = CARLOS [a+2];
4 CARLOS[CARLOS[a]] = CARLOS[2] + 5;
ICCT COLLEGES 51