You are on page 1of 62

Chapter 2

Fundamental of C++ Programming


Objectives

After learning this chapter, you will be able to…


Given a task, create pseudocode
Given pseudocode, create a flowchart
Define/describe these terms: program, compile vs.
interpret, loop, variable, function, syntax, code, debug, IF
THEN ELSE
What is programming?
A program is a set of instructions that guide the computer in carrying out a
specific task.
To write a program, we need to have programming languages such as c ++
and java
Computer can not understand these languages. In order for computer to carry
out the instructions, the program must be translated to a language that the
machine can understand, called machine language and then executed.
Types of Translations:
Assembler converts program developed with assembler Language
to machine language
Compiler converts program developed with High Level Language
to machine language
Interpreter converts program developed with High Level
Language to machine language.
What is programming?

Compiler converts all contents to machine code at a time where


as interpreter converts the program to machine code line by
line.
Some programming languages (like Java or C++) require the code to
be compiled (translated to binary) before it can be started.
Others (like JavaScript) are interpreted, meaning that each command
is translated separately when the program is started.
What is a programming language?

Set of commands that a computer has been “taught” to understand


Languages that look like “machine code” (e.g., 82A8: jsr r5,@#82AE
82AC: sob r0,8296) are used for…
Writing games
Writing application programs (like Excel)
Other languages look like English (“high level,” e.g., PRINT “HELLO”)
Logo
JavaScript
And many more
Programming language Overview
What does programming look like?

Here are some examples of an instruction to print


the word ‘Hello’
Logo PR [Hello]
JavaScript alert(“Hello”);
FORTRANPRINT “Hello”
BASIC PRINT “Hello”
COBOL DISPLAY ‘Hello’.
C++ COUT<<“Hello”;
Pascal WRITELN(‘Hello’);
Assembly XPRNT MESSAGE1
Language MESSAGE1 DC ‘Hello’
How do you write a program?
Decide what steps are needed to complete the task
Write the steps in pseudocode (written in English) or as a
flowchart (graphic symbols)
Translate into the programming language
Try out the program and “debug” it (fix if necessary)
Algorithms and Pseudo code

An algorithm is a sequence of a finite number of steps arranged in a specific


logical order which, when executed, produces the solution for a problem.
An algorithm must satisfy these requirements:
It must have an input
It must have an output
It should not be ambiguous (there should not be different interpretations to it)
It must be general (it can be used for different inputs)
It must be correct and it must solve the problem for which it is designed
It must execute and terminate in a finite amount of time
It must be efficient enough so that it can solve the intended problem using the
resource currently available on the computer
An algorithm can be represented using pseudocodes or flowcharts
What is pseudocode?
Pseudo code is Structured English used to represent an algorithm.
Pseudo code is English-like language used to express algorithms
(less restrictive/formal than a programming language) .
It is easy for both users and programmers to read and write
algorithms regardless of the programming experience.
There is no standard pseudo code but we should follow some
conventional rules below:
Statements are written in simple English.
Each statement is written on a separate line.

Example
Task: add two numbers
Pseudocode:
Start
Get two numbers
Add them
Print the answer
End
Flowchart
A flowchart is a graphical diagram that depicts the “flow” of a program using a
series of standard geometric symbols and lines, which are connected according
to the logic of the algorithm. There are a lot of symbols used in flowcharting
but the common five are:
Programming control structures
Programming control structure controls how the each
statement (step) of the algorithm flows (executes). Control
structures in most programming languages typically include
the following.
1. Sequence
The sequence control structure is the straightforward
execution of one processing step after another.

Sequence’s pseudo code:


Program Start
Process A
Process B
Process C
Program Stop
Programming control structures
2. Selection
The selection control structure is the presentation of a condition and two
actions between two actions. The choice depending on whether the condition
is true or false.
• IF’ s pseudo code: IF-ELSE’ s pseudo code:
• Program Start Program Start
• IF (Condition) Then IF (Condition) Then
• Process A Process A
• End IF ELSE
• Program Stop Process B
End IF
• Program Stop
Programming control structures
Programming control structures
3. Iteration (Looping)
The iteration control structure can be defined as the representation of a set of
instructions to be performed repeatedly, as long as the condition is satisfied
(TRUE or FALSE). There are many types of iteration control structure: for loop,
while loop, DO…..WHILE loop and REPEAT_UNTIL.
 DOWHILE’ s pseudo code:
Program Start
DOWHILE (Condition)
Process A
Process B
Process C
Process D
Process E
Process F
.
.
Process n
ENDWHILE
Program Stop
Programming control structures
REPEAT_UNTIL structure is similar to DOWHILE structure, in that a
group of statements are repeated in accordance with a specified
condition. But REPEAT_UNTIL tests the condition at the end of the
loop. This means that the statements within the loop will be execute once
before the condition is tested. The loop will be terminated if the result of
condition is True.
REPEAT_UNTIL’ s pseudo code:
Program Start
REPEAT
Process A
Process B
Process C .
.
.
Process n
UNTIL (Condition)
Program Stop
Programming control structures
Algorithm development examples
 In developing an algorithm, the problem should be defined and divided
into three separate components:
Input: a list of the source data provided to the problem.
Output: a list of the outputs required.
Processing: a list of actions needed to produce the required output.
Example01: Add three numbers
A program is required to read three numbers from a user, add them
together, and print their total on the screen.
Identify I/O
Input: number1, number2, number3
Output: Total
Process: read three numbers, add numbers together, print total to
the screen
Programming control structures
Write pseudo code and flow chart accordingly
 Pseudo code:
Program Start
Set number1, number2, number3, total = 0
Read number1, number2, number3
total = number1+number2+number3
Print total
Program Stop
Programming control structures
Compare two numbers
A program is required to read two numbers from a user, compare them
to find out whether number1 is greater than number2 or not. Print the
result of the comparison on the screen. i.e. number1 is greater than
number2
Identify I/O
Input:number1, number2
Output: larger number
Process: Read number1, number2
Compare number1 and number2
Print output message on the screen
Programming control structures
Write pseudo code and flow chart according to this defining diagram
Pseudo code:
Program Start
Set number1, number2 = 0
Read number1, number2
IF number1> number2 THEN
Print “Number1 is greater than number2”
ELSE
Print “Number2 is greater than number1”
ENDIF
Program Stop
Programming control structures
 Find average score
 A program will accept 10 students’ scores then calculate the average score. After finishing the
calculation, the program will print the average score on the screen.
 Input: Score (10 scores)
 Output: Average
 Process: Read score,
Calculate total,
Calculate count
Compute average
Print average on the screen
 Pseudo code:
Program Start
Set score, total, count, average = 0
DOWHILE count<10
Read score
Add score to total
Add 1 to count
ENDDO
average = total/count
Print average
Program Stop
General Rules for flowcharting
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other
entry points. The exit point for all flowchart symbols is on the bottom except
for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the
bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow
can be shown as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
6. All flow charts start with a Terminal or Predefined Process (for interrupt
programs or subroutines) symbol.
7. All flowcharts end with a terminal or a contentious loop.
Exercise
1. Design an algorithm and the corresponding flowchart for finding the
sum of the numbers 2, 4, 6, 8, …, n
2. Using flowcharts, write an algorithm to read 100 numbers and then
display the sum.
3. Write an algorithm to read two numbers then display the largest and
the smallest.
Questions??
Basics of C++

C++ is a
general –purpose
 case sensitive
 free form programming language that support procedural
 object oriented and
generic programming.
C++ is a vendor-neutral (C++ standard is the same in any compiler or
platform).
The first C++ Program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world!\n";
return 0;
}
All (non-white-space) characters are important
C++ is case sensitive: return ≠ Return
Any C++ program file should be saved with file name extension “.CPP ”
Parts of a Simple Program
#include – preprocessor directive
includes the contents of another file
using namespace – where to search unknown names
main() – function, starting point of the program
When the program starts, main() is called automatically.
Every C++ program has a main() function.
The end of a single statement ends with semicolon (;)
Comments:
// comment which ends at the end of the line
/* comment which may have multiple lines. It ends here: */
Elements of a Program

All programming languages have certain features in common. For


example:
Variables
Commands/Syntax (the way commands are structured)
Loops
Decisions
Functions
Each programming language has a different set of rules about these
features.
Variables
Variables are part of almost every program.
A variable is a “place to put data” and is usually represented by a letter or a
word.
Variables are used for holding data values so that they can be used in
various computations in a program.
Variable names cannot contain spaces.
Usually there are several ways to put information into a variable.
The most common way is to use the equal sign (=).
X = Y + 7 means take the value of Y, add 7, and put it into X.
COUNT=COUNT + 2 means take the current value of COUNT, add 2 to it, and
make it the new value of COUNT.
Variables

A variable will have three components:


Data Type: a type which is established when the variable is
defined. (e.g. integer, real, character etc). Data type describes the property
of the data and the size of the reserved memory
Here are some examples of data types:
Numeric (numbers of all kinds)
String (text, “strings of letters”)
Integer (whole numbers)
Long (large numbers)
Boolean (true/false)
Name: a name which will be used to refer to the value in the variable. A
unique identifier for the reserved memory location
Value: a value which can be changed by assigning a new value to the
variable.
Declaring Variables.
Variables can be created in a process known as declaration.
Syntax: Datatype Variable_Name;
The declaration will instruct the computer to reserve a memory location with the
name and size specified during the declaration.
Good variable names indicate the purpose of the variable or
they should be self descriptive.
E.g. int myAge; //variable used to store my age
Certain words are reserved by C++ for specific purposes and
can not be used as identifiers.
These are called reserved words or keywords and are summarized in the
following table.
Scope of a Variables

In C++, we can declare variables any where in the source code. But we should
declare a variable before using it no matter where it is written
Variables may be classified as global or local.
A global variable is one that can be shared by all parts of a program, including any
functions or sub-programs as long as it is declared first. A variable declared before
any function immediately after the include statements are global variables.
A local variable is one that is used only within a certain part of the program, for
example, only in one function or sub-program.
 In the following example, the integer data type num1 is accessible
everywhere whereas z and is only accessible in the add function and
num2 is accessible in main function. This means cout<<z; or any
statement involving z is only valid in add function
Characters.

Characters variables (type char) are typically one byte in size, enough to hold
256 different values. A char can be represented as a small number (0 - 255).
Char in C++ are represented as any value inside a single quote.
E.g.: ‘x’, ‘A’, ‘5’, ‘a’, etc.
When the compiler finds such values (characters), it translates back the value to
the ASCII values. E.g. ‘a’ has a value 97 in ASCII.
Special Printing characters.
In C++, there are some special characters used for formatting.
These are:
\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)
Operators.

An operator is a symbol that makes the machine to take an action.


C++ provides several categories of operators, including the following:
Assignment operator
Arithmetic operator
Relational operator
Logical operator
Increment/decrement operator
Conditional operator
Comma operator
The size of operator
Explicit type casting operators, etc
Operators ( cont.…)
 Assignment operator (=).
The assignment operator causes the operand on the left side of the assignment statement to have its valu
changed to the value on the right side of the statement.
Syntax: Operand1=Operand2;
Operand1 is always a variable
Operand2 can be one or combination of:
A literal constant: E.g. x=12
A variable: E.g. x=y;
An expression: E.g. x=y+2;
 Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=,&=, ^=).
Compound assignment operator is the combination of the assignment operator with other operators like
arithmetic and bit wise operators.
E.g.:
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a – 5;
a /= b; is equivalent to a = a / b;
price *= units + 1 is equivalent to price = price * (units + 1);
Operators ( cont.…)
• Arithmetic operators ( +, -, *, /, % )
Modulo (%) is the operation that gives the remainder of a division
of two values.
E.g.:
a = 11 % 3
a is 2

Commands/Syntax

Programming languages are ruly languages.


They have rules about grammar, spelling, punctuation, etc.
You need to learn the rules of a programming language, just as you
learned to speak and write English.
Loops

A loop is a repetition of all or part of the commands in a program.


A loop often has a counter (a variable) and continues to repeat a
specified number of times.
A loop may also continue until a certain condition is met (e.g., until
the end of a file or until a number reaches a set limit)
Decisions

• You saw a flowchart symbol for decisions.


• A program often needs to decide whether something is true or false
in order to see which way to continue.
• Programs often use IF (or IF THEN or IF THEN ELSE) statements to
show a decision.
Decisions

• An IF statement always has a condition to check, often a comparison


between a variable and a number.
• The IF statement also must specify what to do if the
condition/comparison is true.
• These instructions (for “true”) may come after the word THEN, or
they may simply be listed.
Decisions

• In an IF THEN statement, when the condition is false, the program


simply ignores the THEN commands and continues to the next line.
• In an IF THEN ELSE statement, commands are given for both the true
and false conditions.
Functions

• In most programming languages, small sub-programs are used to perform


some of the tasks.
• These may be called functions, subroutines, handlers, or other such terms.
• Functions often have names (e.g., getName or CALCTAX).
Functions

• A function generally gets information from the main program, performs


some task, and returns information back to the program.
• Functions follow the same rules of syntax, etc. as the main program.
• JavaScript code is primarily made of a series of functions.
Hints for Writing Code

• “Code” means writing the program in the appropriate language


• Be sure the code is exact (spelling, capitals/lower case, punctuation,
etc).
• Write part of the code, try it, then write more.
Debugging

• To “debug” means to try a program, then fix any


mistakes.
• Virtually no program works the first time you run it.
There are just too many places to make errors.
• When you are debugging a program, look for
spelling and punctuation errors.
• Fix one error at a time, then try the program again.
General form of a C++ program
// Program description
#include directives
int main()
{
constant declarations;
variable declarations;
executable statements;
return 0;
}
A First Program – Hello_World.cpp

Preprocessor // Program: Display greetings


directives // This is Comment.
Comments

#include <iostream> Provides simple access


Function using namespace std;
named int main() {
main() cout << "Hello world!" << endl;
indicates return 0;
start of }
program
Ends executions Insertion
Function
of main() which ends statement
program
C++ keywords

• Keywords appear in blue in Quincy and Visual C++.


• Each keyword has a predefined purpose in the language.
• Do not use keywords as variable and constant names!!
• We shall cover the following keywords in this class:
bool, break, case, char, const, continue,
do, default, double, else, extern, false,
float, for, if, int, long, namespace,
return, short, static, struct, switch,
typedef, true, unsigned, void, while,
signed,
C++ identifiers
• Identifiers appear in black in Visual C++ and Quincy.
• An identifier is a name for a variable, constant, function, etc.
• It consists of a letter followed by any sequence of letters, digits, and underscores.
• Examples of valid identifiers: First_name, age, y2000, y2k
• Examples of invalid identifiers: 2000y
• Identifiers cannot have special characters in them. For example: X=Y, J-20,
~Ricky,*Michael are invalid identifiers.
• Identifiers are case-sensitive. For example: Hello, hello, WHOAMI,
WhoAmI, whoami are unique identifiers.
C++ comments
• Comments appear in green in Quincy and Visual C++.
• Comments are explanatory notes; they are ignored by
the compiler.
• There are two ways to include comments in a program:

// A double slash marks the start of a //single


line comment.

/* A slash followed by an asterisk marks the


start of a multiple line comment. It ends with
an asterisk followed by a slash. */
C++ compiler directives

• Compiler directives appear in blue in Quincy and Visual C++.


• The #include directive tells the compiler to include some already
existing C++ code in your program.
• The included file is then linked with the program.
• There are two forms of #include statements:
#include <iostream> //for pre-defined files

#include "my_lib.h" //for user-defined files


Programming Style
C++ is a free-format language, which means that:
• Extra blanks (spaces) or tabs before or after identifiers/operators
are ignored.
• Blank lines are ignored by the compiler just like comments.
• Code can be indented in any way.
• There can be more than one statement on a single line.
• A single statement can continue over several lines.
Programming Style (cont. )
In order to improve the readability of your program, use the
following conventions:
• Start the program with a header that tells what the program
does.
• Use meaningful variable names.
• Document each variable declaration with a comment telling
what the variable is used for.
• Place each executable statement on a single line.
• A segment of code is a sequence of executable statements that
belong together.
• Use blank lines to separate different segments of code.
• Document each segment of code with a comment telling
what the segment does.
Assignment Operators
• Assignment expression abbreviations
c = c + 3; can be abbreviated as c += 3; using the addition assignment operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators include:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Increment and Decrement
Operators
• Increment operator (c++) - can be used instead of c += 1
• Decrement operator (c--) - can be used instead of c -= 1
• Preincrement
• When the operator is used before the variable (++c or ––c)
• Variable is changed, then the expression it is in is evaluated.
• Posincrement
• When the operator is used after the variable (c++ or c--)
• Expression the variable is in executes, then the variable is changed.
A Simple C++ Example
// C++ simple example C++ style comments

#include <iostream.h> //for C++ Input and Output


int main ()
{ standard output stream object
int number3; stream insertion operator

cout << "Enter a number:";


cin >> number3;
stream extraction operator
int number2, sum; standard input stream object

cout << "Enter another number:";


cin >> number2;

sum = number2 + number3;


cout << "Sum is: " << sum <<endl;
stream manipulator
return 0;
Concatenating insertion operators
}

57
A Simple C++ Program

• <iostream>
• Must be included for any program that outputs data to the screen or inputs
data from the keyboard using C++ style stream input/output.
• Replaces <stdio.h> of C

• C++ requires you to specify the return type, possibly void, for all
functions.
• Specifying a parameter list with empty parentheses is equivalent to
specifying a void parameter list in C.

58
Notes on Simple C++ Program

• Stream manipulator endl


• Outputs a newline.
• Flushes the output buffer

Note: ends flushes the buffer


but does
• The notation std::cout not addanewline.
specifies name (cout ) that belongs
to the namespace std.

Namespace: a generalization of scope.


C++ allows access to multiple namespaces
with the ' :: ' operator

59
Header Files
• C++ Standard Library header files
• Each contains a portion of the Standard Library.
• Function prototypes for the related functions
• Definitions of various class types and functions
• Constants needed by those functions
• “Instruct” the compiler on how to interface with library and user-written components.
• Header file names ending in .h
• Are “old-style” header files
• Superseded by the C++ Standard Library header files
• Use #include directive to include class in a program.

60
C++ Standard Library header files
C++ Standard
Library header Explanation
files
<iostream> Contains function prototypes for the C++ standard input and
standard output functions. This header file replaces header file
<iostream.h>. This header is discussed in detail in
Chapter 26, Stream Input/Output.
<iomanip> Contains function prototypes for stream manipulators that format
streams of data. This header file replaces header file
<iomanip.h>. This header is used in Chapter 26, Stream
Input/Output.
<cmath> Contains function prototypes for math library functions. This
header file replaces header file <math.h>.
<cstdlib> Contains function prototypes for conversions of numbers to text,
text to numbers, memory allocation, random numbers and various
other utility functions. This header file replaces header file
<stdlib>.
<ctime> Contains function prototypes and types for manipulating the time
and date. This header file replaces header file <time.h>.
<vector>, These header files contain classes that implement the C++
<list> Standard Library containers. Containers store data during a
<deque>, program’s execution.
<queue>,
<stack>,
<map>,
<set>,
<bitset>

61

You might also like