SlideShare a Scribd company logo
1 of 51
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 1
LESSON 1
COMPUTER PROGRAM / PROGRAMMING
Objectives:
At the end of this lesson, the student should be able to:
 Have a better understanding of what program is.
 know what are the steps in problem solving
INTRODUCTION
Nowadays computers are able to perform many different tasks,
from simple mathematical operations to sophisticated animated simulations.
But the computer does not create these tasks by itself, these are performed
following a series of predefined instructions that conform what we call
a program.
A computer does not have enough creativity to make tasks
which it has not been programmed for, so it can only follow the instructions
of programs which it has been programmed to run. Those in charge of
generating programs so that the computers may perform new tasks are
known as programmers or coders, who for that purpose use
a programming language.
WHAT IS PROGRAM?
The word program is used in two ways:
1. to describe individual instructions, or source code, created by the
programmer, and to
2. describe an entire piece of executable software.
Source code can be turned into an executable program in two ways:
1. Interpreters translate the source code into computer instructions,
and the computer acts on those instructions immediately.
Alternatively,
2. Compilers translate source code into a program, which you can run
at a later time. While interpreters are easier to work with, most
serious programming is done with compilers because compiled
code runs much faster. C++ is a compiled language.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 2
DIAGRAM 1. Compiler vs Interpreter
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
All programming involves creating something that solves a problem.
The problems can range from something of great scientific or national
importance, through to something as trivial as relieving personal boredom!
This section describes one approach to solving such problems - think
of it as a rough guide to the things you should do when entering the land of
programming.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 3
The programming process consists of 5 steps. These are really only
guidelines that have come to be recognized as being part of writing good,
easily understood, and useful computer programs.
1] Define the Problem
The programmer prepares a problem statement outlining the answers
to the following questions:
1. What is the job to be done?
2. What is the input data to be processed?
3. How is the data to be processed?
4. What is the desired format of the output?
2] Analyze the Problem
A plan of action is prepared describing the processing sequence of the
operations. The plan may be in the form of a
1. Decision table – presents a complex situation, the conditions and
the corresponding actions.
2. Flowchart – shows the sequence of operations.
3] Code the Program
The sequence of operations contained in the flowchart is translated
into a set of instructions written in symbolic languages like COBOL, BASIC,
C, C++, etc. This program is then loaded into the memory of a computer
where a compiler program translates this set of instructions into machine
readable form.
4] Debug and Test the Program
Programs are tested to locate and correct programming errors or
bugs. programming errors are due to:
1. Clerical error – Ex. Assigning the same statement number to two
instructions
2. Logical error – ex. Omitting certain facts important to the whole
system in a payroll application.
Types of Errors
30
1. Compile-time error or syntax errors
 occur if there is a syntax error in the code.
 The compiler will detect the error and the program won't even
compile. At this point, the programmer is unable to form an
executable program that a user can run until the error is fixed.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 4
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
Debugging is done using these methods:
a. Desk checking – manual review of the program
b. Diagnostics – computer prints out error messages through
the computer programs.
5] Document the Program
All data pertaining to a program are collected, organized, and
recorded. A complete documentation gives the following advantages:
1. Simplifies program revision
2. Enables another programmer to modify or maintain the program.
3. Facilitates the operation of the program by the operator.
4. Minimizes need for major program overhaul.
Coding - is the act of translating the design into an actual program,
written in some form of programming language. This is the step
where you actually have to sit down at the computer and type!
Programming - is then the task of describing your design to the
computer: teaching it your way of solving the problem
Compilation - is actually the process of turning the program written
in some programming language into the instructions made up of 0's
and 1's that the computer can actually follow.
Debugging - is simply the task of looking at the original program,
identifying the mistakes, correcting the code and recompiling it.
Code - The instructions in a computer program. Instructions written
by a programmer in a programming language are often called source
code. Instructions that have been converted into machine language
that the computer understands are called machine code or executable
code.
DEFINITION OF TERMS
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 5
LESSON 2
INTRODUCTION TO C++ PROGRAMMING LANGUAGE
Objectives:
At the end of this lesson, the student should be able to:
 Learn why C++ is the emerging standard in software
development.
 Have a good understanding of how C++ evolved and what
problems it was designed to solve.
 Identify the parts of the C++ on-screen editor and know the
basic commands used.
Background:
Computer languages have undergone dramatic evolution since the
first electronic computers were built to assist in telemetry calculations
during World War II. Early on, programmers worked with the most primitive
computer instructions: machine language. These instructions were
represented by long strings of ones and zeroes. Soon, assemblers were
invented to map machine instructions to human-readable and manageable
mnemonics, such as ADD and MOV.
In time, higher-level languages evolved, such as BASIC and COBOL.
These languages let people work with something approximating words and
sentences, such as Let I = 100. These instructions were translated back into
machine language by interpreters and compilers. An interpreter
translates a program as it reads it, turning the program instructions, or
code, directly into actions. A compiler translates the code into an
intermediary form. This step is called compiling, and produces an object
file. The compiler then invokes a linker, which turns the object file into an
executable program.
Because interpreters read the code as it is written and execute the
code on the spot, interpreters are easy for the programmer to work with.
Compilers, however, introduce the extra steps of compiling and linking the
code, which is inconvenient. Compilers produce a program that is very fast
each time it is run. However, the time-consuming task of translating the
source code into machine language has already been accomplished.
Another advantage of many compiled languages like C++ is that you
can distribute the executable program to people who don't have the
compiler. With an interpretive language, you must have the language to run
the program.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 6
For many years, the principle goal of computer programmers was to
write short pieces of code that would execute quickly. The program needed
to be small, because memory was expensive, and it needed to be fast,
because processing power was also expensive. As computers have become
smaller, cheaper, and faster, and as the cost of memory has fallen, these
priorities have changed. Today the cost of a programmer's time far
outweighs the cost of most of the computers in use by businesses. Well-
written, easy-to-maintain code is at a premium. Easy- to-maintain means
that as business requirements change, the program can be extended and
enhanced without great expense.
How c ++ evolved?
 The C++ programming language has a history going back to 1979,
when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the
languages Stroustrup had the opportunity to work with was a language
called Simula, which as the name implies is a language primarily designed
for simulations.The Simula 67 language - which was the variant that
Stroustrup worked with - is regarded as the first language to support the
object-oriented programming paradigm. Stroustrup found that this
paradigm was very useful for software development, however the Simula
language was far too slow for practical use.
 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).
 In 1985, Stroustrup's reference to the language entitled The C++
Programming Language was published. That same year, C++ was
implemented as a comercial product. The language was not officially
standardized yet, making the book a very important reference. The
language was updated again in 1989 to include protected and static
members, as well as inheritance from several classes.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 7
 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.
 In 1998, the C++ standards committee published the first international
standard for C++ ISO/IEC 14882:1998, which would be informally known
as C++98.
 In 2005, the C++ standards committee released a technical report
(dubbed TR1) detailing various features they were planning to add to the
latest C++ standard. The new standard was informally dubbed C++0x as
it was expected to be released sometime before the end of the first
decade. Ironically, however, the new standard would not be released until
mid-2011. Several technical reports were released up until then, and
some compilers began adding experimental support for the new features.
 In mid-2011, the new C++ standard (dubbed C++11) was finished.
The Boost library project made a considerable impact on the new
standard, and some of the new modules were derived directly from the
corresponding Boost libraries. Some of the new features included regular
expression support (details on regular expressions may be found here), a
comprehensive randomization library, a new C++ time library, atomics
support, a standard threading library (which up until 2011 both C and
C++ were lacking), a new for loop syntax providing functionality similar
to for each loops in certain other languages, the auto keyword, new
container classes, better support for unions and array-initialization lists,
and varied templates.
The ANSI Standard
The Accredited Standards Committee,
operating under the procedures of the
American National Standards Institute
(ANSI), is working to create an international
standard for C++.
The ANSI standard is an attempt to ensure
the C++ is portable--that code you write for
Microsoft's Compiler will compile without
errors, using a compiler from any other
vendor.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 8
THE C++ INTEGRATED DEVELOPMENT ENVIRONMENT
PARTS FUNCTION/USAGE
1 Menu Bar Is a region on top of a screen where drop down list of
menus are displayed.
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.
4 Desktop/Editor The area in the middle of screen at which several list of
different types of windows can be placed.
5 Frame Serves as a window border
6 Resize Corner It is used to change the size of the active window.
7 Message
Compiler
Window
lies beneath the edit window and is used to display various
compiler or linker messages
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.
10 Scroll bar Used to scroll the content of the window horizontally or
vertically.
11 Zoom Box Used to view the window to a full screen
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 9
SHORT CUT KEY COMMANDS
How to : Method
Activate the menu bar Press F10
Select a menu from the
menu bar
Method 1: Press F10
 Use the arrow keys to select the menu
 Press the ENTER key and the submenu appears
Method 2: Press ALT + the highlighted key of choice
in the menu ( ex. ALT + F for File menu )
Select a command from the
submenu
Press ALT + the highlighted key of choice in the menu
 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)
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 10
LESSON 3
GETTING STARTED WITH C++ PROGRAM
Objectives:
At the end of this lesson, the student should be able to:
 Define identifiers know its importance
 Know what the reserve words are and how to use data types.
 Know how to define and declare variables and constants in a
program.
KEYWORDS
Keywords are predefined reserved identifiers that have special
meanings. They cannot be used as identifiers in your program.
Reserved words
Words “reserved” by the programming language for expressing
various statements and constructs, thus they may not be redefined by
the programmer.
The standard reserved keywords are:
asm, auto, bool, break, case, catch, char, class, const,
const_cast, continue, default, delete, do, double, dynamic_cast,
else, enum, explicit, export, extern, false, float, for, friend,
goto, if, inline, int, long, mutable, namespace, new, operator,
private, protected, public, register, reinterpret_cast, return,
short, signed, sizeof, static, static_cast, struct, switch,
template, this, throw, true, try, typedef, typeid, typename,
union, unsigned, using, virtual, void, volatile, wchar_t, while
Additionally, alternative representations for some operators cannot be used
as identifiers since they are reserved words under some circumstances:
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.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 11
IDENTIFIERS
 composed of a sequence of letters, digits, and the special character
_(underscore)
 these are defined by the programmer, thus they should be
descriptive.
 It must consist only of letters, digits and underscores
 It cannot begin with a digit or underscore.
 An identifier defined in the C++ standard library should not be
redefined.
Very important: The C++ language is a "case sensitive" language. That
means that an identifier written in capital letters is not equivalent to another
one with the same name but written in small letters. Thus, for example,
the RESULT variable is not the same as the result variable or
the Result variable. These are three different variable identifiers.
DATA TYPE (Most Commonly Used)
Defines as the set of values that a variable can store along with a set
of operations that can be performed on that variable.
Table 1. Commonly used data types.
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
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 12
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.
Type Typical Bit Width Typical Range
char 1byte -127 to 127 or 0 to 255
int 4bytes -2147483648 to 2147483647
long
int
4bytes -2,147,483,647 to 2,147,483,647
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
Table 2. Data types typical range
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.
C++ BACKSLASH CODE Sample code
CODE MEANING
a alert (bell)
n newline
b backspace
f formfeed
r carriage return
t tab Output
v vertical tab
 backslash
’ single quote mark
” double quote mark
0 null
#include<iostream.h>
#include<conio.h>
main()
{
cout<<”HnEnLnLnO”;
cout<<”t”WORLD””;
getch();
}
H
E
L
L
O
“WORLD”
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 13
DATA VALUES
VARIABLES - identifiers that can store value that can be changed and can
store literals or some type of structured data.
Variable declaration
 consist of a data type and a variable name.
 The effect is that it reserves memory space for each of the variable it
declares.
In order to use a variable in C++, we must first declare it specifying
which data type we want it to be. The syntax to declare a new variable is to
write the specifier of the desired data type (like int, bool, float...) followed
by a valid variable identifier.
Format: <data type> <variable_name> ;
For example:
1
2
int a;
float mynumber;
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;
C++ assignment statement
 may be used to assign values to variables of any types.
Format: <variable> =
Ex.: num1 = num;
num2 = 23;
num3 = tot1 + tot2;
1
2
3
int a;
int b;
int c;
Constant
Variable
Arithmetic expression
These are two valid declarations of variables. The first
one declares a variable of type int with the
identifier a. The second one declares a variable of
type float with the identifier mynumber. Once
declared, the variables a and mynumber can be used
within the rest of their scope in the program.
This declares three variables (a, b and c), all
of them of type int, and has exactly the
same meaning as:
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 14
SCOPE OF VARIABLES
All the variables that we intend to use in a program must have
been declared with its type specifier in an earlier point in the code, like we
did in the previous code at the beginning of the body of the function main
when we declared that a, b, and result were of type int.
A variable can be either of global or local scope.
A. A global variable is a variable declared in the main body of the source
code, outside all functions.
B. A local variable is one declared within the body of a function or a
block.
Diagram 2. 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.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 15
CONSTANTS
Constants are expressions with a fixed value. It is identifiers that can
store values that cannot be changed. Usually are all capital letters with
underscores between each word to distinguished from variable.
Ex. char LETTER = ‘I’;
int MILES = 23;
There are two simple ways in C++ to define constants:
1. Using const keyword.
2. Using #define preprocessor.
1. Declared Constant (const)
With the const prefix you can declare constants with a specific type in the
same way as you would do with a variable:
1
2
const int pathwidth = 100;
const char tabulator = 't';
2. #define DIRECTIVE
 Directs the compiler to replaces all the instances of constant_identifier
with literal value whenever it appears in the program.
 The main use to a #define directive is to make it easy for the
programmer to change all occurrences of a certain value throughout a
program.
 A #define line can occur anywhere in a program, but are normally
placed at column 1. it affects only those lines that come after it.
Format: #define constant_identifier literal
Ex.: #define SCHOOL “ICCT Colleges”
#define INITIAL ‘I’
Sample code
Output
int a, b;
#define a 1;
#define b 2;
cout<<”The Sum is : “<<a+b;
char a;
#define a ”HELLO WORLD”;
cout<<”The Sum is : “<<a;
The Sum is : 3 HELLO WORLD
Here, pathwidth and tabulator are two typed
constants. They are treated just like
regular variables except that their values
cannot be modified after their definition.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 16
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 = 5;
Literal constants can be divided in Numeric Literals, Non-Numeric Literal
and the Boolean Literals
A. Numeric Literals
Can be further sub divided into Whole Numbers and Real Numbers.
1.) Whole Numbers or Integer Numerals
There is no doubt that it is a constant: whenever we write 1776 in a
program, we will be referring to the value 1776.
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:
1
2
3
75 // decimal
0113 // octal
0x4b // hexadecimal
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 /:
75 // int
75u // unsigned int
75l // long
1
2
3
1776
707
-273
The 5 in this piece of code was a literal constant.
All of these represent the same number: 75
(seventy-five) expressed as a base-10 numeral,
octal numeral and hexadecimal numeral,
respectively.
They are numerical constants that identify integer decimal
values. Notice that to express a numerical constant we do
not have to write quotes (") nor any special character.
In both cases, the suffix can be specified using
either upper or lowercase letters.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 17
2.) Real Numbers or Floating Point Literals
They express numbers with decimals and/or exponents. They can
include either a decimal point, an e character (that expresses "by ten at the
Xth height", where X is an integer value that follows the e character), or
both a decimal point and an e character:
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:
In defining numeric literals, the following rules should be followed:
1] No comma.
2] No space between the unary sign (+ or -) and the digits.
3] Must begin and end with a digit.
B. Non-Numeric Literals
May be in the form of a character or a series of characters(Strings).
'z'
'p'
"Hello world"
"How do you do?"
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.
1
2
3
4
3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0
1
2
3.14159L // long double
6.02e23f // float
These are four valid numbers with decimals
expressed in C++. The first number is PI, the
second one is the number of Avogadro, the
third is the electric charge of an electron (an
extremely small number) -all of them
approximated- and the last one is the number
three expressed as a floating-point numeric
literal.
Any of the letters that can be part of a floating
point numerical constant (e, f, l) can be
written using either lower or uppercase letters
without any difference in their meanings.
The first two expressions represent single character
constants, and the following two represent string literals
composed of several characters. Notice that to represent a
single character we enclose it between single quotes (') and
to express a string (which generally consists of more than one
character) we enclose it between double quotes (").
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 18
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:
1
2
3
4
5
6
7
8
9
10
// my first program in C++
#include <iostream.h>
#include <conio.h>
int main ()
{
cout << "Hello World!";
getch();
}
Hello World!
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.
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.
Instruct C++ to include the header file conio.h during compilation
and from which getch() function is also defined in conio.h
Rules when inserting #include directive into a program:
a. There must be no space between the hash character # from the
include keyword.
b. The # must begin in column 1 of the source file and there must
be no preceding blanks or tabs.
// my first program in C++
#include<iostream.h>
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 19
This line corresponds to the beginning of the definition of the main
function. The main function is the point by where all C++ programs start
their execution, independently of its location within the source code. It does
not matter whether there are other functions with other names defined
before or after it - the instructions contained within this function's definition
will always be the first ones to be executed in any C++ program. For that
same reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()).
That is because it is a function declaration: In C++, what differentiates a
function declaration from other types of expressions are these parentheses
that follow its name. Optionally, these parentheses may enclose a list of
parameters within them.
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.
This line is a C++ statement. A statement is a simple or compound
expression that can actually produce some effect. In fact, this statement
performs the only action that generates a visible effect in our first program.
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.
int main ()
cout << " Hello World!";
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 20
The program has been structured in different lines in order to be more
readable, but in C++, we do not have strict rules on how to separate
instructions in different lines. For example, instead of
1
2
3
4
5
int main ()
{
cout << " Hello World!";
getch();
}
We could have written:
int main () { cout << "Hello World!"; return 0; }
All in just one line and this would have had exactly the same meaning as
the previous code.
Using the sample program “Hello World” on the previous lesson,
create your own program that will display your Name, Address, Gender,
Birthday, Course, Year, Height and Weight. Refer your code on the sample
target output below.
SAMPLE TARGET OUTPUT:
Name : Ernanie Carlos
Address : Rosario, Pasig City
Gender : Male
Birthday : January 17, 1990
Course : BSIT
Year : 4th year
Height : 5’11
Weight : 60 kgs
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 21
What is comments?
Comments are parts of the source code disregarded by the compiler.
They simply do nothing. Their purpose is only to allow the programmer to
insert notes or descriptions embedded within the source code.
C++ supports two ways to insert comments:
1
2
// line comment
/* block comment */
1. The first of them, known as line comment, discards everything from
where the pair of slash signs (//) is found up to the end of that same
line.
2. The second one, known as block comment, discards everything
between the /*characters and the first appearance of
the */ characters, with the possibility of including more than one line.
Example:
Note:
If you include comments within the source code of your programs
without using the comment characters combinations //, /* or */,
the compiler will take them as if they were C++ expressions, most
likely causing one or several error messages when you compile it.
1
2
3
4
5
6
7
8
9
10
11
12
/* my second program in C++
with more comments */
#include <iostream>
#include<conio.h>
int main ()
{
cout << "Hello World! ";
// prints Hello World!
cout << "I'm a C++ program";
// prints I'm a C++ program
getch();
}
Hello World! I'm a C++
program
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 22
LESSON 4
C++ OPERATORS, EXPRESSION, STATEMENTS, STANDARD INPUT
AND OUTPUT
Objectives:
At the end of this lesson, the student should be able to:
 Know what expression is.
 Know how to construct block of statements
 Know the difference of integer division and the use of modulus
 Know how to combine mathematical and assignment operators
 Know the difference between increment and decrement and
postfix from prefix.
 How to use the standard input and output in a complex program.
BLOCK AND COMPOUND STATEMENT
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:
EXPRESSIONS
Anything that evaluates to a value is an expression in C++. An expression
is said to return a value. Thus, 3+2’ returns the value of 5 and so is an
expression. All expressions are statements.
Here are three examples:
3.2 // returns the value 3.2
PI // float const that the value 3.14
Seconds per minute //int const that returns 60
{
temp = a;
a = b;
b = temp;
}
This block of codeacts as one
statementandswaps the values inthe
variables aand b.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 23
BASIC OUTPUT / INPUT
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.
C++ uses a convenient abstraction called streams to perform input
and output operations in sequential media such as the screen or the
keyboard. A stream is an object where a program can either insert or
extract characters to/from it. We do not really need to care about many
specifications about the physical media associated with the stream - we
only need to know it will accept or provide characters sequentially.
The standard C++ library includes the header file iostream, where
the standard input and output stream objects are declared.
STANDARD OUTPUT (cout)
By default, the standard output of a program is the screen, and the
C++ stream object defined to access it is cout.
cout is used in conjunction with the insertion operator, which is written
as << (two "less than" signs).
1
2
3
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on
screen
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:
1
2
cout << "Hello"; // prints Hello
cout << Hello; // prints the content of Hello variable
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 24
The insertion operator (<<) may be used more than once in a single
statement:
cout << "Hello, " << "I am " << "a C++ statement";
This last statement would print the message:
Hello, I am a C++ statement
Additionally, to add a new-line, you may also use the endl manipulator. For
example:
1
2
cout << "First sentence." << endl;
cout << "Second sentence." << endl;
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.
STANDARD INPUT (cin)
The standard input device is usually the keyboard. Handling the
standard input in C++ is done by applying the overloaded operator of
extraction (>>) on the cin stream. The operator must be followed by the
variable that will store the data that is going to be extracted from the
stream. For example:
1
2
int age;
cin >> age;
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.
Would print out:
First sentence.
Second sentence.
The first statement declares a variable of type int called age,
and the second one waits for an input from cin (the keyboard)
in order to store it in this integer variable.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 25
Please enter an integer value: 12
and its double is : 144
is equivalent to:
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.
Sample
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// i/o example
#include <iostream.h>
#include <conio.h>
int main ()
{
int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is : " << i*2 << ".n";
getch();
}
cin >> a >> b; 1
2
cin >> a;
cin >> b;
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 26
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).
This statement assigns to variable a (the lvalue) the value contained in
variable b (the rvalue). The value that was stored until this moment
in a is not considered at all in this operation, and in fact that value is
lost.
OPERATORS
Once we know of the existence of variables and constants, we can
begin to operate with them. For that purpose, C++ integrates operators.
Unlike other languages whose operators are mainly keywords, operators in
C++ are mostly made of signs that are not part of the alphabet but are
available in all keyboards. This makes C++ code shorter and more
international, since it relies less on English words, but requires a little of
learning effort in the beginning.
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.
Assignments Operators (=)
An operator is a symbol that cause the compiler to take an action.
Operators act on operands, and in C++ all operands are expressions. In
C++ there are several different types of operators. These are:
o mathematical operators (+ , - , / , * )
o relational operators ( true or false statement)
o logical operators ( and, or, not )
a = 5;
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:
a = b;
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.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 27
Operations of addition, subtraction, multiplication and
division literally correspond with their respective
mathematical operators. The only one that you might
not be so used to see is modulo; whose operator is the
percentage sign (%). Modulo is the operation that gives
the remainder of a division of two values.
Arithmetic Operators (+, -, *, /, % )
The five arithmetical operations supported by the C++ language are:
Integer division and modulus
Integer division is somewhat different from everyday division. When you
divide 21 by 4, the result is a real number (a number with fraction part),
integers don’t have fractions, and so the “remainder” is looped off. The
answer is therefore 5. To get the remainder, you take 21 modulus (21 % 4)
and the result is 1. The modulus operator tells you the remainder after an
integer division.
Write the output of the given source code below.
+ addition
- subtraction
* multiplication
/ division
%modulo
// TRY THIS:
#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();
}
Write your output here:
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 28
are all equivalent in its functionality: the three of them increase by
one the value of c.
Prefix and Postfix
Compound Assignments
(+=,-=, *=, /=, %=, <<=, >>=, &=, ^=, |= )
When we want to modify the value of a variable by performing an
operation on the value currently stored in that variable we can use
compound assignment operators:
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);
Increment(++) and Decrement(--)
Shortening even more some expressions, the increase operator (++)
and the decrease operator (--) increase or reduce by one the value stored
in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:
Both the increment operator (++) and the decrement operator (--) come in
two varieties:
 Prefix – written before the variable name (++myage), Increment the
value and fetch it.
 Postfix – written after variable name (myage++), Fetch the value and
then increment the original
A characteristic of this operator is that it can be used both as a prefix
and as a suffix. That means that it can be written either before the variable
identifier (++a) or after it (a++). Although in simple expressions
like a++ or ++aboth have exactly the same meaning, in other expressions in
which the result of the increase or decrease operation is evaluated as a
value in an outer expression they may have an important difference in their
meaning: In the case that the increase operator is used as a prefix (++a)
the value is increased before the result of the expression is evaluated and
therefore the increased value is considered in the outer expression; in case
that it is used as a suffix (a++) the value stored in a is increased after being
evaluated and therefore the value stored before the increase operation is
evaluated in the outer expression. Notice the difference:
1
2
3
c++;
c+=1;
c=c+1;
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 29
Example 1 Example 2
B=3;
A=++B;
// A contains 4, B contains 4
B=3;
A=B++;
// A contains 3, B contains 4
In Example 1, B is increased before its value is copied to A. While in
Example 2, the value of B is copied to A and then B is increased.
What is the output of the given source code below.
#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();
}
Write your output here:
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 30
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
We may doubt if it really means:
1
2
a = 5 + (7 % 2) // with a result of 6, or
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
THE NATURE OF TRUTH
In C++, zero is considered false, and all other values are considered
true, although true is usually represented by 1. Thus if an expression is
false, it is equal to zero. And if an expression is equal to zero, it is false. If a
statement is true, all you know is that is nonzero, and any zero statement is
true.
Relational and Equality Operators
In order to evaluate a comparison between two expressions we can
use the relational and equality operators. The result of a relational operation
is a Boolean value that can only be true or false, according to its Boolean
result.
We may want to compare two expressions, for example, to know if
they are equal or if one is greater than the other is. Here is a list of the
relational and equality operators that can be used in C++:
==Equal to
!= Not equal to
> Greater than
< Less than
>=Greater than or equal to
<=Less than or equal to
1
2
3
4
5
(7 == 5) // evaluates to false.
(5 > 4) // evaluates to true.
(3 != 2) // evaluates to true.
(6 >= 6) // evaluates to true.
(5 < 5) // evaluates to false.
Here there are some examples:
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 31
Of course, instead of using only numeric constants, we can use any
valid expression, including variables.
Suppose that a=2, b=3 and c=6,
1
2
3
4
(a == 5) // evaluates to false since a is not equal to 5.
(a*b >= c) // evaluates to true since (2*3 >= 6) is true.
(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
((b=2) == a) // evaluates to true.
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:
1
2
3
4
!(5 == 5)// false because the expression at its right is true
!(6 <= // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
The logical operators && and || are used when evaluating two
expressions to obtain a single relational result.
&& OPERATOR
a b a && b
true true true
true false false
false true false
false false false
|| OPERATOR
a b a || b
true true true
true false true
false true true
false false false
The operator && corresponds with Boolean
logical operation AND. This operation results
true if both its two operands are true, and false
otherwise.
The operator || corresponds with Boolean logical
operation OR. This operation results true if either
one of its two operands is true, thus being false
only when both operands are false themselves
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 32
A. Suppose that a = 2, b = 3 and c = 4 evaluate the given expression
below. Write the word TRUE if the expression evaluates true otherwise
write FALSE
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)
B. Analyze and complete the table by writing the missing relational
operators below.
Suppose that a = 3, b = 4, c = 5 and d = 6
EXPRESSION 1 OPERATOR EXPRESSION 2 EVALUATION
(a==3) (a!=b) True
(c!=d) (c!=5) False
(a>1) (b==b) True
(!(b=c) (!(d=6) False
(c==c) (b>a) True
(b>a) (d>12) False
(d<10) (!(c=d) True
(c>=5) (b>=d) False
(a!=b) (!(c>d) True
(b>=b) (b!=a) False
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 33
LESSON 5
C++ Program Control Structures
Objectives:
At the end of this lesson, the student should be able to:
 Understand what control structure is.
 Differentiate types of Control Structures
 Know how to use and construct Control Structures
Control Strucuture
A program is usually not limited to a linear sequence of instructions.
During its process it may bifurcate, repeat code or take decisions. For that
purpose, C++ provides control structures that serve to specify what has to
be done by our program, when and under which circumstances.
With the introduction of control structures we are going to have to
introduce a new concept: the compound-statement or block. A block is a
group of statements which are separated by semicolons (;) like all C++
statements, but grouped together in a block enclosed in braces: { }.
{statement1; statement2; statement3;}
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.
Types of control structures
1. Sequence Structure
2. Selection /Conditional Structure
3. Repetition/Iteration Structure
SEQUENCE STRUCTURE
The instructions are executed sequentially starting from the first
instruction up to the last instruction in the program.
Entry ExitS1 S2 S3 S4
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 34
CONDITIONAL / SELECTION STRUCTURE
It performs different computations or actions depending on whether a
programmer-specified Boolean condition evaluates to true or false.
a. If Statement
The if keyword is used to execute a statement or block only if a condition
is fulfilled. Its form is:
Syntax:
if (condition) statement
Where condition is the expression that is being evaluated. If this condition
is true, statement is executed. If it is false, statement is ignored (not
executed) and the program continues right after this conditional structure.
If we want more than a single statement to be
executed in case that the condition is true we
can specify a block using braces { }:
# include <iostream.h>
#include<conio.h>
main ()
{
int grade;
clrscr();
cout<<” Enter a grade: “
cin>> grade;
If ( grade >=75)
cout << “ PASSED”;
If ( grade <75)
cout << “FAILED”;
getch ();
}
Write the output 1 here
Write the output 2 here
1
2
if (x == 100)
cout << "x is 100";
1
2
3
4
5
if (x == 100)
{
cout << "x is ";
cout << x;
}
The following code fragment prints x is
100 only if the value stored in the x variable is
indeed 100:
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 35
`
b. If Else Statement
It executes two statements in a program. If the condition is satisfied the
first statement will be executed otherwise, it will go to another statement.
We can additionally specify what we want to happen if the condition is not
fulfilled by using the keyword else. Its form used in conjunction with if is:
Syntax: if (condition)
statement 1;
else
statement 2;
For example:
1
2
3
4
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
# include <iostream.h>
#include<conio.h>
main ()
{
int num;
clrscr();
cout<<” Enter a Number: “
cin>> grade;
If ( num > 0)
cout << “Positive Number”;
else If ( grade < 0)
cout << “Negative Number”;
else
cout<<”That is 0”;
getch ();
}
Write the output 1 here (input positive # )
Write the output 2 here (input Negative # )
Write the output 3 here (input zero )
Prints on the screen x is 100 if
indeed x has a value of 100, but if it
has not -and only if not- it prints out x
is not 100.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 36
c. Else If Statement
Usually it is used to execute if you have three or more statement to be
executed in the program.
The if + else structured can be concatenated with the intention of verifying
a range of values. The following example shows its use telling if the value
currently stored in x is positive, negative or none of them (i.e zero):
1
2
3
4
5
6
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
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 { }.
#include<iostream.h>
#include<conio.h>
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();
}
Write all the possible output
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 37
SAMPLE OUTPUT
SAMPLE OUTPUT
PROBLEM 1 :
Create a program that will compute
your age and will display if you are a
minor or a legal age. Refer your source
code on the given output. Write your
program on the box below
Enter Your Birth Year : 1990
Enter Present Year : 2012
Your age is : 22 years old
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
________________________________________________
________________________________________________
________________________________________________
________________________________________________
________________________________________________
________________________________________________
_______________________________________________
________________________________________________
________________________________________________
________________________________________________
________________________________________________
________________________________________________
________________________________________________
________________________________________________
________________________________________________
__________________________
________________________________________________
Enter a number : 5
That is odd number
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 38
d. Switch Case Statement
Its objective is to check several possible constant values for an
expression. Its form is the
e.
f.
g.
h.
i.
j.
k.
l.
m.
n.
o.
p. Both of the following code fr
q.
r.
s.
t.
Both of the following code fragments have the same behavior
The switch case statement is a bit peculiar within C++ language
because it uses labels instead of blocks. This forces us to put break
statements after the group of statements that we want to be executed
for a specific condition. Otherwise the remaining statements –
including those corresponding to other labels - will also be executed
until the end of the switch selective block or a break statement is
reached.
Switch (expression)
{
Case constant 1:
Group of statements
1;
Break;
Case constant 2:
Group of statement 2;
Break
-
-
-
Default:
Default group of
statements
}
It works in the following way:
1. Switch evaluates expression and
checks if its equivalent to constant1,
if it is, it executes group of
statements1 until it finds the break
statement. When it finds this break
statement the program jumps to the
end of the switch selective structure.
2. If expression is not equal to constant
1 it will be check against constant2 if
its equal to this, it will execute group
of statements2 until break keyword is
found, then will jump to the end of
the switch selective structure.
3. Finally, if the value of expression did
not match any of the previously
specified constants, the program will
execute the statements included
after the default.
SWITCH CASE SAMPLE
switch(x)
case
cout<<”x is 1”;
break;
case
cout<<”x is 2”;
break
default:
cout<<”value of x
is unknown”;
}
If – else equivalent
{
If (x == 1)
{
Cout<<”x is 1”;
}
Else if (x == 2)
{
Cout<<”x is 2”;
}
Else
{
Cout<<”value of x
is unknown”;
}
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 39
Create a source code of the following output. Write you program on the box
below.
SAMPLE OUTPUT
SOURCE CODE:
[A] – ADDITION
[S] – SUBTRACTION
[M] – MULTIPLICATION
[D] – DIVISION
ENTER OPERATION : M
ENTER NUM 1 : 5
ENTER NUM 2 : 10
THE PRODUCT IS : 50
[A] – ADDITION
[S] – SUBTRACTION
[M] – MULTIPLICATION
[D] – DIVISION
ENTER OPERATION : W
INVALID ENTRY
[A] – ADDITION
[S] – SUBTRACTION
[M] – MULTIPLICATION
[D] – DIVISION
ENTER OPERATION : A
ENTER NUM 1 : 12
ENTER NUM 2 : 13
THE SUM IS : 25
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
_________________________
____________________________________________________________________________
________
____________________________________________________________________________
________
____________________________________________________________________________
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 40
LESSON 6
ITERATION / REPETITION STRUCTURE
Objectives:
At the end of this lesson, the student should be able to:
 Learn The Different Types of Repetitions Structure
 Differentiate the repetition from selection structure
 Apply The syntax of different repetition structure in creating a
complex program.
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
goto allows to make an absolute jump to another point in the
program. You should use this feature with caution since its execution causes
an unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an
argument for the goto statement. A label is made of a valid identifier
followed by a colon (:).
Generally speaking, this instruction has no concrete use in structured
or object oriented programming aside from those that low-level
programming fans may find for it. For example, here is our countdown loop
using goto:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// goto loop example
#include <iostream.h>
#include <conio.h>
int main ()
{
int n=10;
loop:
cout << n << ",n ";
n--;
if (n>0) goto loop;
cout << "FIRE!n";
getch();
}
10,
9,
8,
7,
6,
5,
4,
3,
2,
1,
FIRE!
NOTE. Use of goto is almost a sign of bad design. The advice is avoid using it
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 41
The exit function
exit is a function defined in the cstdlib library.
The purpose of exit is to terminate the current program with a specific exit
code. Its prototype is:
void exit (int exitcode);
The exitcode is used by some operating systems and may be used by
calling programs. By convention, an exit code of 0 means that the program
finished normally and any other value means that some error or unexpected
results happened.
THE REPETITION CONTROL STRUCTURE
also known as the looping or iteration control structure. Looping is
the process of repeatedly executing one or more steps of an algorithm or
program; it is essential in programming, as most programs perform
repetitious tasks.
Every loop consists of the following three parts:
1. The loop termination decision - determines when (under what
condition) the loop will be terminated (stopped). It is essential that
some provision in the program be made for the loop to stop;
otherwise, the computer would continue to execute the loop
indefinitely - a loop that doesn't stop is called an endless
loop or infinite loop; when a program gets stuck in an endless loop,
programmers say that the program is "looping".
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.
3. Transfer back to the beginning of the loop - returns control to the
top of the loop so that a new repetition (iteration) can begin.
Three types of repetition Structure
1. While Loop
2. Do Loop
3. For Loop
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 42
1. THE WHILE LOOP
Its Syntax is:
while (expression) statement
and its functionality is simply to repeat statement while the condition set in
expression is true.
For example
we are going to make a program to countdown using a while-loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// custom countdown using while
#include <iostream>
include <conio>
int main ()
{
int n;
cout << "Enter a number > ";
cin >> n;
while (n>0) {
cout << n << "/n";
--n;
}
cout << "FIRE!n";
getch();
}
Enter a number > 8
8
7
6
5
4
3
2
1
FIRE!
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.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 43
The whole process of the previous program can be interpreted according to
the following script (beginning in main):
User assigns a value to n
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.
When creating a while-loop, we must always consider that it has to end
at some point, therefore we must provide within the block some method to
force the condition to become false at some point, otherwise the loop will
continue looping forever. In this case we have included --n; that decreases
the value of the variable that is being evaluated in the condition (n) by one
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// custom countdown using while
#include <iostream>
include <conio>
int main ()
{
int n;
cout << "Enter a number :> ";
cin >> n;
while (n>0) {
cout <<"ICCT COLLEGES";
--n;
}
cout << "FIRE!n";
gecth();
}
What is the output?
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 44
The break statement
Using break we can leave a loop even if the condition for its end is
not fulfilled. It can be used to end an infinite loop, or to force it to end
before its natural end. For example, we are going to stop the count down
before its natural end (maybe because of an engine check failure?):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// break loop example
#include <iostream>
#include <conio>
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << "n";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
Getch;
}
What is the output?
The continue statement
The continue statement causes the program to skip the rest of the
loop in the current iteration as if the end of the statement block had been
reached, causing it to jump to the start of the following iteration. For
example, we are going to skip the number 5 in our countdown:
1
2
3
4
5
6
7
8
9
10
11
12
13
// continue loop example
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!n";
return 0;
}
What is the output?
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 45
2. THE DO-WHILE LOOP
Its Syntax is:
do statement while (condition);
Its functionality is exactly the same as the while loop, except
that condition in the do-while loop is evaluated after the execution of
statement instead of before, granting at least one execution
of statement even if condition is never fulfilled. For example, the
following example program echoes any number you enter until you enter 0.
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.
3. THE FOR LOOP
Its syntax is:
for (initialization; condition; increase) statement;
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// number echoer
#include <iostream>
include <conio>
int main ()
{
unsigned long n;
do {
cout << "Enter number: ";
cin >> n;
cout << "You entered: "<n<<n";
} while (n != 0);
Getch;
}
What is the output?
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 46
It works in the following way:
1. initialization is executed. Generally it is an initial value setting for
a counter variable. This is executed only once.
2. condition is checked. If it is true the loop continues, otherwise the
loop ends and statement is skipped (not executed).
3. statement is executed. As usual, it can be either a single statement
or a block enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed and the
loop gets back to step 2.
Here is an example of countdown using a for loop:
1
2
3
4
5
6
7
8
9
10
11
// countdown using a for loop
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!n";
return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
FIRE!
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:
1
2
3
4
for ( n=0, i=100 ; n!=i ; n++, i-- )
{
// whatever here...
}
This loop will execute for 50 times if neither n or i are modified within the
loop:
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 47
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 :
ENTER YOUR NAME: CARLOS
ENTER HOW MANY TIMES YOU WANT TO DISPLAY YOUR NAME: 5
DISPLAY CARLOS 0 and 5 ONLY
DISPLAY CARLOS 1 and 4 ONLY
DISPLAY CARLOS 2 and 3 ONLY
DISPLAY CARLOS 3 and 2 ONLY
DISPLAY CARLOS 4 and 1 ONLY
DISPLAY CARLOS 5 and 0 ONLY
END OF YOUR NAME!!!
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 48
LESSON 7
THE ARRAY
Objectives:
At the end of this lesson, the student should be able to:
 Learn what array is and what it does.
 Learn how to use array in a program
What is Array?
An array is a series of elements of the same type placed in contiguous
memory locations that can be individually referenced by adding an index to
a unique identifier.
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 each blank panel represents an element of the array, that in
this case are integer values of type int. These elements are numbered
from 0 to 4 since in arrays the first index is always 0, independently of its
length. Like a regular variable, an array must be declared before it is used.
A typical declaration for an array in C++ is:
type name [elements];
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.
Therefore, in order to declare an array called CARLOS as the one
shown in the above diagram it is as simple as:
int CARLOS [5];
For example, an array to contain 5 integer values of Type int called
CARLOS could be represented like this:
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 49
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
When declaring a regular array of local scope (within a function, for
example), if we do not specify otherwise, its elements will not be initialized
to any value by default, so their content will be undetermined until we store
some value in them. The elements of global and static arrays, on the other
hand, are automatically initialized with their default values, which for all
fundamental types this means they are filled with zeros.
In both cases, local and global, when we declare an array, we have
the possibility to assign initial values to each one of its elements by
enclosing the values in braces { }. For example:
int CARLOS [5] = { 16, 2, 77, 40, 12071 };
This declaration would have created an array like this:
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 { }:
int CARLOS [] = { 16, 2, 77, 40, 12071 };
After this declaration, array CARLOS would be 5 ints long, since we have
provided 5 initialization values.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 50
Accessing the values of an array
In any point of a program in which an array is visible, we can access
the value of any of its elements individually as if it was a normal variable,
thus being able to both read and modify its value. The format is as simple
as:
name[index]
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];
Therefore, the expression CARLOS[2] is for all purposes like a variable of
type int.
Notice that the third element of CARLOS is specified CARLOS[2], since
the first one is CARLOS[0], the second one isCARLOS[1], and therefore, the
third one is CARLOS[2]. By this same reason, its last element is CARLOS[4].
Therefore, if we write CARLOS[5], we would be accessing the sixth element
of CARLOS and therefore exceeding the size of the array.
In C++ it is syntactically correct to exceed the valid range of indices
for an array. This can create problems, since accessing out-of-range
elements do not cause compilation errors but can cause runtime errors. The
reason why this is allowed will be seen further ahead when we begin to use
pointers.
INTRODUCTION TO COMPUTERSCIENCE C++ Programming
ICCT COLLEGES 51
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.
1
2
int CARLOS[5]; // declaration of a new array
CARLOS[2] = 75; // access to an element of the array.
If you read carefully, you will see that a type specifier always precedes a
variable or array declaration, while it never precedes an access.
Some other valid operations with arrays:
1
2
3
4
CARLOS[0] = a;
CARLOS[a] = 75;
b = CARLOS [a+2];
CARLOS[CARLOS[a]] = CARLOS[2] + 5;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// arrays example
#include <iostream>
#include<conio>
int CARLOS [] = {16, 2, 77, 40,
12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += CARLOS[n];
}
cout << result;
gecth();
}
WHAT IS THE OUTPUT?

More Related Content

What's hot

Highlights in Computer History
Highlights in Computer HistoryHighlights in Computer History
Highlights in Computer History
Buffalo Seminary
 
The American Colonization in the Philippines
The American Colonization in the PhilippinesThe American Colonization in the Philippines
The American Colonization in the Philippines
liliemanna
 

What's hot (20)

computer languages
computer languagescomputer languages
computer languages
 
Programming languages and paradigms
Programming languages and paradigmsProgramming languages and paradigms
Programming languages and paradigms
 
Macario's Noche Buena by Tarcila Malabanan Katigbak
Macario's Noche Buena by Tarcila Malabanan KatigbakMacario's Noche Buena by Tarcila Malabanan Katigbak
Macario's Noche Buena by Tarcila Malabanan Katigbak
 
Living in the IT Era - Lesson 2.pptx
Living in the IT Era - Lesson 2.pptxLiving in the IT Era - Lesson 2.pptx
Living in the IT Era - Lesson 2.pptx
 
Highlights in Computer History
Highlights in Computer HistoryHighlights in Computer History
Highlights in Computer History
 
Chapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to ProgrammingChapter 1 - An Introduction to Programming
Chapter 1 - An Introduction to Programming
 
Struggle And Survival
Struggle And SurvivalStruggle And Survival
Struggle And Survival
 
Computer languages
Computer languagesComputer languages
Computer languages
 
Ge 7
Ge 7Ge 7
Ge 7
 
Mga Gunita ng HimagsikanTrue Version of the Philippine Revolution (1).pdf
Mga Gunita ng HimagsikanTrue Version of the Philippine Revolution (1).pdfMga Gunita ng HimagsikanTrue Version of the Philippine Revolution (1).pdf
Mga Gunita ng HimagsikanTrue Version of the Philippine Revolution (1).pdf
 
Presentation of programming languages for beginners
Presentation of programming languages for beginnersPresentation of programming languages for beginners
Presentation of programming languages for beginners
 
Living in the IT Era - Lesson 3.pptx
Living in the IT Era - Lesson 3.pptxLiving in the IT Era - Lesson 3.pptx
Living in the IT Era - Lesson 3.pptx
 
Maintain Computer Systems and Network.ppt
Maintain Computer Systems and Network.pptMaintain Computer Systems and Network.ppt
Maintain Computer Systems and Network.ppt
 
Propaganda
PropagandaPropaganda
Propaganda
 
Maintaining computer and network system
Maintaining computer and network systemMaintaining computer and network system
Maintaining computer and network system
 
The American Colonization in the Philippines
The American Colonization in the PhilippinesThe American Colonization in the Philippines
The American Colonization in the Philippines
 
Materials, tools, equipment and testing devices
Materials, tools, equipment and testing devicesMaterials, tools, equipment and testing devices
Materials, tools, equipment and testing devices
 
History of Programming Language
History of Programming LanguageHistory of Programming Language
History of Programming Language
 
Rediscovery of the philippines
Rediscovery of the philippinesRediscovery of the philippines
Rediscovery of the philippines
 
Ict 9 module 4, lesson 1.3 diagnosing computer systems
Ict 9 module 4, lesson 1.3 diagnosing computer systemsIct 9 module 4, lesson 1.3 diagnosing computer systems
Ict 9 module 4, lesson 1.3 diagnosing computer systems
 

Similar to Comso c++

Programming lesson1
Programming lesson1Programming lesson1
Programming lesson1
camfollower
 

Similar to Comso c++ (20)

Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
Ic lecture8
Ic lecture8 Ic lecture8
Ic lecture8
 
Stnotes doc 5
Stnotes doc 5Stnotes doc 5
Stnotes doc 5
 
PROBLEM SOLVING
PROBLEM SOLVINGPROBLEM SOLVING
PROBLEM SOLVING
 
WEBSITE DEVELOPMENT
WEBSITE DEVELOPMENTWEBSITE DEVELOPMENT
WEBSITE DEVELOPMENT
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Programming in C
Programming in CProgramming in C
Programming in C
 
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdfINTRODUCTION TO C PROGRAMMING MATERIAL.pdf
INTRODUCTION TO C PROGRAMMING MATERIAL.pdf
 
CS3251-_PIC
CS3251-_PICCS3251-_PIC
CS3251-_PIC
 
Software programming and development
Software programming and developmentSoftware programming and development
Software programming and development
 
Programming lesson1
Programming lesson1Programming lesson1
Programming lesson1
 
C lecture notes new
C lecture notes newC lecture notes new
C lecture notes new
 
Introduction to Computer
Introduction to ComputerIntroduction to Computer
Introduction to Computer
 
C.pdf
C.pdfC.pdf
C.pdf
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)
 
Introduction to Computer Programming
Introduction to Computer ProgrammingIntroduction to Computer Programming
Introduction to Computer Programming
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
 
An introduction to programming
An introduction to programmingAn introduction to programming
An introduction to programming
 
C programming
C programmingC programming
C programming
 

More from Mi L

Techniques for better classroom discipline
Techniques for better classroom discipline Techniques for better classroom discipline
Techniques for better classroom discipline
Mi L
 
Business statistic survey sample
Business statistic survey sampleBusiness statistic survey sample
Business statistic survey sample
Mi L
 
Business statistic
Business statisticBusiness statistic
Business statistic
Mi L
 
Case study management
Case study managementCase study management
Case study management
Mi L
 

More from Mi L (20)

Stock exchange
Stock exchangeStock exchange
Stock exchange
 
Japanese Model
Japanese ModelJapanese Model
Japanese Model
 
Elements of Short story
Elements of Short storyElements of Short story
Elements of Short story
 
Elements of Poetry
Elements of PoetryElements of Poetry
Elements of Poetry
 
Philippines and japan literature
Philippines and japan literaturePhilippines and japan literature
Philippines and japan literature
 
Elements of Literature
Elements of  LiteratureElements of  Literature
Elements of Literature
 
Elements of Novel
Elements of NovelElements of Novel
Elements of Novel
 
Elements of Essay
Elements of EssayElements of Essay
Elements of Essay
 
Elements of Drama
Elements of DramaElements of Drama
Elements of Drama
 
Techniques for better classroom discipline
Techniques for better classroom discipline Techniques for better classroom discipline
Techniques for better classroom discipline
 
Katangian ng wika
Katangian ng wikaKatangian ng wika
Katangian ng wika
 
Special behavioral problems of Student
Special behavioral problems of StudentSpecial behavioral problems of Student
Special behavioral problems of Student
 
Financial Management report
Financial Management reportFinancial Management report
Financial Management report
 
Alamat ng langka
Alamat ng langkaAlamat ng langka
Alamat ng langka
 
Sun
SunSun
Sun
 
Biag ni lam
Biag ni lamBiag ni lam
Biag ni lam
 
Business statistic survey sample
Business statistic survey sampleBusiness statistic survey sample
Business statistic survey sample
 
Business statistic
Business statisticBusiness statistic
Business statistic
 
Case study management
Case study managementCase study management
Case study management
 
Economics
EconomicsEconomics
Economics
 

Recently uploaded

VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 
( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...
( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...
( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...
nilamkumrai
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 

Recently uploaded (20)

Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
Pirangut | Call Girls Pune Phone No 8005736733 Elite Escort Service Available...
 
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
Yerawada ] Independent Escorts in Pune - Book 8005736733 Call Girls Available...
 
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
 
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
 
( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...
( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...
( Pune ) VIP Pimpri Chinchwad Call Girls 🎗️ 9352988975 Sizzling | Escorts | G...
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
 

Comso c++

  • 1. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 1 LESSON 1 COMPUTER PROGRAM / PROGRAMMING Objectives: At the end of this lesson, the student should be able to:  Have a better understanding of what program is.  know what are the steps in problem solving INTRODUCTION Nowadays computers are able to perform many different tasks, from simple mathematical operations to sophisticated animated simulations. But the computer does not create these tasks by itself, these are performed following a series of predefined instructions that conform what we call a program. A computer does not have enough creativity to make tasks which it has not been programmed for, so it can only follow the instructions of programs which it has been programmed to run. Those in charge of generating programs so that the computers may perform new tasks are known as programmers or coders, who for that purpose use a programming language. WHAT IS PROGRAM? The word program is used in two ways: 1. to describe individual instructions, or source code, created by the programmer, and to 2. describe an entire piece of executable software. Source code can be turned into an executable program in two ways: 1. Interpreters translate the source code into computer instructions, and the computer acts on those instructions immediately. Alternatively, 2. Compilers translate source code into a program, which you can run at a later time. While interpreters are easier to work with, most serious programming is done with compilers because compiled code runs much faster. C++ is a compiled language.
  • 2. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 2 DIAGRAM 1. Compiler vs Interpreter 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 All programming involves creating something that solves a problem. The problems can range from something of great scientific or national importance, through to something as trivial as relieving personal boredom! This section describes one approach to solving such problems - think of it as a rough guide to the things you should do when entering the land of programming.
  • 3. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 3 The programming process consists of 5 steps. These are really only guidelines that have come to be recognized as being part of writing good, easily understood, and useful computer programs. 1] Define the Problem The programmer prepares a problem statement outlining the answers to the following questions: 1. What is the job to be done? 2. What is the input data to be processed? 3. How is the data to be processed? 4. What is the desired format of the output? 2] Analyze the Problem A plan of action is prepared describing the processing sequence of the operations. The plan may be in the form of a 1. Decision table – presents a complex situation, the conditions and the corresponding actions. 2. Flowchart – shows the sequence of operations. 3] Code the Program The sequence of operations contained in the flowchart is translated into a set of instructions written in symbolic languages like COBOL, BASIC, C, C++, etc. This program is then loaded into the memory of a computer where a compiler program translates this set of instructions into machine readable form. 4] Debug and Test the Program Programs are tested to locate and correct programming errors or bugs. programming errors are due to: 1. Clerical error – Ex. Assigning the same statement number to two instructions 2. Logical error – ex. Omitting certain facts important to the whole system in a payroll application. Types of Errors 30 1. Compile-time error or syntax errors  occur if there is a syntax error in the code.  The compiler will detect the error and the program won't even compile. At this point, the programmer is unable to form an executable program that a user can run until the error is fixed.
  • 4. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 4 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 Debugging is done using these methods: a. Desk checking – manual review of the program b. Diagnostics – computer prints out error messages through the computer programs. 5] Document the Program All data pertaining to a program are collected, organized, and recorded. A complete documentation gives the following advantages: 1. Simplifies program revision 2. Enables another programmer to modify or maintain the program. 3. Facilitates the operation of the program by the operator. 4. Minimizes need for major program overhaul. Coding - is the act of translating the design into an actual program, written in some form of programming language. This is the step where you actually have to sit down at the computer and type! Programming - is then the task of describing your design to the computer: teaching it your way of solving the problem Compilation - is actually the process of turning the program written in some programming language into the instructions made up of 0's and 1's that the computer can actually follow. Debugging - is simply the task of looking at the original program, identifying the mistakes, correcting the code and recompiling it. Code - The instructions in a computer program. Instructions written by a programmer in a programming language are often called source code. Instructions that have been converted into machine language that the computer understands are called machine code or executable code. DEFINITION OF TERMS
  • 5. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 5 LESSON 2 INTRODUCTION TO C++ PROGRAMMING LANGUAGE Objectives: At the end of this lesson, the student should be able to:  Learn why C++ is the emerging standard in software development.  Have a good understanding of how C++ evolved and what problems it was designed to solve.  Identify the parts of the C++ on-screen editor and know the basic commands used. Background: Computer languages have undergone dramatic evolution since the first electronic computers were built to assist in telemetry calculations during World War II. Early on, programmers worked with the most primitive computer instructions: machine language. These instructions were represented by long strings of ones and zeroes. Soon, assemblers were invented to map machine instructions to human-readable and manageable mnemonics, such as ADD and MOV. In time, higher-level languages evolved, such as BASIC and COBOL. These languages let people work with something approximating words and sentences, such as Let I = 100. These instructions were translated back into machine language by interpreters and compilers. An interpreter translates a program as it reads it, turning the program instructions, or code, directly into actions. A compiler translates the code into an intermediary form. This step is called compiling, and produces an object file. The compiler then invokes a linker, which turns the object file into an executable program. Because interpreters read the code as it is written and execute the code on the spot, interpreters are easy for the programmer to work with. Compilers, however, introduce the extra steps of compiling and linking the code, which is inconvenient. Compilers produce a program that is very fast each time it is run. However, the time-consuming task of translating the source code into machine language has already been accomplished. Another advantage of many compiled languages like C++ is that you can distribute the executable program to people who don't have the compiler. With an interpretive language, you must have the language to run the program.
  • 6. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 6 For many years, the principle goal of computer programmers was to write short pieces of code that would execute quickly. The program needed to be small, because memory was expensive, and it needed to be fast, because processing power was also expensive. As computers have become smaller, cheaper, and faster, and as the cost of memory has fallen, these priorities have changed. Today the cost of a programmer's time far outweighs the cost of most of the computers in use by businesses. Well- written, easy-to-maintain code is at a premium. Easy- to-maintain means that as business requirements change, the program can be extended and enhanced without great expense. How c ++ evolved?  The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity to work with was a language called Simula, which as the name implies is a language primarily designed for simulations.The Simula 67 language - which was the variant that Stroustrup worked with - is regarded as the first language to support the object-oriented programming paradigm. Stroustrup found that this paradigm was very useful for software development, however the Simula language was far too slow for practical use.  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).  In 1985, Stroustrup's reference to the language entitled The C++ Programming Language was published. That same year, C++ was implemented as a comercial product. The language was not officially standardized yet, making the book a very important reference. The language was updated again in 1989 to include protected and static members, as well as inheritance from several classes.
  • 7. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 7  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.  In 1998, the C++ standards committee published the first international standard for C++ ISO/IEC 14882:1998, which would be informally known as C++98.  In 2005, the C++ standards committee released a technical report (dubbed TR1) detailing various features they were planning to add to the latest C++ standard. The new standard was informally dubbed C++0x as it was expected to be released sometime before the end of the first decade. Ironically, however, the new standard would not be released until mid-2011. Several technical reports were released up until then, and some compilers began adding experimental support for the new features.  In mid-2011, the new C++ standard (dubbed C++11) was finished. The Boost library project made a considerable impact on the new standard, and some of the new modules were derived directly from the corresponding Boost libraries. Some of the new features included regular expression support (details on regular expressions may be found here), a comprehensive randomization library, a new C++ time library, atomics support, a standard threading library (which up until 2011 both C and C++ were lacking), a new for loop syntax providing functionality similar to for each loops in certain other languages, the auto keyword, new container classes, better support for unions and array-initialization lists, and varied templates. The ANSI Standard The Accredited Standards Committee, operating under the procedures of the American National Standards Institute (ANSI), is working to create an international standard for C++. The ANSI standard is an attempt to ensure the C++ is portable--that code you write for Microsoft's Compiler will compile without errors, using a compiler from any other vendor.
  • 8. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 8 THE C++ INTEGRATED DEVELOPMENT ENVIRONMENT PARTS FUNCTION/USAGE 1 Menu Bar Is a region on top of a screen where drop down list of menus are displayed. 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. 4 Desktop/Editor The area in the middle of screen at which several list of different types of windows can be placed. 5 Frame Serves as a window border 6 Resize Corner It is used to change the size of the active window. 7 Message Compiler Window lies beneath the edit window and is used to display various compiler or linker messages 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. 10 Scroll bar Used to scroll the content of the window horizontally or vertically. 11 Zoom Box Used to view the window to a full screen
  • 9. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 9 SHORT CUT KEY COMMANDS How to : Method Activate the menu bar Press F10 Select a menu from the menu bar Method 1: Press F10  Use the arrow keys to select the menu  Press the ENTER key and the submenu appears Method 2: Press ALT + the highlighted key of choice in the menu ( ex. ALT + F for File menu ) Select a command from the submenu Press ALT + the highlighted key of choice in the menu  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)
  • 10. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 10 LESSON 3 GETTING STARTED WITH C++ PROGRAM Objectives: At the end of this lesson, the student should be able to:  Define identifiers know its importance  Know what the reserve words are and how to use data types.  Know how to define and declare variables and constants in a program. KEYWORDS Keywords are predefined reserved identifiers that have special meanings. They cannot be used as identifiers in your program. Reserved words Words “reserved” by the programming language for expressing various statements and constructs, thus they may not be redefined by the programmer. The standard reserved keywords are: asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved words under some circumstances: 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.
  • 11. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 11 IDENTIFIERS  composed of a sequence of letters, digits, and the special character _(underscore)  these are defined by the programmer, thus they should be descriptive.  It must consist only of letters, digits and underscores  It cannot begin with a digit or underscore.  An identifier defined in the C++ standard library should not be redefined. Very important: The C++ language is a "case sensitive" language. That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters. Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different variable identifiers. DATA TYPE (Most Commonly Used) Defines as the set of values that a variable can store along with a set of operations that can be performed on that variable. Table 1. Commonly used data types. 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
  • 12. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 12 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. Type Typical Bit Width Typical Range char 1byte -127 to 127 or 0 to 255 int 4bytes -2147483648 to 2147483647 long int 4bytes -2,147,483,647 to 2,147,483,647 float 4bytes +/- 3.4e +/- 38 (~7 digits) double 8bytes +/- 1.7e +/- 308 (~15 digits) Table 2. Data types typical range 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. C++ BACKSLASH CODE Sample code CODE MEANING a alert (bell) n newline b backspace f formfeed r carriage return t tab Output v vertical tab backslash ’ single quote mark ” double quote mark 0 null #include<iostream.h> #include<conio.h> main() { cout<<”HnEnLnLnO”; cout<<”t”WORLD””; getch(); } H E L L O “WORLD”
  • 13. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 13 DATA VALUES VARIABLES - identifiers that can store value that can be changed and can store literals or some type of structured data. Variable declaration  consist of a data type and a variable name.  The effect is that it reserves memory space for each of the variable it declares. In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid variable identifier. Format: <data type> <variable_name> ; For example: 1 2 int a; float mynumber; 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; C++ assignment statement  may be used to assign values to variables of any types. Format: <variable> = Ex.: num1 = num; num2 = 23; num3 = tot1 + tot2; 1 2 3 int a; int b; int c; Constant Variable Arithmetic expression These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber. Once declared, the variables a and mynumber can be used within the rest of their scope in the program. This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:
  • 14. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 14 SCOPE OF VARIABLES All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous code at the beginning of the body of the function main when we declared that a, b, and result were of type int. A variable can be either of global or local scope. A. A global variable is a variable declared in the main body of the source code, outside all functions. B. A local variable is one declared within the body of a function or a block. Diagram 2. 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.
  • 15. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 15 CONSTANTS Constants are expressions with a fixed value. It is identifiers that can store values that cannot be changed. Usually are all capital letters with underscores between each word to distinguished from variable. Ex. char LETTER = ‘I’; int MILES = 23; There are two simple ways in C++ to define constants: 1. Using const keyword. 2. Using #define preprocessor. 1. Declared Constant (const) With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: 1 2 const int pathwidth = 100; const char tabulator = 't'; 2. #define DIRECTIVE  Directs the compiler to replaces all the instances of constant_identifier with literal value whenever it appears in the program.  The main use to a #define directive is to make it easy for the programmer to change all occurrences of a certain value throughout a program.  A #define line can occur anywhere in a program, but are normally placed at column 1. it affects only those lines that come after it. Format: #define constant_identifier literal Ex.: #define SCHOOL “ICCT Colleges” #define INITIAL ‘I’ Sample code Output int a, b; #define a 1; #define b 2; cout<<”The Sum is : “<<a+b; char a; #define a ”HELLO WORLD”; cout<<”The Sum is : “<<a; The Sum is : 3 HELLO WORLD Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.
  • 16. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 16 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 = 5; Literal constants can be divided in Numeric Literals, Non-Numeric Literal and the Boolean Literals A. Numeric Literals Can be further sub divided into Whole Numbers and Real Numbers. 1.) Whole Numbers or Integer Numerals There is no doubt that it is a constant: whenever we write 1776 in a program, we will be referring to the value 1776. 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: 1 2 3 75 // decimal 0113 // octal 0x4b // hexadecimal 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 /: 75 // int 75u // unsigned int 75l // long 1 2 3 1776 707 -273 The 5 in this piece of code was a literal constant. All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively. They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we do not have to write quotes (") nor any special character. In both cases, the suffix can be specified using either upper or lowercase letters.
  • 17. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 17 2.) Real Numbers or Floating Point Literals They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character: 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: In defining numeric literals, the following rules should be followed: 1] No comma. 2] No space between the unary sign (+ or -) and the digits. 3] Must begin and end with a digit. B. Non-Numeric Literals May be in the form of a character or a series of characters(Strings). 'z' 'p' "Hello world" "How do you do?" 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. 1 2 3 4 3.14159 // 3.14159 6.02e23 // 6.02 x 10^23 1.6e-19 // 1.6 x 10^-19 3.0 // 3.0 1 2 3.14159L // long double 6.02e23f // float These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated- and the last one is the number three expressed as a floating-point numeric literal. Any of the letters that can be part of a floating point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings. The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes (").
  • 18. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 18 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: 1 2 3 4 5 6 7 8 9 10 // my first program in C++ #include <iostream.h> #include <conio.h> int main () { cout << "Hello World!"; getch(); } Hello World! 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. 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. Instruct C++ to include the header file conio.h during compilation and from which getch() function is also defined in conio.h Rules when inserting #include directive into a program: a. There must be no space between the hash character # from the include keyword. b. The # must begin in column 1 of the source file and there must be no preceding blanks or tabs. // my first program in C++ #include<iostream.h>
  • 19. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 19 This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it - the instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function. The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++, what differentiates a function declaration from other types of expressions are these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within them. 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. This line is a C++ statement. A statement is a simple or compound expression that can actually produce some effect. In fact, this statement performs the only action that generates a visible effect in our first program. 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. int main () cout << " Hello World!";
  • 20. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 20 The program has been structured in different lines in order to be more readable, but in C++, we do not have strict rules on how to separate instructions in different lines. For example, instead of 1 2 3 4 5 int main () { cout << " Hello World!"; getch(); } We could have written: int main () { cout << "Hello World!"; return 0; } All in just one line and this would have had exactly the same meaning as the previous code. Using the sample program “Hello World” on the previous lesson, create your own program that will display your Name, Address, Gender, Birthday, Course, Year, Height and Weight. Refer your code on the sample target output below. SAMPLE TARGET OUTPUT: Name : Ernanie Carlos Address : Rosario, Pasig City Gender : Male Birthday : January 17, 1990 Course : BSIT Year : 4th year Height : 5’11 Weight : 60 kgs
  • 21. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 21 What is comments? Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. C++ supports two ways to insert comments: 1 2 // line comment /* block comment */ 1. The first of them, known as line comment, discards everything from where the pair of slash signs (//) is found up to the end of that same line. 2. The second one, known as block comment, discards everything between the /*characters and the first appearance of the */ characters, with the possibility of including more than one line. Example: Note: If you include comments within the source code of your programs without using the comment characters combinations //, /* or */, the compiler will take them as if they were C++ expressions, most likely causing one or several error messages when you compile it. 1 2 3 4 5 6 7 8 9 10 11 12 /* my second program in C++ with more comments */ #include <iostream> #include<conio.h> int main () { cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program getch(); } Hello World! I'm a C++ program
  • 22. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 22 LESSON 4 C++ OPERATORS, EXPRESSION, STATEMENTS, STANDARD INPUT AND OUTPUT Objectives: At the end of this lesson, the student should be able to:  Know what expression is.  Know how to construct block of statements  Know the difference of integer division and the use of modulus  Know how to combine mathematical and assignment operators  Know the difference between increment and decrement and postfix from prefix.  How to use the standard input and output in a complex program. BLOCK AND COMPOUND STATEMENT 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: EXPRESSIONS Anything that evaluates to a value is an expression in C++. An expression is said to return a value. Thus, 3+2’ returns the value of 5 and so is an expression. All expressions are statements. Here are three examples: 3.2 // returns the value 3.2 PI // float const that the value 3.14 Seconds per minute //int const that returns 60 { temp = a; a = b; b = temp; } This block of codeacts as one statementandswaps the values inthe variables aand b.
  • 23. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 23 BASIC OUTPUT / INPUT 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. C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen or the keyboard. A stream is an object where a program can either insert or extract characters to/from it. We do not really need to care about many specifications about the physical media associated with the stream - we only need to know it will accept or provide characters sequentially. The standard C++ library includes the header file iostream, where the standard input and output stream objects are declared. STANDARD OUTPUT (cout) By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout. cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs). 1 2 3 cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen 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: 1 2 cout << "Hello"; // prints Hello cout << Hello; // prints the content of Hello variable
  • 24. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 24 The insertion operator (<<) may be used more than once in a single statement: cout << "Hello, " << "I am " << "a C++ statement"; This last statement would print the message: Hello, I am a C++ statement Additionally, to add a new-line, you may also use the endl manipulator. For example: 1 2 cout << "First sentence." << endl; cout << "Second sentence." << endl; 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. STANDARD INPUT (cin) The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example: 1 2 int age; cin >> age; 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. Would print out: First sentence. Second sentence. The first statement declares a variable of type int called age, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable.
  • 25. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 25 Please enter an integer value: 12 and its double is : 144 is equivalent to: 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. Sample 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: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // i/o example #include <iostream.h> #include <conio.h> int main () { int i; cout << "Please enter an integer value: "; cin >> i; cout << "The value you entered is " << i; cout << " and its double is : " << i*2 << ".n"; getch(); } cin >> a >> b; 1 2 cin >> a; cin >> b;
  • 26. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 26 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). This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was stored until this moment in a is not considered at all in this operation, and in fact that value is lost. OPERATORS Once we know of the existence of variables and constants, we can begin to operate with them. For that purpose, C++ integrates operators. Unlike other languages whose operators are mainly keywords, operators in C++ are mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++ code shorter and more international, since it relies less on English words, but requires a little of learning effort in the beginning. 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. Assignments Operators (=) An operator is a symbol that cause the compiler to take an action. Operators act on operands, and in C++ all operands are expressions. In C++ there are several different types of operators. These are: o mathematical operators (+ , - , / , * ) o relational operators ( true or false statement) o logical operators ( and, or, not ) a = 5; 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: a = b; 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.
  • 27. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 27 Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. Arithmetic Operators (+, -, *, /, % ) The five arithmetical operations supported by the C++ language are: Integer division and modulus Integer division is somewhat different from everyday division. When you divide 21 by 4, the result is a real number (a number with fraction part), integers don’t have fractions, and so the “remainder” is looped off. The answer is therefore 5. To get the remainder, you take 21 modulus (21 % 4) and the result is 1. The modulus operator tells you the remainder after an integer division. Write the output of the given source code below. + addition - subtraction * multiplication / division %modulo // TRY THIS: #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(); } Write your output here:
  • 28. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 28 are all equivalent in its functionality: the three of them increase by one the value of c. Prefix and Postfix Compound Assignments (+=,-=, *=, /=, %=, <<=, >>=, &=, ^=, |= ) When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators: 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); Increment(++) and Decrement(--) Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus: Both the increment operator (++) and the decrement operator (--) come in two varieties:  Prefix – written before the variable name (++myage), Increment the value and fetch it.  Postfix – written after variable name (myage++), Fetch the value and then increment the original A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++aboth have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression. Notice the difference: 1 2 3 c++; c+=1; c=c+1;
  • 29. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 29 Example 1 Example 2 B=3; A=++B; // A contains 4, B contains 4 B=3; A=B++; // A contains 3, B contains 4 In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased. What is the output of the given source code below. #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(); } Write your output here:
  • 30. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 30 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 We may doubt if it really means: 1 2 a = 5 + (7 % 2) // with a result of 6, or 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 THE NATURE OF TRUTH In C++, zero is considered false, and all other values are considered true, although true is usually represented by 1. Thus if an expression is false, it is equal to zero. And if an expression is equal to zero, it is false. If a statement is true, all you know is that is nonzero, and any zero statement is true. Relational and Equality Operators In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++: ==Equal to != Not equal to > Greater than < Less than >=Greater than or equal to <=Less than or equal to 1 2 3 4 5 (7 == 5) // evaluates to false. (5 > 4) // evaluates to true. (3 != 2) // evaluates to true. (6 >= 6) // evaluates to true. (5 < 5) // evaluates to false. Here there are some examples:
  • 31. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 31 Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6, 1 2 3 4 (a == 5) // evaluates to false since a is not equal to 5. (a*b >= c) // evaluates to true since (2*3 >= 6) is true. (b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false. ((b=2) == a) // evaluates to true. 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: 1 2 3 4 !(5 == 5)// false because the expression at its right is true !(6 <= // evaluates to true because (6 <= 4) would be false. !true // evaluates to false !false // evaluates to true. The logical operators && and || are used when evaluating two expressions to obtain a single relational result. && OPERATOR a b a && b true true true true false false false true false false false false || OPERATOR a b a || b true true true true false true false true true false false false The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves
  • 32. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 32 A. Suppose that a = 2, b = 3 and c = 4 evaluate the given expression below. Write the word TRUE if the expression evaluates true otherwise write FALSE 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) B. Analyze and complete the table by writing the missing relational operators below. Suppose that a = 3, b = 4, c = 5 and d = 6 EXPRESSION 1 OPERATOR EXPRESSION 2 EVALUATION (a==3) (a!=b) True (c!=d) (c!=5) False (a>1) (b==b) True (!(b=c) (!(d=6) False (c==c) (b>a) True (b>a) (d>12) False (d<10) (!(c=d) True (c>=5) (b>=d) False (a!=b) (!(c>d) True (b>=b) (b!=a) False
  • 33. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 33 LESSON 5 C++ Program Control Structures Objectives: At the end of this lesson, the student should be able to:  Understand what control structure is.  Differentiate types of Control Structures  Know how to use and construct Control Structures Control Strucuture A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances. With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }. {statement1; statement2; statement3;} 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. Types of control structures 1. Sequence Structure 2. Selection /Conditional Structure 3. Repetition/Iteration Structure SEQUENCE STRUCTURE The instructions are executed sequentially starting from the first instruction up to the last instruction in the program. Entry ExitS1 S2 S3 S4
  • 34. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 34 CONDITIONAL / SELECTION STRUCTURE It performs different computations or actions depending on whether a programmer-specified Boolean condition evaluates to true or false. a. If Statement The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is: Syntax: if (condition) statement Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the program continues right after this conditional structure. If we want more than a single statement to be executed in case that the condition is true we can specify a block using braces { }: # include <iostream.h> #include<conio.h> main () { int grade; clrscr(); cout<<” Enter a grade: “ cin>> grade; If ( grade >=75) cout << “ PASSED”; If ( grade <75) cout << “FAILED”; getch (); } Write the output 1 here Write the output 2 here 1 2 if (x == 100) cout << "x is 100"; 1 2 3 4 5 if (x == 100) { cout << "x is "; cout << x; } The following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:
  • 35. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 35 ` b. If Else Statement It executes two statements in a program. If the condition is satisfied the first statement will be executed otherwise, it will go to another statement. We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with if is: Syntax: if (condition) statement 1; else statement 2; For example: 1 2 3 4 if (x == 100) cout << "x is 100"; else cout << "x is not 100"; # include <iostream.h> #include<conio.h> main () { int num; clrscr(); cout<<” Enter a Number: “ cin>> grade; If ( num > 0) cout << “Positive Number”; else If ( grade < 0) cout << “Negative Number”; else cout<<”That is 0”; getch (); } Write the output 1 here (input positive # ) Write the output 2 here (input Negative # ) Write the output 3 here (input zero ) Prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is not 100.
  • 36. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 36 c. Else If Statement Usually it is used to execute if you have three or more statement to be executed in the program. The if + else structured can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e zero): 1 2 3 4 5 6 if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else 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 { }. #include<iostream.h> #include<conio.h> 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(); } Write all the possible output
  • 37. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 37 SAMPLE OUTPUT SAMPLE OUTPUT PROBLEM 1 : Create a program that will compute your age and will display if you are a minor or a legal age. Refer your source code on the given output. Write your program on the box below Enter Your Birth Year : 1990 Enter Present Year : 2012 Your age is : 22 years old 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 ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ _______________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ ________________________________________________ __________________________ ________________________________________________ Enter a number : 5 That is odd number
  • 38. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 38 d. Switch Case Statement Its objective is to check several possible constant values for an expression. Its form is the e. f. g. h. i. j. k. l. m. n. o. p. Both of the following code fr q. r. s. t. Both of the following code fragments have the same behavior The switch case statement is a bit peculiar within C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remaining statements – including those corresponding to other labels - will also be executed until the end of the switch selective block or a break statement is reached. Switch (expression) { Case constant 1: Group of statements 1; Break; Case constant 2: Group of statement 2; Break - - - Default: Default group of statements } It works in the following way: 1. Switch evaluates expression and checks if its equivalent to constant1, if it is, it executes group of statements1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure. 2. If expression is not equal to constant 1 it will be check against constant2 if its equal to this, it will execute group of statements2 until break keyword is found, then will jump to the end of the switch selective structure. 3. Finally, if the value of expression did not match any of the previously specified constants, the program will execute the statements included after the default. SWITCH CASE SAMPLE switch(x) case cout<<”x is 1”; break; case cout<<”x is 2”; break default: cout<<”value of x is unknown”; } If – else equivalent { If (x == 1) { Cout<<”x is 1”; } Else if (x == 2) { Cout<<”x is 2”; } Else { Cout<<”value of x is unknown”; }
  • 39. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 39 Create a source code of the following output. Write you program on the box below. SAMPLE OUTPUT SOURCE CODE: [A] – ADDITION [S] – SUBTRACTION [M] – MULTIPLICATION [D] – DIVISION ENTER OPERATION : M ENTER NUM 1 : 5 ENTER NUM 2 : 10 THE PRODUCT IS : 50 [A] – ADDITION [S] – SUBTRACTION [M] – MULTIPLICATION [D] – DIVISION ENTER OPERATION : W INVALID ENTRY [A] – ADDITION [S] – SUBTRACTION [M] – MULTIPLICATION [D] – DIVISION ENTER OPERATION : A ENTER NUM 1 : 12 ENTER NUM 2 : 13 THE SUM IS : 25 ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ ____________________________________________________________________________ _________________________ ____________________________________________________________________________ ________ ____________________________________________________________________________ ________ ____________________________________________________________________________
  • 40. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 40 LESSON 6 ITERATION / REPETITION STRUCTURE Objectives: At the end of this lesson, the student should be able to:  Learn The Different Types of Repetitions Structure  Differentiate the repetition from selection structure  Apply The syntax of different repetition structure in creating a complex program. 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 goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:). Generally speaking, this instruction has no concrete use in structured or object oriented programming aside from those that low-level programming fans may find for it. For example, here is our countdown loop using goto: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // goto loop example #include <iostream.h> #include <conio.h> int main () { int n=10; loop: cout << n << ",n "; n--; if (n>0) goto loop; cout << "FIRE!n"; getch(); } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! NOTE. Use of goto is almost a sign of bad design. The advice is avoid using it
  • 41. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 41 The exit function exit is a function defined in the cstdlib library. The purpose of exit is to terminate the current program with a specific exit code. Its prototype is: void exit (int exitcode); The exitcode is used by some operating systems and may be used by calling programs. By convention, an exit code of 0 means that the program finished normally and any other value means that some error or unexpected results happened. THE REPETITION CONTROL STRUCTURE also known as the looping or iteration control structure. Looping is the process of repeatedly executing one or more steps of an algorithm or program; it is essential in programming, as most programs perform repetitious tasks. Every loop consists of the following three parts: 1. The loop termination decision - determines when (under what condition) the loop will be terminated (stopped). It is essential that some provision in the program be made for the loop to stop; otherwise, the computer would continue to execute the loop indefinitely - a loop that doesn't stop is called an endless loop or infinite loop; when a program gets stuck in an endless loop, programmers say that the program is "looping". 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. 3. Transfer back to the beginning of the loop - returns control to the top of the loop so that a new repetition (iteration) can begin. Three types of repetition Structure 1. While Loop 2. Do Loop 3. For Loop
  • 42. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 42 1. THE WHILE LOOP Its Syntax is: while (expression) statement and its functionality is simply to repeat statement while the condition set in expression is true. For example we are going to make a program to countdown using a while-loop: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // custom countdown using while #include <iostream> include <conio> int main () { int n; cout << "Enter a number > "; cin >> n; while (n>0) { cout << n << "/n"; --n; } cout << "FIRE!n"; getch(); } Enter a number > 8 8 7 6 5 4 3 2 1 FIRE! 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.
  • 43. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 43 The whole process of the previous program can be interpreted according to the following script (beginning in main): User assigns a value to n 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. When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one 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. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // custom countdown using while #include <iostream> include <conio> int main () { int n; cout << "Enter a number :> "; cin >> n; while (n>0) { cout <<"ICCT COLLEGES"; --n; } cout << "FIRE!n"; gecth(); } What is the output?
  • 44. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 44 The break statement Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before its natural end (maybe because of an engine check failure?): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // break loop example #include <iostream> #include <conio> int main () { int n; for (n=10; n>0; n--) { cout << n << "n"; if (n==3) { cout << "countdown aborted!"; break; } } Getch; } What is the output? The continue statement The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown: 1 2 3 4 5 6 7 8 9 10 11 12 13 // continue loop example #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!n"; return 0; } What is the output?
  • 45. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 45 2. THE DO-WHILE LOOP Its Syntax is: do statement while (condition); Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0. 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. 3. THE FOR LOOP Its syntax is: for (initialization; condition; increase) statement; 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. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // number echoer #include <iostream> include <conio> int main () { unsigned long n; do { cout << "Enter number: "; cin >> n; cout << "You entered: "<n<<n"; } while (n != 0); Getch; } What is the output?
  • 46. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 46 It works in the following way: 1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }. 4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2. Here is an example of countdown using a for loop: 1 2 3 4 5 6 7 8 9 10 11 // countdown using a for loop #include <iostream> using namespace std; int main () { for (int n=10; n>0; n--) { cout << n << ", "; } cout << "FIRE!n"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE! 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: 1 2 3 4 for ( n=0, i=100 ; n!=i ; n++, i-- ) { // whatever here... } This loop will execute for 50 times if neither n or i are modified within the loop:
  • 47. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 47 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 : ENTER YOUR NAME: CARLOS ENTER HOW MANY TIMES YOU WANT TO DISPLAY YOUR NAME: 5 DISPLAY CARLOS 0 and 5 ONLY DISPLAY CARLOS 1 and 4 ONLY DISPLAY CARLOS 2 and 3 ONLY DISPLAY CARLOS 3 and 2 ONLY DISPLAY CARLOS 4 and 1 ONLY DISPLAY CARLOS 5 and 0 ONLY END OF YOUR NAME!!! ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________________________________________ ____________________________________
  • 48. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 48 LESSON 7 THE ARRAY Objectives: At the end of this lesson, the student should be able to:  Learn what array is and what it does.  Learn how to use array in a program What is Array? An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. 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 each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length. Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is: type name [elements]; 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. Therefore, in order to declare an array called CARLOS as the one shown in the above diagram it is as simple as: int CARLOS [5]; For example, an array to contain 5 integer values of Type int called CARLOS could be represented like this:
  • 49. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 49 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 When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros. In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example: int CARLOS [5] = { 16, 2, 77, 40, 12071 }; This declaration would have created an array like this: 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 { }: int CARLOS [] = { 16, 2, 77, 40, 12071 }; After this declaration, array CARLOS would be 5 ints long, since we have provided 5 initialization values.
  • 50. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 50 Accessing the values of an array In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as: name[index] 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]; Therefore, the expression CARLOS[2] is for all purposes like a variable of type int. Notice that the third element of CARLOS is specified CARLOS[2], since the first one is CARLOS[0], the second one isCARLOS[1], and therefore, the third one is CARLOS[2]. By this same reason, its last element is CARLOS[4]. Therefore, if we write CARLOS[5], we would be accessing the sixth element of CARLOS and therefore exceeding the size of the array. In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems, since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The reason why this is allowed will be seen further ahead when we begin to use pointers.
  • 51. INTRODUCTION TO COMPUTERSCIENCE C++ Programming ICCT COLLEGES 51 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. 1 2 int CARLOS[5]; // declaration of a new array CARLOS[2] = 75; // access to an element of the array. If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it never precedes an access. Some other valid operations with arrays: 1 2 3 4 CARLOS[0] = a; CARLOS[a] = 75; b = CARLOS [a+2]; CARLOS[CARLOS[a]] = CARLOS[2] + 5; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // arrays example #include <iostream> #include<conio> int CARLOS [] = {16, 2, 77, 40, 12071}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += CARLOS[n]; } cout << result; gecth(); } WHAT IS THE OUTPUT?