0% found this document useful (0 votes)
86 views220 pages

Chapter One: Problem Solving Using Computers

This document provides an overview of computer fundamentals and problem solving using computers. It discusses what a computer is, components of a computer system including hardware and software. It also covers computer programming languages from first to fifth generation as well as problem solving techniques. The document concludes with an overview of the software development method.

Uploaded by

minichel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views220 pages

Chapter One: Problem Solving Using Computers

This document provides an overview of computer fundamentals and problem solving using computers. It discusses what a computer is, components of a computer system including hardware and software. It also covers computer programming languages from first to fifth generation as well as problem solving techniques. The document concludes with an overview of the software development method.

Uploaded by

minichel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 220

Chapter One

Problem solving using computers

Simegnew A.
Computer Fundamentals
What is a Computer?
Why Computer?
Speed

Accuracy

Storage Capability

Versatility

Diligence

Automatic
Cont..
What is computer system?
Hardware
 Input Devices
 Central Processing Unit (CPU)
 Output Devices
 Storage devices
 Primary storage device
 Secondary storage device
Software
 Application Software
 System software
Cont..
Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices
e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,
and Tape and NIC Mouse Printer

CPU: It retrieves instructions from memory and executes them


Cont…
Memory: to store data and program instructions for CPU to
execute
A memory unit is an ordered sequence of bytes, each holds eight bits
A program and its data must be brought to memory before they can be
executed
A memory byte is never empty, but its initial content may be
meaningless to your program
The current content of a memory byte is lost whenever new information
is placed in it
Memory address Memory content

Cont.. .
.
.
.
. .
2000 01001010 Encoding for character ‘J’
2001 01100001 Encoding for character ‘a’
2002 01110110 Encoding for character ‘v’
2003 01100001 Encoding for character ‘a’
2004 00000011 Encoding for number 3

How data is stored?


Data of various kinds, such as numbers, characters, and strings, are
encoded as a series of bits (zeros and ones)
If computer needs to store a large number that cannot fit into a single
byte, it uses a number of adjacent bytes
No two data can share or split a same byte.
A byte is the minimum storage unit.
Cont…

Storage Device: Memory is volatile, because information is lost


when the power is off
Programs and data are permanently stored on storage devices and are
moved to memory when the computer actually uses them
Output Devices: Monitor
The monitor displays information (text and graphics)
The resolution and dot pitch determine the quality of the display
Resolution: The resolution specifies the number of pixels per
square inch
Pixels (short for “picture elements”) are tiny dots that form an image on
the screen
The higher the resolution, the sharper and clearer the image is
Dot pitch: The dot pitch is the amount of space between pixels
 The smaller the dot pitch, the better the display
Con…
Communication Device: A regular modem uses a phone line and
can transfer data in a speed up to 56,000 bps (bits per second)
A DSL (digital subscriber line) also uses a phone line and can transfer
data in a speed 20 times faster than a regular modem
A cable modem uses the TV cable line maintained by the cable company
A cable modem is as fast as a DSL
Network interface card (NIC) is a device to connect a computer to a local
area network (LAN)
Programming Language
What is Natural language?
What is Program?
What is Programming Language?
Computer programming (programming or coding)?
In order to solve a given problem, computers must be given the correct
instruction about how they can solve it

Several hundred programming languages are in use today, each varying


in their specific syntax, but showing similarities in purpose
What skills do we need to be a programmer?
Programming Language Skill: knowing one or more programming
language to talk to the computer and instruct the machine to perform a
task.
Problem Solving Skill: skills on how to solve real world problem and
represent the solution in understandable format.
Algorithm Development: skill of coming up with sequence of simple
and human understandable set of instructions showing the step of
solving the problem.
Generation of Programming Language
Programming languages fit into five generations
First generation languages to fifth-generation languages
Categorized into two broad categories
Low-level languages:- are machine-dependent
 Designed to be run on a particular computer
High-level languages:- are machine-independent
 Can be run on a variety of computers
The first two generations were low-level and the rest high-level of
programming languages
First generation (Machine languages, 1940’s)
Difficult to program in
They are dependent on machine languages of the type of computer
being used
Machine language is the ultimate low-level language
All the instructions were given in binary form
Programmer must remember exact memory addresses used to store data
and instructions
Second generation (Assembly languages, appeared in the early 1950’s)

Use symbolic names for operations and storage locations


Assembly language is easier to use than machine language but it is still
difficult to understand.
However, no matter how close assembly language is to machine code,
computers still cannot understand it
A systems program called an assembler translates it into machine
language
Created by the assembler from the original program (source code) is
called object code
Thus assembly languages are unique to a specific computer (machine)
Third generation (High-level languages, emerged from 1950’s - 1970’s)

Use English-like instructions like print


Mathematicians were able to define variables with statements such as
Z=A+B
Has syntax rules that must be followed
Two types of systems programs exist for translating them into machine
language
Interpreters: Translate source code programs one line at a time
Advantages - fairly easy to write, and easy to debug
Disadvantage - SLOW
 Compilers: Translate the entire source code program before execution
Advantages – fast
Disadvantages - harder to write and debug
Fourth-generation (Since late 70’s)
Have simple, English-like syntax rules
Commonly used to access databases
Are nonprocedural languages
There are several categories of 4GLs languages
The most common once are:
Query languages: allow the user to retrieve information from databases by following
simple syntax rules
Report generators: produce customized reports using data stored in a database
 The user specifies the data to be in the report, how the report should be formatted, and whether any
subtotals and totals are needed
Application generators: the user writes programs to allow data to be entered into the
database
Graphic languages: Retrieve data from files or databases and display them in graphic
format
Fifth-generation (1990’s)
Used in artificial intelligence and expert systems
Nonprocedural languages and are also commonly used to query databases
Fifth-generation languages are the “natural” languages whose instructions
closely resemble human speech
"Get me Debela’s sales figures for the 1997 financial year" is a typical instruction
Very powerful hardware and software are required to execute such programs
Because of the complexity involved in interpreting commands entered in human
language
Computers can in the future have the ability to think for themselves
Can draw their own inferences using programmed information in large
databases
Complex processes like understanding speech would appear to be trivial
Problem solving Techniques
Problems: Undesirable situations that prevent an organization from
fully achieving its purpose, goals and objectives
Problem solving :Is the process of transforming the description of a problem into
the solution of that problem
Is basic intellectual process that has been refined and systemized for the various
challenges people face
There are two approaches of problem solving:
Top down design: Disintegrate a larger problem into more smaller and
manageable problems to narrow the problem domain
Bottom up design: lowest level component are built first and the system builds
up from the bottom until the whole process is finally completed
Problem solving Techniques
In computer programming two facts are given more weight:
The first part focuses on defining the problem and logical procedures to follow in solving it.
The second introduces the means by which programmers communicate those procedures
to the computer system so that it can be executed.
The programs we design need to be
Reliable: The program should always do what it is expected to do and handle all types of
expectations
Maintainable: The program should be in a way that it could be modified and upgraded when the
need arises
Portable: It needs to be possible to adapt the software written for one type of computer to
another with minimum modification.
Efficient: The program should be designed to make optimal use of time, space and other
resources
Software Development Method
Is the method (approach) that software Engineers use in solving problems in computing

 Is called software life cycle


The software life cycle has the following components
1. Preliminary Investigation
2. Analysis
3. Design
4. Implementation
5. Testing
6. Maintenance
Preliminary Investigation
Defining the problem
 Examines documents, work papers, and procedures
 Observe system operations
 Interview key users of the system
 Suggesting a solution (often improving an existing one or building a new information
system)

Feasibility study (Determine whether the solution is feasible)


 Technical feasibility: Whether implementation is possible with the available or affordable
hardware, software and other technical resources.
 Economic feasibility: Whether the benefits of the proposed solution outweigh the costs
 Operational feasibility: Whether the proposed solution is desirable within the existing
managerial and organizational framework.
Preliminary Investigation
Feasibility study checks:
If the system contributes organizational objectives. 

If the system can be engineered using current technology and within budget.

If the system can be integrated with other systems that are used. 
Requirement Analysis (Requirement Gathering)
Try to understand the business in general: (activities done, how it is done, etc)
Define the specific information requirements: who needs what information, where, when,
and how
Present a detail description of the functions the new system must perform
 In this phase we identify:
 Inputs to the problem and their form (Filing status: Single, Married, divorced)
 Outputs expected from the solution and their form
 Constraints (What are the limits on the data? Income cannot be a negative number)
 Assumptions (Problem deals in $US, Only for 2005)
 Formulas (For determining the area, it is length x width)
Design
Also known as algorithm design
In this phase we focus on ‚HOW‛ question.
There are different ways of describing of algorithm
 Pseudo codes
 Structured chart
 Flow chart
Implementation
Algorithms cannot be executed (performed) directly by the computer
The process of writing the program
Conversion of algorithm into desired programming language.
Testing
Also called program verification or debugging.
Removing error in the program.
Error in the program is called bug and the process of correcting known error is called
Debugging.
Three types of error: - syntax error, run time error and logical error.
Unit testing (Program testing): Test each unit of program in the system separately
System testing: Test the functions of the system as a whole (performance, capacity for
file storage, recovery and restart capabilities)
Acceptance testing: System is evaluated by users and management
Maintenance
This stage is ongoing throughout the life of the system
Involves correcting faults which are not detected during testing
Fix bugs found by the customer
Make modifications
Add new features
Software Crisis
Let us now focus on the Causes of software crisis:
Due to the Projects running over-budget
Due to the Projects running over-time
Software was very inefficient and was of low quality
Software often did not meet requirements
Code was difficult to maintain and Projects were a mess and
unmanageable
Cont…
There are some solutions for preventing software crisis:
 Experience working as a team member on a software development project
 Knowledge of basic statics and experimental design
 Less time and fewer people needed for productive innovation
Algorithm development
Programs vs. Algorithms
To make a computer do anything, you have to write a program
 To write a computer program, you have to tell the computer, step by step, exactly what
you want it to do.
The computer then "executes" the program, following each step mechanically, to
accomplish the end goal.
An algorithm is a finite, step-by-step sequence of instructions that describe how the data
is to be processed to produce the desired outputs
The algorithm is implemented by a program
Pseudocode
Is an artificial and informal language that helps programmers develop algorithms
Allows the designer to focus on the logic of the algorithm without being distracted by
details of language syntax
Text-based" detail (algorithmic) design tool
Pseudocode is not a hard notation, since it is read by other people, not by the computer
Pseudocode
Pseudo code can be broken down into five components.
 Variables
 Assignment
 Input/output
 Selection
 Repetition
 Computation/Assignment 
 set the value of "variable" to :"arithmetic expression" or
        "variable" equals "expression" or
        "variable" = "expression"
• Input/Output
–    get "variable", "variable", ...
   display "variable", "variable", ...
• Conditional
–          if  "condition"
                   (subordinate) statement 1 
                     etc ...
       else
                    (subordinate) statement 2
                    etc ...
• Iterative
–           while "condition" 
                    (subordinate) statement 1
                   etc ...
Example
 Write a program that obtains two integer numbers from the user. It will print out the
sum of those numbers.
 Pseudo code:
 Prompt the user to enter the first integer
 Prompt the user to enter a second integer
 Compute the sum of the two user inputs
 Display an output prompt that explains the answer as the sum
 Display the result
Example
 Write pseudo code that reads two numbers and multiplies them together and print out
their product.
Read num1 , num2
Set multi to num1*num2
Write multi
Flow Chart
A graphic representation of an algorithm, often used in the design phase of programming
to work out the logical flow of a program
Flowchart symbols
Process Symbol
 Arithmetic computations or data movement
Decision Symbol
 Yes/No decision to be made by the program
Flowline
 Instructions transferring to next step
Start/End Symbol
 Represent the start and the end of the program
Input/Output Symbol
 Show input or output data
Selection

True
• Single Selection (if) Won Raise
lottery? Hand
• If you’ve won the lottery:
raise your hand False
• Double Selection (if-else)
• If you’re happy:
smile
else:
frown False True
Frown Happy? Smile
Selection (continued)

• Multiple Selection (switch)


If the light is ... Light True
Red? Stop
red -> stop
False
green -> go True
Light
Go
yellow -> slow down False
Green?

True
Light Slow
Yellow? Down
False
Example
 Write the algorithmic description and draw a flow chart to find the following sum.
Algorithmic description
Start
1. Initialize sum to 0 and counter to 1
Sum = 0
1.1 If the counter is less than or equal to 50 Counter = 1

Add counter to sum Is Yes


Counter Print Sum
Increase counter by 1 > 50 ?
No

Repeat step 1.1 Sum = Sum + Counter End

1.2. Else Counter = Counter + 1

Exit
2. Write sum
Example
 A certain company plan to give a 10% bonus to each of its employees at the end of
every year. If an employee has been working 10/more years at the company, she/he is
to get an additional birr 100. Draw a flowchart of an algorithm to calculate and print
the bonus for a given employee.
Chapter Two
Fundamentals of C++ Programming Language
Your readiness to learn:
Your readiness to learn:
Your readiness to learn:
Your readiness to learn:
Programming paradigm…

A programming paradigm is a fundamental style of programming

Unstructured Programming

Procedural programming .

Structured Programming

Object Oriented Programming


Unstructured Programming
Consisting only of one large (usually main) program
“main program”' stands for a sequence of commands or
statements
data is global throughout the whole program

disadvantages
Complex
if the same statement sequence is needed at different locations
within the program, the sequence must be copied
Procedural programming
based upon the concept of procedure call
A procedure call is used to invoke the procedure
Procedures (routines, subroutines, methods,
functions) simply contain a series of computational
steps to be carried out to solve a problem
 We have a single program, which is divided into small
pieces called procedures

 Advantage
 to re-use the same code at different places in the
program without copying it
 easier way to keep track of program flow
 Example
 FORTRAN, ADA
Structured Programming
is a subset of procedural programming (also known as
modular programming)
procedures of a common functionality are grouped together
into separate modules
Each module can have its own data
allows each module to manage an internal state which is modified
by calls to procedures of this module
top-down design model
map out the overall program structure into separate subsections
Advantage
Reuse
easier to understand and modify
Object Oriented Programming - OOP
• Is a method of implementation in which programs are organized as
cooperative collections of objects
• Data and operations are grouped together
• Each object is capable of receiving messages, processing data, and sending
messages to other objects
• Modeling of the domain as objects so that the implementation naturally
reflects the problem at hand.
History Note
• First programmable computer
• Designed by Charles Babbage
• Began work in 1822
• Not completed in Babbage’s life time

• First programmer
• Ada Augusta, Countess of Lovelace
• Colleague of Babbage
Programming and Problem Solving

Algorithm
A sequence of precise instructions which
leads to a solution

Program
An algorithm expressed in a language the computer
can understand
Program Design
Programming is a creative process
No complete set of rules for creating a program

Program Design Process


Problem Solving Phase
 Result is an algorithm that solves the problem
Implementation Phase
 Result is the algorithm translated into a programming
language
Problem Solving Phase
Be certain the task is completely specified
What is the input?
What information is in the output?
How is the output organized?

Develop the algorithm before implementation


Experience shows this saves time in getting your
program to run.
Test the algorithm for correctness
Implementation Phase

Translate the algorithm into a programming language


Easier as you gain experience with the language
Compile the source code
Locates errors in using the programming language
Run the program on sample data
Verify correctness of results
Results may require modification of the algorithm and program
Introduction to C++
Where did C++ come from?
Derived from the C language
C was derived from the B language
B was derived from the BCPL language
C++ History

C developed by Dennis Ritchie at AT&T Bell Labs in the 1970s.


Used to maintain UNIX systems
Many commercial applications written in c
C++ developed by Bjarne Stroustrup at AT&T Bell Labs in the 1980s.
Overcame several shortcomings of C
Incorporated object oriented programming
C remains a subset of C++
Structure of C++ Program
• [Preprocessor directives]
• [Global variable declarations]
• [Prototypes of functions]
• [Definitions of functions]
Writing a Program
Commercial text editor or word processor that can produce text files
Your compiler may have its own built-in text editor
Named with the extension .CPP
Compiling
The compiler converts source code to object code
This file is often named with the extension .OBJ
1.4
Testing and Debugging
Bug
A mistake in a program
Debugging
Eliminating mistakes in programs
Program Errors

Syntax errors
Violation of the grammar rules of the language
Discovered by the compiler
 Error messages may not always show correct location of
errors
Run-time errors
Error conditions detected by the computer at run-time
Logic errors
Errors in the program’s algorithm
Most difficult to diagnose
Computer does not recognize such an error
Linking
C++ programs are typically created by
 linking together one or more OBJ files
one or more libraries
A library is a collection of linkable files
A Linker combines
The object code for the programs we write
and
The object code for the pre-compiled routines
into
The machine language program the CPU can run
Summary
• The steps to create an executable file are
• Create a source code file, with a .CPP extension.

• Compile the source code into a file with the .OBJ extension.

• Link your OBJ file with any needed libraries to produce an executable
program
Program is created in
• Phases of C++ Programs: Editor
the editor and stored
Disk on disk.
1. Edit Preprocesso Disk
Preprocessor program
processes the code.
r
2. Preprocess Compiler Disk
Compiler creates
object code and stores
it on disk.
3. Compile Linker Disk Linker links the object
code with the libraries
4. Link Primary Memory

Loader
5. Load Loader puts program
in memory.
Disk ..

6. Execute
..
..

Primary Memory
CPUtakes each
CPU instruction and
 
executes it, possibly
storing new data
..
..
values as the program
..
executes.
Showing Sample program

Every C++ program has a number of components


main function
some variable declarations
some executable statements
C++ Programs

A C++ program is a collection of one or more subprograms, called


functions
Every C++ program has a function called main
The smallest individual unit of a program written in any language is
called a token
Keyboard and Screen I/O

#include <iostream>

input data output data

executing
Keyboard program Screen

cin cout

(of type istream) (of type ostream)


Insertion Operator ( << )
Variable cout is predefined to denote an output stream that goes to the
standard output device (display screen).

The insertion operator << called “put to” takes 2 operands.

The left operand is a stream expression, such as cout. The right


operand is an expression of simple type or a string constant.
Output Statements
SYNTAX

cout << Expression << Expression . . . ;

cout statements can be linked together using << operator.


These examples yield the same output:

cout << “The answer is “ ;


cout << 3 * 4 ;

cout << “The answer is “ << 3 * 4 ;


Output Statements (String constant)
String constants (in double quotes) are to be printed as is, without the
quotes.
cout<<“Enter the number of candy bars ”;
OUTPUT: Enter the number of candy bars
“Enter the number of candy bars ” is called a prompt.
All user inputs must be preceded by a prompt to tell the user what is
expected.
You must insert spaces inside the quotes if you want them in the output.
Do not put a string in quotes on multiple lines.
Output Statements (Expression)

All expressions are computed and then outputted.


cout << “The answer is ” << 3 * 4 ;
OUTPUT: The answer is 12
Escape Sequences
The backslash is called the escape character.
It tells the compiler that the next character is “escaping” it’s typical
definition and is using its secondary definition.
Examples:
new line: \n
horizontal tab: \t
backslash: \\
double quote \”
Newline
cout<<“\n” and cout<<endl both are used to insert a blank line.
Advances the cursor to the start of the next line rather than to the next
space.
Always end the output of all programs with this statement.
Extraction Operator (>>)

Variable cin is predefined to represent an input stream from the


standard input device (the keyboard)
The extraction operator >> called “get from” takes 2 operands. The
left operand is a stream expression, such as cin--the right operand is a
variable of simple type.
Operator >> attempts to extract the next item from the input stream
and store its value in the right operand variable.
Input Statements
SYNTAX

cin >> Variable >> Variable . . . ;

cin statements can be linked together using >> operator.


These examples yield the same output:

cin >> x;
cin >> y;

cin >> x >> y;


How Extraction Operator works?

Input is not entered until user presses <ENTER> key.


Allows backspacing to correct.
Skips whitespaces (space, tabs, etc.)
Multiple inputs are stored in the order entered:
 cin>>num1>>num2;
 User inputs: 3 4
 Assigns num1 = 3 and num2 = 4
Numeric Input

Leading blanks for numbers are ignored.


If the type is double, it will convert integer to double.
Keeps reading until blank or <ENTER>.
Remember to prompt for inputs
First Program in C++

1. #include <iostream.h>
2. int main()
3. {
4. cout << "Hello World!\n";
5. return 0;
6. }
First Program in C++: Printing a Line of Text
(Cont.)
Preprocessor directives
Processed by preprocessor before compiling
Begin with #
Example
 #include <iostream>
 Tells preprocessor to include the input/output stream header file <iostream>
Common Programming Error

Forgetting to include the <iostream> header file in a program that


inputs data from the key­board or outputs data to the screen causes
the compiler to issue an error message, because the compiler cannot
recognize references to the stream components (e.g., cout).
First Program in C++: Printing a Line of Text
(Cont.)
Function main
A part of every C++ program
 Exactly one function in a program must be main
what will be executed when you run your program
“main” is function where execution starts
Can “return” a value
Example
 int main()
 This main function returns an integer (whole number)
Body is delimited by braces ({})
Statements
Instruct the program to perform an action
All statements end with a semicolon (;)
First Program in C++: Printing a Line of Text
(Cont.)
Stream insertion operator <<
Value to right (right operand) inserted into left operand
Example
 cout << "Hello World!\n";
 Inserts the string " "Hello World!” " into the standard output
 Displays to the screen

Escape characters
A character preceded by "\"
 Indicates “special” character output
Example
 "\n"
 Cursor moves to beginning of next line on the screen
Common Programming Error

Omitting the semicolon at the end of a C++ statement is a syntax


error. (preprocessor directives do not end in a semicolon.) The
syntax of a programming language specifies the rules for creating
a proper program in that language. A syntax error occurs when
the compiler encounters code that violates C++’s language rules
(i.e., its syntax). The compiler normally issues an error message
to help the programmer locate and fix the incorrect code.
Common Programming Error

Syntax errors are also called compiler errors, compile-time


errors or compilation errors, because the compiler detects
them during the compilation phase. You will be unable to
execute your program until you correct all the syntax errors
in it. As you will see, some compilation errors are not syntax
errors.
First Program in C++: Printing a Line of Text (Cont.)

return statement
One of several means to exit a function
When used at the end of main
 The value 0 indicates the program terminated successfully
 Example
 return 0;
Basic Elements
Five kind of tokens in C++
Comments
Keywords (reserved words)
Identifiers
Literals
Operators
Comments
Remark about programs
Explain programs to other programmers
Improve program readability
Ignored by compiler
Two types
Single-line comment
 Begin with //
 Example
 // This is a text-printing program.
Multi-line comment
 Start with /*
 End with */
Typical uses
Identify program and who wrote it
Record when program was written
Add descriptions of modifications
Example
1 /* Fig. 2.1: fig02_01.cpp
2 Text-printing program. */
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 cout << "Welcome to C++!\n"; // display message
9
10 return 0; // indicate that program ended successfully
11

12 } // end function main

Welcome to C++!
Every program should begin with a comment that
describes the purpose of the program, author, date
and time.
Chapter Three
Constants, Variables, data Types and Operators
C++ tokens
Identifiers: Names given to different entries such as variables, structures, and functions

Keywords: Reserved words which have fixed meaning and its meaning cannot be changed

Operators: A symbol that is used to perform mathematical or logical manipulations

Constants: Are like a variable, except that their value never changes during execution once
defined
Identifiers
Programmer given names
Identify classes, variables, functions, etc.
Consist of letters, digits, and the underscore character (_)
Must begin with a letter or underscore
 Not be a reserved word, they are reserved for special purpose
C++ is case sensitive
Some predefined identifiers are cout and cin
Unlike reserved words, predefined identifiers may be redefined, but
it is not a good idea
Rules for naming C++ identifiers
Identifiers must begin with a letter or underscore( _ ).
No special characters are allowed in identifier naming, only letters,
digits or underscores can be used.
A keyword can’t be an identifier.
White space is not allowed within identifier
It should only be up to 31 characters long
Legal and Illegal Identifiers

The following are legal identifiers in C++:


first
conversion
payRate
Keywords (reserved words)
Words with special meaning to the compiler
Have a predefined meaning that can’t be changed
All reserved words are in lower-case letters
Must not be used for any other purposes
Example
and , auto, bool, break, char, const, default, delete ,do, double, else, for, friend,
new, void, if
Variables

A variable is a memory address where data can be stored and changed.


Declaring a variable means specifying both its name and its data type.
All variables have two important attributes
A type - Once defined, the type of a C++ variable cannot be changed
A value - can be changed by assigning a new value
E.g. int a = 5;
Type integer
Value 5
Variable Declaration
All variables must declared before use.
At the top of the program
Just before use.
Commas are used to separate identifiers of the same type.
int count, age;
Variables can be initialized to a starting value when they
are declared
int count = 0;
int age, count = 0;
Variable Declaration
defining (creating) a variable
Two parts
 Variable name - unique name of the memory location
 Data type (or type) - defines what kind of values the variable can hold
Syntax
<type> <Var-idf>;
E.g.
 double varTime;
 int myAge;
Can declare several variables of same type in one declaration
 Comma-separated list
 int integer1, integer2, sum;
Variables must be declared before used
Variable names
Valid identifier
 Series of characters (letters, digits, underscores)
 Cannot begin with digit
 Case sensitive
Assignment operator =
Assigns value on left to variable on right
Binary operator (two operands)
Example:
 sum = variable1 + variable2;
 Add the values of variable1 and variable2
 Store result in sum
1 // Fig. 2.5: fig02_05.cpp
2 // Addition program that displays the sum of two numbers.

Outline
3
4
#include <iostream.h> // allows program to perform input and output

5 // function main begins program execution


6 int main()
7 {
8 // variable declarations
9 int number1; // first integer to add
10 int number2; // second integer to add
11 int sum; // sum of number1 and number2
12
13 cout << "Enter first integer: "; // prompt user for data
14 std::cin >> number1; // read first integer from user into number1
15
16 cout << "Enter second integer: "; // prompt user for data
17 cin >> number2; // read second integer from user into number2
18
19 sum = number1 + number2; // add the numbers; store result in sum
20
21 cout << "Sum is " << sum << std::endl; // display sum; end line
22
23 return 0; // indicate that program ended successfully
24
25 } // end function main

Enter first integer: 45


Enter second integer: 72
Sum is 117
Variables and Memory Concept

Variable names
Correspond to actual locations in computer's memory
 Every variable has name, type, size and value
When new value placed into variable, overwrites old value
 Writing to memory is destructive
Reading variables from memory nondestructive
Example
 int number1= 45;
 int number2= 72;
 int sum = 0;
 sum = number1 + number2;
 Value of sum is overwritten
 Values of number1 and number2 remain intact
CONSTANTS

Constants are treated just like regular variables except that their
values cannot be modified after their definition
There are two simple ways in C++ to define constants
Using #define preprocessor.
Using const keyword
The #define Preprocessor

Following is the form to use #define preprocessor to define a constant


#define identifier value
Eg,
RESULT
The const Keyword

Following is the form


const type variable = value;
Eg,
RESULT

Note that it is a good programming practice to define constants in CAPITALS.


Data Types
When you define a variable in C++, you must tell the compiler
what kind of variable it is
Tell the data type

Data Type: set of values together with a set of operations


C++ data can be classified into three categories:
Simple data type
Structured data type
Pointers
Simple Data Types
Three categories of simple data Type
Integral: integers (numbers without a decimal)

Floating-point: decimal numbers

Enumeration type: user-defined data type


Type Size Values

unsigned short int 2 bytes 0 to 65,535

short int(signed short 2 bytes -32,768 to 32,767


int)
unsigned long int 4 bytes 0 to 4,294,967,295

long int(signed long 4 bytes -2,147,483,648 to 2,147,483,647


int)
int
2 bytes -32,768 to 32,767

unsigned int 2 bytes 0 to 65,535

signed int 2 bytes -32,768 to 32,767

char 1 byte 256 character values

float 4 bytes 3.4e-38 to 3.4e38

double 8 bytes 1.7e-308 to 1.7e308

long double 10 1.2e-4932 to 1.2e4932


bytes
Simple Data Types
Type int
represent integers or whole numbers
Some rules to follow:
Plus signs do not need to be written before the number
Minus signs must be written when using negative
Decimal points cannot be used
Commas cannot be used
Leading zeros should be avoided (octal or base 8 #’s
Signed - negative or positive
Unsigned - positive
Short
Long
Simple Data Types

Type double, float


used to represent real numbers
many programmers use type float
avoid leading zeros, trailing zeros are ignored
long double
Simple Data Types
Type char
used to represent character data
a single character which includes a space
1 byte, enough to hold 256 values
must be enclosed in single quotes eg. ‘d’
Escape sequences treated as single char
‘\n’ newline
‘\’’ apostrophe
‘\”’ double quote
‘\t’ tab
(0-255) or as a member of the ASCII set
E.g. the lowercase letter "a" is assigned the value 97
Simple Data Types

Strings
used to represent textual information
string constants must be enclosed in double quotation marks
eg. “Hello world!”
empty string “”
new line char or string “\n”
“the word \”hello\”” (puts quotes around “hello” )
String variables use:
#include “apstring.cpp”
use quotes for user supplied libraries
Area.cpp
#include <iostream.h>
int main() {
float Length;
float Width;
// Extract length and width
cout << enter width and length: ";
cin >> Length >> Width;
// Compute and insert the area
float Area = Length * Width;
cout << "Area = " << Area << " = Length "
<< Length << " * Width " << Width <<
endl;
return 0;}
• Write a program that accepts a character from the user and echo it to
the screen.
Operator
A symbol that tells the compiler to perform specific mathematical or
logical manipulations
5 Operators
Arithmetic operators
Assignment operator
Increment/Decrement operators
Relational operators
Logical operators
Arithmetic Operators

Common
Addition +
Subtraction -
Multiplication *
Division /
Mod %
Integer Division
Integer division produces an integer result
Truncates the result

Examples
3 / 2 evaluates to 1
4 / 6 evaluates to 0
10 / 3 evaluates to 3
Mod
Produces the remainder of the division

Examples
5 % 2 evaluates to 1
12 % 4 evaluates to 0
4 % 5 evaluates to 4
Arithmetic Operators and Precedence
 Consider m*x + b which of the following is it equivalent to
 (m * x) + b
 m * (x + b)
 Operator precedence tells how to evaluate expressions

 Standard precedence order


 () Evaluate first, if nested innermost
done first
 */% Evaluate second. If there are several,
then evaluate from left-to-right
 +- Evaluate third. If there are several,
then evaluate from left-to-right
Arithmetic Operator Precedence

Examples
20 - 4 / 5 * 2 + 3 * 5 % 4

(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
Increment & Decrement Operators
Increment operator: increment variable by 1
Decrement operator: decrement variable by 1
Pre-increment: ++variable
Post-increment: variable++
Pre-decrement: --variable
Post-decrement: variable--
Increment & Decrement Operators (continued)

++count; or count++; increments the value of count by 1


--count; or count--; decrements the value of count by 1
If x = 5; and y = ++x;
After the second statement both x and y are 6
If x = 5; and y = x++;
After the second statement y is 5 and x is 6
Assignment Operator

Assignment operator =
Assigns value on left to variable on right
Example:
int a= 5;
float b= 9.66;
char ch=‘d’;
int m, n, p;
m = n = p = 100;
Assignment Operator
Compound assignment Operator
+=, -=, *=, /=, %=
Compound assignment Operator
Relational Operators
Operator
Name Example

== Equality 5 == 5 // gives 1

!= Inequality 5 != 5 // gives 0

< Less Than 5 < 5.5 // gives 1

<= Less Than or Equal 5 <= 5 // gives 1

> Greater Than 5 > 5.5 // gives 0

>= Greater Than or Equal 6.3 >= 5 // gives 1

Relational operators
Logical Operators
• Like the relational operators, logical operators
evaluate to 1 or 0.

Operator Name Example

! Logical Negation !(5 == 5) // gives 0

&& Logical And 5 < 6 && 6 < 6 // gives 0

|| Logical Or 5 < 6 || 6 < 5 // gives 1

Logical operators
Type conversion
• A value in any of the built-in types can be converted
• Called type cast
• Syntax
• (<data – type> )value; or <data – type> (value);
• E.g
• (int) 3.14 // converts 3.14 to an int to give 3
• (long) 3.14 // converts 3.14 to a long to give 3L
• (double) 2 // converts 2 to a double to give 2.0
• (char) 122 // converts 122 to a char whose code is 122
• (unsigned short) 3.14 // gives 3 as an unsigned short
Some times the compiler does the type casting – implicit
type cast
E.g
double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d;
Chapter Four
Control Flow Statements
(Selection and Repetition Statements
Introduction
C++ provides different forms of statements for different purposes
Declaration statements
Assignment-like statements
etc
The order in which statements are executed is called flow control
Branching statements:
Specify alternate paths of execution, depending on the outcome of a logical
condition
Loop statements:
specify computations, which need to be repeated until a certain logical
condition is satisfied.
if-else Statement Syntax
Formal syntax:
if (<boolean_expression>)
<yes_statement>
else
<no_statement>
Note each alternative is only ONE statement!
To have multiple statements execute in either branch  use
compound statement
Compound/Block Statement
Only "get" one statement per branch
Must use compound statement { } for multiples
Also called a "block" statement
Each block should have block statement
Even if just one statement
Enhances readability
Compound Statement in Action
Note indenting in this example:
if (myScore > yourScore)
{
cout << "I win!\n";
wager = wager + 100;
}
else
{
cout << "I wish these were golf scores.\n";
wager = 0;
}
The Optional else
else clause is optional
If, in the false branch (else), you want "nothing" to happen, leave it
out
Example:
if (sales >= minimum)
salary = salary + bonus;
cout << "Salary = %" << salary;
Note: nothing to do for false condition, so there is no else clause!
Execution continues with cout statement
Example2, when dividing two values, we may want to check that the
denominator is nonzero
Nested Statements
if-else statements contain smaller statements
Compound or simple statements (we’ve seen)
Can also contain any statement at all, including another if-else stmt!
Example:
if (speed > 55)
if (speed > 80)
cout << "You’re really speeding!";
else
cout << "You’re speeding.";
Note proper indenting!
Multi way if-else: Display Statements
Multi way if-else Example:
Display
Write Program to find number is Even or Odd using if-else statement
Write a program that accepts a character from the user and:
If the char is number print “the character is a number”
 If the char is capital letter print “the character is capital letter”
If the char is small letter print “the character is small letter”
Else “the character is special character”;
 to the screen.
The switch Statement
A new statement for controlling multiple branches
Uses controlling expression which returns bool data type (true or
false)
Syntax:
 next slide
The switch Statement
The switch Statement in Action
The switch Statement in Action
switch(1) {
case 1 : cout << '1';
case 2 : cout << '2';
}
switch(1) {
case 1 : cout << '1';
break;
case 2 : cout << '2';
break;
}
The switch: multiple case labels
Execution "falls thru" until break
switch provides a "point of entry"
Example:
case "A":
case "a":
cout << "Excellent: you got an "A"!\n";
break;
case "B":
case "b":
cout << "Good: you got a "B"!\n";
break;
Note multiple labels provide same "entry"
Equivalent to if statement
switch (expr) {
case c1:
statements // do these if expr == c1
break;
case c2:
statements // do these if expr == c2
break;
case c2: // multiple values can share same statements
case c3:
case c4:
statements // do these if expr == any of c2, c3, or c4 break;
default:
statements // do these if expr != any above}
Equivalent to if statement
if (expr==c1) {
statements
} else if (expr==c2) {
statements
} else if (expr==c2 || expr==c3 || expr==c4) {
Statements
} else {
Statements
}
Loops
A loop is a way of repeating a series of instructions several
times
Two Parts to Repetition
a Body
 what needs to be repeated
 must be marked off in some fashion like {}
a Control expression
 some way to make the repetition stop when desired
 Infinite loops not wanted!
Loops
3 Types of loops in C++
– while
Most flexible
No "restrictions"
– do -while
Least flexible
Always executes loop body at least once
– for
Natural "counting" loop
while Loops Syntax
The while statement (also called the while loop) provides a way of
repeating a statement while a condition holds.
while Loops
First expression (called the loop condition) is evaluated
If the outcome is nonzero then statement (called the loop body) is
executed and the whole process is repeated
Otherwise, the loop is terminated
while Loops Example
Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
– Loop body executes how many times?
while Loops Example2
void main()
{
int sum =0,i=1,n;
cout<<"Enter the maximum number"<<endl;
cin>>n;
while (i <= n)
sum += i++;
cout<<"the sum of numbers from 1 to <<n<<"is =:"<<sum;
}
do-while Loop Syntax
The do statement (also called do loop) is similar to the while statement,
except that its body is executed first and then the loop condition is
examined.
do-while Loop
First statement is executed and then expression is evaluated.
If the outcome of the latter is nonzero then the whole process is
repeated.
Otherwise, the loop is terminated.
The do loop is less frequently used than the while loop.
It is useful for situations where we need the loop body to be executed at least
once, regardless of the loop condition.
do-while Loop Example
count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition
Loop body executes how many times?
do-while loops always execute body at least once!
do-while Loop Example2
void main ()
{
char ch;
do
{
cout<<"Hello!\n";
cout<<"Do you want to display more Hello's (Y/N) ";
cin >>ch;
} while (ch != 'N');
}
for Loop Syntax
This is the simplest and straight-forward looping construct that has the
following general look:
for(expression1;expression2;expression3)
First expression1 is evaluated. Each time round the loop, expression2 is

evaluated. If the outcome is nonzero then statement is executed and


expression3 is evaluated. Otherwise, the loop is terminated.
For Loop Example
for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}
How many times does loop body execute?
For Loop Example
void main ()
{
int x, limit, sum;
cout << "Please enter a number bigger than 1 : ";
cin >> limit;
sum = 0;
for (x = 1; x <= limit; x++) {
cout << "I am adding " << x << endl;
sum = sum + x;
}
cout << endl;
cout << "The sum of all the numbers from 1 to ";
cout << limit << " is " << sum;
return;
}
Converting Between For and While Loops

for (int i = 1; i < 1024; i *= 2) {


cout << i << endl;
}

int i = 1;
while (i < 1024) {
cout << i << endl;
i *= 2;
}
Loop Issues
Loop’s condition expression can be ANY boolean expression
Examples:
while (count<3 && done!=0)
{
// Do something
}
for (index=0;index<10 && entry!=-99)
{
// Do something
}
Loop Pitfalls: Misplaced ;
Watch the misplaced ; (semicolon)
Example:
while (response != 0) ;
{
cout << "Enter val: ";
cin >> response;
}
Notice the ";" after the while condition!
Result here: INFINITE LOOP!
Loop Pitfalls: Infinite Loops
Loop condition must evaluate to false at some iteration through loop
If not  infinite loop.
Example:
while (1)
{
cout << "Hello ";
}
A perfectly legal C++ loop  always infinite!
Nested Loops
Recall: ANY valid C++ statements can be inside body of loop
This includes additional loop statements!
Called "nested loops"
Requires careful indenting:
for (outer=0; outer<5; outer++)
for (inner=7; inner>2; inner--)
cout << outer << inner;
Notice no { } since each body is one statement
Good style dictates we use { } anyway
Nested Loops Exercise
Write a program which produces a simple multiplication table of the
following format for integers in the range 1 to 9:
The break and continue Statements
Break
Causes immediate exit from a while, for, do/while or switch
structure
Program execution continues with the first statement after the
structure
Common uses of the break statement:
Escape early from a loop
Skip the remainder of a switch structure
The break and continue Statements
Continue
Skips the remaining statements in the body of a while, for or
do/while structure and proceeds with the next iteration of the
loop
In while and do/while, the loop-continuation test is evaluated
immediately after the continue statement is executed
In the for structure, the increment expression is executed, then
the loop-continuation test is evaluated
The break and continue Statements
Causes an immediate jump to the loop test
int next = 0;
while (true){
cin >> next;
if (next < 0)
break;
if (next % 2!=0) //odd number, don’t print
continue;
cout << next << endl;
}
cout << “negative num so here we are!” << endl;
Chapter Five
Introduction to Arrays and Functions
Arrays
• Array
• Consecutive group of memory locations
• All of which have the same type
• Index
• Position number used to refer to a specific
location/element
• Also called subscript
• Place in square brackets
• Must be positive integer or integer expression
• First element has index zero, last element has index n-1
Properties of an array

• Homogeneous
• Contiguous
• Have random access to any element
• Ordered (numbered from 0 to n-1)
• Number of elements does not change - MUST be a constant when
declared
Declaring Arrays
• When declaring arrays, specify
• Name
• Type of array
• Number of elements
arrayType arrayName[ numberOfElements ];
• Examples:
int c[ 10 ];
float myArray[ 3284 ];
• Declaring multiple arrays of same type
• Format similar to regular variables
• Example:
int b[ 100 ], x[ 27 ];

178
Examples Using Arrays

• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
• If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
• All elements 0
• If too many a syntax error is produced
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
• 5 initializers, therefore 5 element array

179
Array of 12 elements
Arrays (Cont.)
• Examine array c in the figure
• c is the array name
• c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
Declaration of an Array
• The index is also called the subscript

• In C++, the first array element always has subscript 0, the


second array element has subscript 1, etc.

• The base address of an array is its beginning address in memory

182
Using a named constant

• it is very common to use a named constant to set the size of an array


• E.g.
const int SIZE = 15;
int arr[SIZE];
• useful because it can be used to control loops throughout program
• easy to change if size of array needs to be changed
•It is important to note the difference between the “seventh element of the
array” and “array element 7.”

•Array subscripts begin at 0, so the “seventh element of the array” has a


subscript of 6, while “array element 7” has a subscript of 7 and is actually
the eighth element of the array.

•Unfortunately, this distinction frequently is a source of off-by-one errors.

•To avoid such errors, we refer to specific array elements explicitly by their
array name and subscript number (e.g., c[ 6 ] or c[ 7 ]).
Solution to problem
int counter = 0, n[5], total = 0; average = total / 5;
float average; ct= 0;
while (counter < 5) while (ct < 5)
{ {
cout << "enter a number ";
if (n[ct] > average)
cin >> n[counter];
total = total + n[counter]; cout << n[ct];
counter = counter + 1; ct = ct + 1;
} }
Initializing Array
• Initializing an array in a declaration with an initializer list
• Initializer list
• Items enclosed in braces ({})
• Items in list separated by commas
• Example
• int n[] = { 10, 20, 30, 40, 50 };
• Because array size is omitted in the declaration, the
compiler determines the size of the array based on the
size of the initializer list
• Creates a five-element array
• Index values are 0, 1, 2, 3, 4
• Initialized to values 10, 20, 30, 40, 50, respectively
Initializing Array
• If fewer initializers than elements in the array
• Remaining elements are initialized to zero
• Example
• int n[ 10 ] = { 0 };
• Explicitly initializes first element to zero
• Implicitly initializes remaining nine elements to zero
• If more initializers than elements in the array
• Compilation error
Initialization of arrays
• int a[] = {1, 2, 9, 10}; // has 4 elements
• int a[5] = {2, 5, 4, 1, -2, 5}; // error!
• int a[5] = {2, 3}; // rest are zero
• int a[5] = {0}; // all are zero
• can use it with char, float, even bool
Assigning Values to
Individual Array Elements
float temps[5];
int m = 4; // Allocates memory
temps[2] = 98.6;
temps[3] = 101.2;
temps[0] = 99.4;
temps[m] = temps[3] / 2.0;
temps[1] = temps[3] - 1.2;
// What value is assigned?
7000 7004 7008 7012 7016

99.4 ? 98.6 101.2 50.6

temps[0] temps[1] temps[2] temps[3] temps[4] 189


What values are assigned?

float temps[5]; // Allocates memory


int m;

for (m = 0; m < 5; m++)


{
temps[m] = 100.0 + m * 0.2 ;
}

7000 7004 7008 7012 7016

? ? ? ? ?
temps[0] temps[1] temps[2] temps[3] temps[4] 190
Now what values are printed?
float temps[5]; // Allocates memory
int m;
.....
for (m = 4; m >= 0; m--)
{
cout << temps[m] << endl;
}

7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8


temps[0] temps[1] temps[2] temps[3] temps[4] 191
Indexes

• subscripts can be constants or variables or expressions

• if i is 5, a[i-1] refers to a[4] and a[i*2] refers to a[10]

• you can use i as a subscript at one point in the program and j as a


subscript for the same array later - only the value of the variable
matters
Variable Subscripts
float temps[5]; // Allocates memory
int m = 3;
. . . . . .
What is temps[m + 1] ?

What is temps[m] + 1 ?
7000 7004 7008 7012 7016

100.0 100.2 100.4 100.6 100.8


temps[0] temps[1] temps[2] temps[3] temps[4]
193
Selection sort - 1-d array
Algorithm for the sort
1. find the maximum in the list
2. put it in the highest numbered element by swapping it with the data
that was at that location
3. repeat 1 and 2 for shorter unsorted list - not including highest
numbered location
4. repeat 1-3 until list goes down to one
Find the maximum in the list
// n is number of elements
max = a[0]; // value of largest element // seen so far
for (i = 1; i < n; i++) // note start at 1, not 0
if (max < a[i])
max = a[i];
// now max is value of largest element in list
Find the location of the max
max = 0; // max is now location of the max
for (i = 1; i < n; i++)
if (a[max] < a[i])
max = i;
Swap with highest numbered
element at right end of list is numbered n-1

temp = a[max];
a[max] = a[n-1];
a[n-1] = temp;
Find next largest element and swap
max = 0;
for (i = 1; i < n-1; i++) // note n-1, not n
{
if (a[max] < a[i])
max = i;
}
temp = a[max];
a[max] = a[n-1];
a[n-1] = temp;
put a loop around the general code to repeat
for n-1 passes
for (pass = n-1; pass >= 0; pass --)
{ max = 0;
for (i = 1; i <= pass; i++)
if (a[max] < a[i])
max = i;
temp = a[max];
a[max] = a[pass];
a[pass] = temp;
}
Multidimensional Array
• Multidimensional arrays with two dimensions
• Called two dimensional or 2-D arrays
• Represent tables of values with rows and columns
• Elements referenced with two subscripts ([x][y])
• In general, an array with m rows and n columns is called an m-
by-n array
• E.g.
• int a[5][4]; // row then column
• twenty elements, numbered from [0][0] to [4][3]
• Multidimensional arrays can have more than two dimensions
Two-Dimensional Array
• A two-dimensional array is a collection of components, all
of the same type, structured in two dimensions, (referred
to as rows and columns)
• Individual components are accessed by a pair of indexes
representing the component’s position in each dimension

DataType ArrayName[ConstIntExpr][ConstIntExpr]...;

201
Processing a 2-d array by rows
finding the total for the first row
for (i = 0; i < 5; i++)
total = total + a[0][i];
finding the total for the second row
for (i = 0; i < 5; i++)
total = total + a[1][i];
Processing a 2-d array by rows

total for ALL elements by adding first row, then second row, etc.

for (i = 0; i < 5; i++)


for (j = 0; j < 4; j++)
total = total + a[i][j];
Processing a 2-d array by columns

total for ALL elements by adding first column, second column, etc.

for (j = 0; j < 4; j++)


for (i = 0; i < 5; i++)
total = total + a[i][j];
Functions in C++
Function - a subprogram that can act on data and return a value
Every C++ program has at least one function, main(), where program
execution begins
A C++ program might contain more than one function.
Functions may interact using function call
Functions in C++ come in two varieties:

user-defined

built-in
 E.g pow(), sqrt(), cin, etc
Declaration of Functions
Functions must be declared before use
The declaration tells the compiler
The name,
Return type,
Parameters of the function
Three ways
Write your prototype into a file, and then use the #include directive to include it
in your program.
Write the prototype into the file in which your function is used.
Define the function before it is called by any other function.
Function Prototypes
The declaration of a function is called its prototype
Is a statement - it ends with a semicolon
It consists of the function's
return type,
 name,
 parameter list
Syntax
return_type function_name (type [parameterName1], type
[ParameterName2] ... );
 E.g. long Area(int, int);
 Or
 long Area(int length, int width);
Function Prototypes
• All functions have a return type – default is int
• If the function doesn’t have a return type void will be used
• void is a reserved word
• The function prototype usually placed at the beginning of the
program
• The definition of the prototype must be given
• Many of the built-in functions have their function prototypes already
written in the header files you include in your program by using
#include
Defining a Function
• The definition tells the compiler how the function works.
• Consists of :
• the function header :
• like the function prototype except that the parameters must be named
• there is no terminating semicolon
• its body
• the task of the function
• Syntax
return_type function_name(parameter declarations)
{
declarations;
statements;
}
Defining a Function
• E.g.
long Area(long l, long w)
{
return l * w;
}
• The return statement without any value is typically used to exit
the function early
• C++ does not allow nested functions
• The definition of one function cannot be included in the body of another
function
• A function definition must agree in return type and parameter list
with its prototype
Defining a Function
• If the function returns a value, it’s definition should end with a
return statement
• The body of the function is always enclosed in braces, even
when it consists of only one statement
• return keyword
• Returns data, and control goes to function’s caller
• If no data to return, use return;
• Function ends when reaches right brace
• Control goes to caller
// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies data types
int square( int ); // function prototype of arguments and return values.
square expects an int, and returns
int main() an int.
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call

cout << endl; Parentheses () cause function to be called.


When done, it returns the result.
return 0; // indicates successful termination

} // end main

// square function definition returns square of an integer


int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
Definition of square. y is a
copy of the argument passed.
} // end function square Returns y * y, or y squared.

1 4 9 16 25 36 49 64 81 100
Program Using a Function
#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit is”<<result<<endl;

double Celsius_to_Fahr(double Celsius)


{
double temp; // Declare variables
temp = (9.0/5.0)*Celsius + 32; // Convert
return temp;
}
Execution of Functions

• Each function has its own name


• When that name is encountered, called function call, the execution
of the program branches to the body of that function – called
function
• When the function returns, execution resumes on the next line of
the calling function
• Functions can also call other functions and can even call
themselves
Scope of identifier
• Refers to where in the program an identifier is
accessible
• Determines how long it is available to your program
and where it can be accessed
• Two kind
• Local identifier - identifiers declared within a function (or
block)
• Global identifier – identifiers declared outside of every
function definition
Local scope
• You can declare variables within the body of the function
• local variables
• When the function returns, the local variables are no longer available
• Variables declared within a block are scoped to that block –
Local to that block
• they can be accessed only within that block and "go out of existence"
when that block ends
• E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
Global Scope
• Variables defined outside of any function have global
scope
• Available from any function in the program,
including main()
• A local variable with the same name as a global
variable hides the global variable - when used within
the function
#include <iostream.h> void myFunction()
void myFunction(); // prototype {
int x = 5, y = 7; // global variables int y = 10;
int main()
cout << "x from myFunction:
{ " << x << "\n";
cout << "x from main: " << x << "\n"; cout << "y from myFunction:
cout << "y from main: " << y << " << y << "\n\n";
"\n\n";
}
myFunction();
cout << "Back from
Output: x from main: 5
myFunction!\n\n";
y from main: 7 x from myFunction: 5
cout << "x from main: " << x <<
y from myFunction: 10
"\n";
Back from myFunction!
cout << "y from main: " << y <<
x from main: 5
"\n";
y from main: 7
return 0;}
Unary Scope Resolution Operator ::
• Using ::, one can access an global variable even if it is
over-shadowed by a local variable of the same name.
• E.g.
#include <iostream.h>
float num=10.8;
int main(){
float num= 9.66;
cout<<the value of num is:<<::num<<endl;
return 0;
}
What is the output of this program
#include <iostream.h>
int main() {
float Length=20;
float Width=10;
float Area = Length * Width;
Cout<<“what do u think about C++”;
cout << "Area = " << Area << " = Length "
<< Length << " * Width " << Width << endl;
return 0;
}

You might also like