Sei sulla pagina 1di 51

INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

ICCT COLLEGES 1
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

ICCT COLLEGES 2
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

ICCT COLLEGES 3
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

2. Runtime Errors
 Compilers aren't perfect and so can't catch all errors at compile
time.
 This is especially true for logic errors such as infinite loops. This
type of error is called runtime error

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.

DEFINITION OF TERMS

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.

ICCT COLLEGES 4
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

ICCT COLLEGES 5
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.
ICCT COLLEGES 6
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

 In 1990, The Annotated C++ Reference Manual was released. The same
year, Borland's Turbo C++ compiler would be released as a commercial
product. Turbo C++ added a plethora of additional libraries which would
have a considerable impact on C++'s development. Although Turbo
C++'s last stable release was in 2006, the compiler is still widely used.

 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.

ICCT COLLEGES 7
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 lies beneath the edit window and is used to display various
Compiler compiler or linker messages
Window

8 Status Area Found at the bottom part of the screen that contains lists of
shortcut keys. It also serves as a source of user’s help.
9 Window number It identifies the number of your window.

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

ICCT COLLEGES 8
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

SHORT CUT KEY COMMANDS

How to : Method
Activate the menu bar Press F10
Method 1: Press F10
 Use the arrow keys to select the menu
Select a menu from the
 Press the ENTER key and the submenu appears
menu bar
Method 2: Press ALT + the highlighted key of choice
in the menu ( ex. ALT + F for File menu )
Select a command from the Press ALT + the highlighted key of choice in the menu
submenu  Use the arrow keys to select a command,
 press ENTER key
Cancel a command Press ESC key
note: Pressing the ESC keys cancels any selection in a
submenu and returns to the previous menu
Create a program Press ALT + F
(to activate file menu, sub-menu appears)
 Choose the NEW option
 Press the ENTER key
 Type your program
Save a new program Press ALT + F
 Use the ARROW keys to go to the SAVE AS command
 Press the ENTER key (A SAVE AS dialog box appears)
 Press TAB key until you reach the input box
 From the input box, type your program name
 Press TAB key again until you reach the OK button,
press the ENTER key
Save an edited program Method 1: Press ALT + F
Use the ARROW keys to go to the SAVE command, press
the ENTER key
Method 2: Press F2
Open a program Method 1: Press ALT + F
 Use the ARROW keys to go to the OPEN command
 Press ENTER key (an OPEN dialog box appears
 Press TAB until you reach the input box
 From the input box, type your program name
 Press TAB until you reach the OK button, press the
ENTER key
Method 2: Press F3
(an OPEN dialog box appears)
 Use ARROW keys to go to the program name you
want to open, press ENTER key
Compile a program Method 1: Press ALT + C (to activate the COMPILE
menu) Use the ARROW keys to go to the COMPILE
command, press ENTER key
Method 2: Press ALT + F9
Run a program Method 1: Press ALT + R
(to activate the RUN command)
Use the ARROW keys to go to the RUN command, press
the ENTER key
Method 2: Press CTRL + F9
Quit Turbo C++ Method 1: Press ALT + F
(to activate the FILE menu)
Use the ARROW keys to go to the QUIT command, press
ENTER key
Method 2: Press ALT + X (a confirmation dialog box
appears)

ICCT COLLEGES 9
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

LESSON 3

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 .

ICCT COLLEGES 10
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

Type Description
bool Stores either value true or false.
char Typically a single octet (one byte). This is an integer
type. It represents the character on your keyboard –
letters of the alphabet, numbers or special character
int The most natural size of integer for the machine. It is a
whole number or a series of decimal digits which can be
preceded by a positive or negative sign.
float A single-precision floating point value. A number with
decimal part
double A double-precision floating point value. a special float
which can store more significant digits and take up
more memory space.
long a large whole number
Table 1. Commonly used data types.

ICCT COLLEGES 11
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

Typical range

The following table shows the variable type, how much memory it
takes to store the value memory and what is maximum and minimum vaue
which can be stored in such type of variables.

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
int 4bytes -2147483648 to 2147483647
long 4bytes -2,147,483,647 to 2,147,483,647
int
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

#include<iostream.h>
CODE MEANING #include<conio.h>
main()
\a alert (bell) {
\n newline cout<<”H\nE\nL\nL\nO”;
\b backspace cout<<”\t\”WORLD\””;
getch();
\f formfeed
}
\r carriage return
\t tab Output
\v vertical tab
H
\\ backslash
E
\’ single quote mark L
\” double quote mark L
\0 null O
“WORLD”

ICCT COLLEGES 12
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

DATA VALUES

VARIABLES - identifiers that can store value that can be changed and can
store literals or some type of structured data.

Variable declaration

 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:

These are two valid declarations of variables. The first


one declares a variable of type int with the
1 int a; identifier a. The second one declares a variable of
2 float mynumber; 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.

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;

This declares three variables (a, b and c), all 1 int a;


of them of type int, and has exactly the 2 int b;
same meaning as: 3 int c;

C++ assignment statement

 may be used to assign values to variables of any types.

Format: <variable> = Constant


Variable
Ex.: num1 = num; Arithmetic expression
num2 = 23;
num3 = tot1 + tot2;

ICCT COLLEGES 13
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

ICCT COLLEGES 14
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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:

Here, pathwidth and tabulator are two typed


1 const int pathwidth = 100; constants. They are treated just like
2 const char tabulator = '\t'; regular variables except that their values
cannot be modified after their definition.

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

int a, b; char a;
#define a 1; #define a ”HELLO WORLD”;
#define b 2; cout<<”The Sum is : “<<a;
cout<<”The Sum is : “<<a+b;

Output

The Sum is : 3 HELLO WORLD

ICCT COLLEGES 15
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

TYPES OF DATA

LITERALS are the most obvious kind of constants. They are used to
express particular values within the source code of a program. We have
already used these previously to give concrete values to variables or to
express messages we wanted our programs to print out, for example, when
we wrote:

a = 5; The 5 in this piece of code was a literal constant.

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

1 1776 They are numerical constants that identify integer decimal


2 707 values. Notice that to express a numerical constant we do
3 -273 not have to write quotes (") nor any special character.

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:
All of these represent the same number: 75
1 75 // decimal
(seventy-five) expressed as a base-10 numeral,
2 0113 // octal
octal numeral and hexadecimal numeral,
3 0x4b // hexadecimal
respectively.

Literal constants, like variables, are considered to have a specific data type.
By default, integer literals are of typeint. However, we can force them to
either be unsigned by appending the u character to it, or long by
appending /:

75 // int In both cases, the suffix can be specified using


75u // unsigned int either upper or lowercase letters.
75l // long

ICCT COLLEGES 16
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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:

These are four valid numbers with decimals


expressed in C++. The first number is PI, the
second one is the number of Avogadro, the
1 3.14159 // 3.14159
third is the electric charge of an electron (an
2 6.02e23 // 6.02 x 10^23
extremely small number) -all of them
3 1.6e-19 // 1.6 x 10^-19
4 3.0 // 3.0 approximated- and the last one is the number
three expressed as a floating-point numeric
literal.

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:

Any of the letters that can be part of a floating


1 3.14159L // long double point numerical constant (e, f, l) can be
2 6.02e23f // float
written using either lower or uppercase letters
without any difference in their meanings.

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).

The first two expressions represent single character


'z' constants, and the following two represent string literals
'p' composed of several characters. Notice that to represent a
"Hello world" single character we enclose it between single quotes (') and
"How do you do?" to express a string (which generally consists of more than one
character) we enclose it between double quotes (").

Note:

Character literals are enclosed in single quotes. If the literal begins with L
(uppercase only), it is a wide character literal (e.g., L'x') and should be stored
in wchar_t type of variable . Otherwise, it is a narrow character literal (e.g., 'x')
and can be stored in a simple variable of char type.

String literals are enclosed in double quotes. A string contains characters that are similar
to character literals: plain characters, escape sequences, and universal characters. You can
break a long lines into multiple lines using string literals and separating them using
whitespaces.

ICCT COLLEGES 17
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

STRUCTURE OF A PROGRAM
Probably the best way to start learning a programming language is by
writing a program. Therefore, here is our first program:

1 // my first program in C++ Hello World!


2
3 #include <iostream.h>
4 #include <conio.h>
5
6 int main ()
7 {
8 cout << "Hello World!";
9 getch();
10 }

We are going to look line by line at the code we have just written:

// my first program in C++

This is a comment line. All lines beginning with two slash signs (//)
are considered comments and do not have any effect on the behavior of the
program. The programmer can use them to include short explanations or
observations within the source code itself. In this case, the line is a brief
description of what our program is.

#include<iostream.h>

Lines beginning with a hash sign (#) are directives for the
preprocessor. They are not regular code lines with expressions but
indications for the compiler's preprocessor. In this case the
directive #include <iostream>tells the preprocessor to include the
iostream standard file. This specific file (iostream) includes the declarations
of the basic standard input-output library in C++, and it is included because
its functionality is going to be used later in the program.

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.

ICCT COLLEGES 18
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

int main ()

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.

cout << " Hello World!";

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.

ICCT COLLEGES 19
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 int main ()
2{
3 cout << " Hello World!";
4 getch();
5}

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 : Jake Dela Cruz

Address : Rosario, Pasig City

Gender : Male

Birthday : January 17, 1990

Course : BSIT

Year : 4th year

Height : 5’11

Weight : 60 kgs

ICCT COLLEGES 20
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 // line comment
2 /* 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:

1 /* my second program in C++ Hello World! I'm a C++


2 with more comments */ program
3
4 #include <iostream>
5 #include<conio.h>
6 int main ()
7 {
8 cout << "Hello World! ";
9 // prints Hello World!
10 cout << "I'm a C++ program";
11 // prints I'm a C++ program
12 getch();
}

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.

ICCT COLLEGES 21
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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:

{
temp = a; This block of code acts as one
a = b; statement and swaps the values in the
b = temp; variables a and b.
}

EXPRESSIONS

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

ICCT COLLEGES 22
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 cout << "Output sentence"; // prints Output sentence on screen


2 cout << 120; // prints number 120 on screen
3 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 cout << "Hello"; // prints Hello


2 cout << Hello; // prints the content of Hello variable

ICCT COLLEGES 23
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

The insertion operator (<<) may be used more than once in a single
statement:

cout << "Hello, " << "I am " << "a C++ statement";

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:
Would print out:
1 cout << "First sentence." << endl;
2 cout << "Second sentence." << endl;
First sentence.
Second sentence.

The endl manipulator produces a newline character, exactly as the


insertion of '\n' does, but it also has an additional behavior when it is used
with buffered streams: the buffer is flushed. Anyway, cout will be an
unbuffered stream in most cases, so you can generally use both
the \n escape character and the endl manipulator in order to specify a new
line without any difference in its behavior.

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:

The first statement declares a variable of type int called age,


1 int age; and the second one waits for an input from cin (the keyboard)
2 cin >> age; in order to store it in this integer variable.

cin can only process the input from the keyboard once
the RETURN key has been pressed. Therefore, even if you request a single
character, the extraction from cin will not process the input until the user
presses RETURN after the character has been introduced.

You must always consider the type of the variable that you are using
as a container with cin extractions. If you request an integer you will get
an integer, if you request a character you will get a character and if you
request a string of characters you will get a string of characters.

ICCT COLLEGES 24
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

Sample

1 // i/o example
2
3 #include <iostream.h>
4 #include <conio.h>
5
6 int main ()
7 {
8 int i;
9 cout << "Please enter an integer value: ";
10 cin >> i;
11 cout << "The value you entered is " << i;
12 cout << " and its double is : " << i*2 << ".\n";
13 getch();
14 }

Output:

Please enter an integer value: 12


and its double is : 144

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:

is equivalent to: 1 cin >> a;


cin >> a >> b;
2 cin >> b;

In both cases the user must give two data, one for variable a and
another one for variable b that may be separated by any valid blank
separator: a space, a tab character or a newline.

ICCT COLLEGES 25
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

OPERATORS

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 )

This statement assigns the integer value 5 to the variable a. The part
a = 5; at the left of the assignment operator (=) is known as the lvalue (left
value) and the right one as the rvalue (right value).

The lvalue has to be a variable whereas the rvalue can be either a constant,
a variable, the result of an operation or any combination of these.

The most important rule when assigning is the right-to-left rule: The
assignment operation always takes place from right to left, and never the
other way:

This statement assigns to variable a (the lvalue) the value contained in


a = b;
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.

Consider also that we are only assigning the value of b to a at the moment
of the assignment operation. Therefore a later change of b will not affect
the new value of a.

ICCT COLLEGES 26
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

Arithmetic Operators (+, -, *, /, % )

The five arithmetical operations supported by the C++ language are:

+ addition Operations of addition, subtraction, multiplication and


division literally correspond with their respective
- subtraction mathematical operators. The only one that you might
not be so used to see is modulo; whose operator is the
* multiplication
percentage sign (%). Modulo is the operation that gives
/ division the remainder of a division of two values.

% modulo

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.

// TRY THIS: Write your output here:

#include<iostream.h>
#include<conio.h>
main()
{
int a, b;
a = 53;
b = 5;
clrscr();
cout<<”QUOTIENT IS : <<a/b;
cout<<”REMAINDER IS : ”<<a%b
getch();
}

ICCT COLLEGES 27
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

Compound Assignments
(+=,-=, *=, /=, %=, <<=, >>=, &=, ^=, |= )

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:

1 c++; are all equivalent in its functionality: the three of them increase by
2 c+=1; one the value of c.
3 c=c+1;

Prefix and Postfix

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:

ICCT COLLEGES 28
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B contains 4

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:

ICCT COLLEGES 29
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 a = 5 + (7 % 2) // with a result of 6, or
2 a = (5 + 7) % 2 // with a result of 0

The correct answer is the first of the two expressions, with a result
of 6. There is an established order with the priority of each operator, and
not only the arithmetic ones (those whose preference come from
mathematics) but for all the operators which can appear in C++. From
greatest to lowest priority

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++:

Here there are some examples:


== Equal to
!= Not equal to
1 (7 == 5) // evaluates to false.
> Greater than 2 (5 > 4) // evaluates to true.
< Less than 3 (3 != 2) // evaluates to true.
>= Greater than or equal to 4 (6 >= 6) // evaluates to true.
<= Less than or equal to 5 (5 < 5) // evaluates to false.

ICCT COLLEGES 30
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 (a == 5) // evaluates to false since a is not equal to 5.


2 (a*b >= c) // evaluates to true since (2*3 >= 6) is true.
3 (b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.
4 ((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 !(5 == 5)// false because the expression at its right is true


2 !(6 <= // evaluates to true because (6 <= 4) would be false.
3 !true // evaluates to false
4 !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 The operator && corresponds with Boolean


true true true logical operation AND. This operation results
true false false true if both its two operands are true, and false
false true false otherwise.
false false false

|| OPERATOR
The operator || corresponds with Boolean logical
a b a || b
operation OR. This operation results true if either
true true true
one of its two operands is true, thus being false
true false true
only when both operands are false themselves
false true true
false false false

ICCT COLLEGES 31
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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

ICCT COLLEGES 32
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 S1 S2 S3 S4 Exit

ICCT COLLEGES 33
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

1 if (x == 100) The following code fragment prints x is


2 cout << "x is 100"; 100 only if the value stored in the x variable is
indeed 100:

1 if (x == 100) If we want more than a single statement to be


2{ executed in case that the condition is true we
3 cout << "x is "; can specify a block using braces { }:
4 cout << x;
5}

# include <iostream.h> Write the output 1 here


#include<conio.h>
main ()
{

int grade;
clrscr();
cout<<” Enter a grade: “
cin>> grade;
Write the output 2 here
If ( grade >=75)
cout << “ PASSED”;
If ( grade <75)
cout << “FAILED”;

getch ();
}

ICCT COLLEGES 34
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

`
b. If Else Statement

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 if (x == 100) Prints on the screen x is 100 if


2 cout << "x is 100"; indeed x has a value of 100, but if it
3 else has not -and only if not- it prints out x
4 cout << "x is not 100"; is not 100.

# include <iostream.h> Write the output 1 here (input positive # )


#include<conio.h>
main ()
{

int num;
clrscr();

cout<<” Enter a Number: “ Write the output 2 here (input Negative # )


cin>> grade;

If ( num > 0)
cout << “Positive Number”;
else If ( grade < 0)
cout << “Negative Number”;
Write the output 3 here (input zero )
else
cout<<”That is 0”;

getch ();
}

ICCT COLLEGES 35
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

c. Else If Statement

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 if (x > 0)
2 cout << "x is positive";
3 else if (x < 0)
4 cout << "x is negative";
5 else
6 cout << "x is 0";

note
Remember that in case that we want more than a single statement to
be executed, we must group them in a block by enclosing them in
braces { }.

#include<iostream.h> Write all the possible output


#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();
}

ICCT COLLEGES 36
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

PROBLEM 1 : SAMPLE OUTPUT

Create a program that will compute Enter Your Birth Year : 1990
your age and will display if you are a Enter Present Year : 2012
minor or a legal age. Refer your source
code on the given output. Write your Your age is : 22 years old
program on the box below Your are in Legal age

____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________
________________________________________________
PROBLEM 2 :
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
Create a program that will ________________________________________________
input a number and will
____________________________________________________________________________________
________________________________________________
display the number is odd
____________________________________________________________________________________
________________________________________________
or an even number
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
_______________________________________________
SAMPLE OUTPUT
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
________________________________________________
Enter a number : 5
____________________________________________________________________________________
________________________________________________
That is odd number
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
________________________________________________
____________________________________________________________________________________
________________________________________________
________________________________________________
________________________________________________
ICCT COLLEGES 37
__________________________
________________________________________________
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

d. Switch Case Statement

Its objective is to check several possible constant values for an


expression. Its form is the
It works in the following way:
e.
Switch (expression) 1. Switch evaluates expression and
f.
{
g.Case constant 1: checks if its equivalent to constant1,
if it is, it executes group of
h.Group of statements
statements1 until it finds the break
i. 1; statement. When it finds this break
Break;
j. statement the program jumps to the
k.Case constant 2: end of the switch selective structure.
l. Group of statement 2; 2. If expression is not equal to constant
Break 1 it will be check against constant2 if
m.
- its equal to this, it will execute group
n. of statements2 until break keyword is
-
o.- found, then will jump to the end of
p.Default:
Both of the following code fr the switch selective structure.
3. Finally, if the value of expression did
q.
not match any of the previously
r.Default group of specified constants, the program will
statements
s.} execute the statements included
t. after the default.

Both of the following code fragments have the same behavior

SWITCH CASE SAMPLE If – else equivalent

switch(x) {
case If (x == 1)
cout<<”x is 1”; {
break; Cout<<”x is 1”;
}
case Else if (x == 2)
cout<<”x is 2”; {
break Cout<<”x is 2”;
}
default: Else
cout<<”value of x {
is unknown”; Cout<<”value of x
} is unknown”;
}

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.

ICCT COLLEGES 38
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

Create a source code of the following output. Write you program on the box
below.

SAMPLE OUTPUT
[A] – ADDITION [A] – ADDITION [A] – ADDITION
[S] – SUBTRACTION [S] – SUBTRACTION [S] – SUBTRACTION
[M] – MULTIPLICATION [M] – MULTIPLICATION [M] – MULTIPLICATION
[D] – DIVISION [D] – DIVISION [D] – DIVISION
ENTER OPERATION : A ENTER OPERATION : M ENTER OPERATION : W
ENTER NUM 1 : 12 ENTER NUM 1 : 5 INVALID ENTRY
ENTER NUM 2 : 13 ENTER NUM 2 : 10
THE SUM IS : 25 THE PRODUCT IS : 50

SOURCE CODE:

____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
_________________________
____________________________________________________________________________
________
ICCT COLLEGES
____________________________________________________________________________ 39

________
____________________________________________________________________________
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

LESSON 6

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 // goto loop example 10,


2 9,
3 #include <iostream.h> 8,
4 #include <conio.h> 7,
5 6,
6 int main () 5,
7 { 4,
8 int n=10; 3,
9 loop: 2,
10 cout << n << ",\n "; 1,
11 n--; FIRE!
12 if (n>0) goto loop;
13 cout << "FIRE!\n";
14 getch();
15 }

NOTE. Use of goto is almost a sign of bad design. The advice is avoid using it

ICCT COLLEGES 40
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

The 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

ICCT COLLEGES 41
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 // custom countdown using while Enter a number > 8


2 8
3 #include <iostream> 7
4 include <conio> 6
5 int main () 5
6 { 4
7 int n; 3
8 cout << "Enter a number > "; 2
9 cin >> n; 1
10 FIRE!
11 while (n>0) {
12 cout << n << "/n";
13 --n;
14 }
15
16 cout << "FIRE!\n";
17 getch();
18 }
19

When the program starts the user is prompted to insert a starting number
for the countdown. Then the while loop begins, if the value entered by the
user fulfills the condition n>0 (that n is greater than zero) the block that
follows the condition will be executed and repeated while the condition
(n>0) remains being true.

Condition is any C++ Boolean expression and Statement is any valid C++
statement or a block of statements. When condition evaluates to TRUE (1)
statement is executed. And then the condition is tested again, this continues until
condition tests FALSE (0) at which time the while loop terminates and execution
continues on the first line below statement.

ICCT COLLEGES 42
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 // custom countdown using while What is the output?


2
3 #include <iostream>
4 include <conio>
5 int main ()
6 {
7
8 int n;
9 cout << "Enter a number :> ";
10 cin >> n;
11
12 while (n>0) {
13 cout <<"ICCT COLLEGES";
14 --n;
15 }
16
17 cout << "FIRE!\n";
18 gecth();
19 }

ICCT COLLEGES 43
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 // break loop example What is the output?


2
3 #include <iostream>
4 #include <conio>
5
6 int main ()
7 {
8 int n;
9 for (n=10; n>0; n--)
10 {
11 cout << n << "\n";
12 if (n==3)
13 {
14 cout << "countdown aborted!";
15 break;
16 }
17 }
18 Getch;
19 }

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 // continue loop example What is the output?


2 #include <iostream>
3 using namespace std;
4
5 int main ()
6 {
7 for (int n=10; n>0; n--) {
8 if (n==5) continue;
9 cout << n << ", ";
10 }
11 cout << "FIRE!\n";
12 return 0;
13 }

ICCT COLLEGES 44
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

1 // number echoer What is the output?


2
3 #include <iostream>
4 include <conio>
5
6 int main ()
7 {
8 unsigned long n;
9 do {
10 cout << "Enter number: ";
11 cin >> n;
12 cout << "You entered: "<n<<\n";
13 } while (n != 0);
14 Getch;
15 }

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.

ICCT COLLEGES 45
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 // countdown using a for loop 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,


2 #include <iostream> FIRE!
3 using namespace std;
4 int main ()
5 {
6 for (int n=10; n>0; n--) {
7 cout << n << ", ";
8 }
9 cout << "FIRE!\n";
10 return 0;
11 }

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 for ( n=0, i=100 ; n!=i ; n++, i-- )


2{
3 // whatever here...
4}

This loop will execute for 50 times if neither n or i are modified within the
loop:

ICCT COLLEGES 46
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

n starts with a value of 0, and i with 100, the condition is n!=i (that n is
not equal to i). Because n is increased by one and i decreased by one, the
loop's condition will become false after the 50th loop, when
both n and i will be equal to 50.

Create the source code of the sample output below, the program should
accept a name and enter how many times you want to display your name.
Use any type of looping in creating your program.

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!!!

Source code :
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
____________________________________

ICCT COLLEGES 47
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

For example, an array to contain 5 integer values of Type int called


CARLOS could be represented like this:

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];

ICCT COLLEGES 48
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

NOTE: The elements field within brackets [] which represents the number of
elements the array is going to hold, must be a constant value, since arrays are
blocks of non-dynamic memory whose size must be determined before
execution. In order to create arrays with a variable length dynamic memory is
needed, which is explained later in these tutorials.

Initializing arrays

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.

ICCT COLLEGES 49
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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.

ICCT COLLEGES 50
INTRODUCTION TO COMPUTER SCIENCE C++ Programming

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 int CARLOS[5]; // declaration of a new array


2 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 CARLOS[0] = a;
2 CARLOS[a] = 75;
3 b = CARLOS [a+2];
4 CARLOS[CARLOS[a]] = CARLOS[2] + 5;

1 // arrays example WHAT IS THE OUTPUT?


2 #include <iostream>
3 #include<conio>
4
5 int CARLOS [] = {16, 2, 77, 40,
6 12071};
7 int n, result=0;
8
9 int main ()
10 {
11 for ( n=0 ; n<5 ; n++ )
12 {
13 result += CARLOS[n];
14 }
15 cout << result;
16 gecth();
}

ICCT COLLEGES 51

Potrebbero piacerti anche