Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Computer Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 147

Course title:

Computer programming
➢ Introduction to Computer
⚫ What is Computer?
⚫ Computer System
✓ Basic component / Basic organization of a
computer system.
⚫ Software
✓ System software
✓ Application software
➢ What is Computer?
A computer is a device capable of performing computations and
making logical decisions at speeds millions (even billions) of
times faster than human beings can.

For example, many of today's personal computers can perform a


billion additions per second – more than a human can perform in
a lifetime.

Today's fastest supercomputers can perform trillions of additions


per second!.
Cont'd
Computers process data under the control of sets of instructions
called computer programs. These programs guide the computer
through orderly sets of actions specified by people, called
computer programmers.

A computer consists of various devices referred to as hardware:

√ keyboard, screen, mouse, hard disk, memory, DVDs and


processing units.

The programs that run on a computer are referred to as software.


➢ Computer System
A system is a collection of elements that works together to solve
a specific problem. Regardless of size, every computer needs
other components to produce results.

The components of a computer system are:


√ People
√ Data
√ Procedures
√ Hardware
√ Software
➢ Hardware components of a computer
⚫ The Physical appearance such as Shape, Size, cost, Performance, and
Reliability of the computer have been changing year by year, but the
basic logical Structure has not change .
⚫ There are five unit’s for converting the Input data into usefull information .
Computer elements Purposes
1. Input unit To receive data and instruction in a form that can be
understood by the computer. Keyboard, mouse, …etc.
2. Output Unit To give out information via a suitable device, i.e., a
printer, speaker, a monitor, sound card or used to
control other devices.
3. Processing Unit To carry out calculations and comparisons based on the
given instructions. Processes such as calculating,
sorting, and searching takes place.
4. Memory Unit ▪ To hold data and instructions until needed by the
processor. Storage space in the computer, where data
is to be processed and instructions required for
processing are stored.
5. Storage Unit To store all the data and instructions in the computer
Cont'd
➢ Main Components of a computer
➢ Computer has two main components:
⚫ Hardware Software Hardware
⚫ Software

➢ Generally, software can be categorized as :


⚫ System software

⚫ Application software Application


Software

System
Software
➢ What is software?
➢ A computer is an electronic machine that can process data, but it
needs to be told what to do in the form of a set of instructions.
➢ Software is a set of computer readable codes compiled to enable
computer to carry out specific functions.
➢ It is also designed to enable humans to communicate effectively
with their computer by passing simple instructions/commands
through user interface.
➢ Software allows the hardware to do something useful; without
software, the hardware wouldn't know what it was supposed to do.
➢ Software /programs are stored as files on a storage device such as the
hard disk, DVD, or Memory sticks.
⚫ When they need to run, they are loaded into the computer's memory(RAM).
9
Cont'd
➢ There are two main categories of software :
1. System software
2. Application software
Application
Software

System
Software

➢ Application software is an application program that help users to


solve particular computing problems. It is developed/designed to
help the end-user to perform specific tasks. This type of program performs
real work for end-user.
Examples: word processing, Computer Aided Design, Image
editing software, Medical software, . . ., etc
➢ System software
System software is set of programs that coordinates activities and
functions of the hardware and various other programs

It can provide a platform for running application software.


System software includes the operating system and all the utilities
that enable the computer to function.
The role of Systems Software is act as interface between end-
users, application software and hardware.

11
Cont'd
Operating system
Operating is a set of programs that manages computer hardware
and various resources.
It allows the parts of a computer to work together by performing
tasks like transferring data between memory and disks or sending
output onto a display device.

12
Cont'd
Main activities performed by the operating system include:
 Provide a user interface and handle input/output
 Manage system memory
 Manage programs
 execute and provide services for applications software.
 Provide networking capability
 Control access to system resources
 Manage files
 Manage computer’s resources – resource allocation
 provides a platform to run high-level system software

Note: Many of today’s computer use Microsoft’s windows OS.

13
Cont'd
Utility software
➢ It is a program that performs very specific tasks, usually related to
managing system resources. It is designed to do one or two specific,
but vital tasks.

➢ Some utility programs might be supplied as part of the operating


system, for instance, Disk Compression and others are purchased
separately.
➢ Some common tasks carried out by utility programs are:
⚫ File compression
⚫ File sorting, File renaming, File conversion, File repair, Printing
jobs, etc.
⚫ Disk defragmentation
⚫ Backing up data
⚫ Antivirus checks
Cont'd
➢ Introduction to Programming
⚫ What is programming?
⚫ Programming languages
⚫ Programming language history
⚫ Types of computer languages
⚫ Computer language translators
⚫ Software development life cycle
What is programming?
Programming is a skill that can be acquired by a computer professional
that gives him/her the knowledge of making the computer perform the
required operation or task.
It is the process of creating and developing an executable machine
program which performs a set of instructions. It can be done using a
variety of computer programming language.
➢ Why do you need to learn computer programming?
Computer programming is critical if one wants to know how to make the
computer perform a task. Most users of a computer only use the available
applications on the computer. These applications are produced by computer
programmers. Thus if someone is interested to make such kind of applications,
he/she needs to learn how to talk to the computer, which is learning computer
programming.
What is Programming Language?
➢ Programming Language is a vocabulary and set of grammatical rules
for instructing a computer or computing device to perform specific tasks
Programming language consists of set of characters, symbols, and usage
rules that allow the users to communicate with computers, like wise
natural language.
Generally, it is a set of commands that a computer has been “taught” to
understand.
In every programming Language, there are sets of rules that govern the
symbols used in a programming language. These set of rules determine
how the programmer can make the computer hardware to perform a
specific operation. These sets of rules are called Syntax.
➢ Reading assignment:

I. Programming language history

II. Generation of programming language

III. Programming Language paradigms


Computer Language
➢ Types of Computer languages Machine Language
Assembly Language
1. Machine Language: High Level Programming Language
The programming Language that uses Machine Instructions (binary
instructions) is called machine language.
e.g: To tell the computer to add the numbers 3 and 4, we may write:
00000011 00000100, and the result becomes 00000111.
Limitation:
1) Complex Language: Modification in machine language is difficult task
because any modification in machine language results in series of changes.
2) Machine Dependent.
3) Tedious: Programs are highly difficult to read and modify, since it uses binary
code.
Advantage:
i. High Speed: Program written in machine language takes shorter time in
execution.
ii. Translator Free: No translator(compiler or interpreter) is required.
cont'd
2. Assembly Language:
Writing programs using machine language is very difficult to
read and find errors because it use a sequence of 0s and 1s. To
solve this problem, assembly language was developed.
Assembly languages use symbolic names, called mnemonics, for
operations and storage locations. Such programs must be
converted to machine code to be understood by the computer.
e.g: To tell the computer to add the numbers 3 and 4 using
Assembly language, we may write:
 Move R1,3. Means move 3 to R1 (R1 is register)
 Move R2,4
 ADD R1, R2. Means add the content of R1 and R2 and store
in R1.
cont'd
2. Assembly language:
⚫ A program that converts assembly languages into machine code is
called an assembler.
Limitation:
❖ Machine Dependent.

❖ Less Efficient: A program written in assembly language takes


more execution time compared to machine language.
❖ Translator Required: An extra program assembler is required
to convert onto machine language.
Advantage:
➢ Easier to Maintain: Easy to modify.
➢ Less Error-Prone: Less error is made.
➢ Easy to Understand and Use.
cont'd
3. HLPL - High Level Programming Language:
HLPL use English like statements to write programs.
It uses naturally understandable language. High-level language
instructions closely resemble with human language, . e.g. x=3+7.
IDE's are used for rapid development lik C++, .Net, environment,
Visual Basic and Visual C++.
Each programming language has a unique set of keywords and a
special syntax for organizing program instructions.
HLPL programs must be converted to machine code to be
understood by the computer.
A program that converts HLPL programs into machine code is
called a compiler.
cont'd
3. HLPL - High Level Programming Language:
A compiler is a special program that processes statements written in a
particular programming language to convert machine readable form or “
machine code".
Limitation:
a) Less Efficient: The HLPL are less efficient.
b) Poor Control on Hardware: Programmers do not have to know the
internal architecture of computer.
c) Translator Required: An extra program compiler is
required to convert onto machine language.
Advantages:
i. Easy to Learn & maintain: Require less time to write.
ii. Machine Independent,
iii. Built-in Functions.
iv. Readability.
cont'd
➢ What skills do you need to be a programmer?
For someone to be a programmer, in addition to basic skills in computer, needs to
have the following major skills:

 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 machine understandable set of
instructions showing the step of solving the problem.
• Those set of steps should not be dependent on any programming language or
machine.
Computer Language Translator
⚫ Language Translator:
➢ A translator is a computer program that translates a program
written in a given programming language into a functionally
equivalent program in a different computer language, without
losing the functional or logical structure of the original code.

➢ Types of Language Translator include:


⚫ Assembler
⚫ Compiler
⚫ Interpreter
a) Assembler:
➢ Assembler is a program that translates assembly language
program into executable machine code.
cont'd
b) Compiler:
➢ A compiler is a program that translates a high-level language
program (source code) into a machine language program (object
code) . The machine language program can then be executed any
time it is needed.

➢ Compilers translate entire programs into machine code.


cont'd
C) Interpreter
➢ Interpreter reads each individual instruction in the program, and
translate it into machine language instructions and then immediately
executes them. This process repeats for every instruction in the
program.

➢ Lisp and BASIC are examples of Programming Languages that use


interpreter to translate source code to object code.
♦ It is time consuming.
➢ Program Development Life Cycle
⚫ The method used in solving problems in computer science and/or
information systems is called the software development life cycle.

⚫ The Software development lifecycle (SDLC) is a framework that


describes the activities performed at each stage of a software
development project.
⚫ SDLC is a process that is used by the software industry to design,
develop, and test high-quality software.
⚫ SDLC aims to produce the quality software that meets or exceeds
customer expectations, reaches completion within time and budget.

⚫ In order to get a quality software product, it requires to follows the


detailed plan that describe how to design, develop, maintain, replace
and alter or enhance specific software.
Program Development Life Cycle (Cont’d)
⚫ To be able to get a quality software product or program, we need
to follow the following stages.

1. Requirement Gathering and Analysis

2. Design

3. implementation or Coding

4. Testing

5. Deployment

6. Maintenance

7. Documentation
1. Requirement Gathering and Analysis
⚫ In this phases, all the relevant information is collected from the
customer to develop a product as per their expectation.
⚫ Any ambiguities must be resolved in this phase only.
⚫ Business analyst and Project Manager set up a meeting with the
customer to gather all the information like what the customer wants to
build, who will be the end-user, what is the purpose of the product.
⚫ Before building a product, a core understanding or knowledge of the
product is very important.
⚫ For Example, A customer wants to have an application which involves
money transactions. In this case, the requirement has to be clear like
what kind of transactions will be done, how it will be done, in which
currency it will be done, etc.
1. Requirement Gathering and Analysis (Cont’d)
⚫ Once the requirement gathering is completed, requirement analysis is done to
check the feasibility of the development of a product.
⚫ In case of any ambiguity, a call is set up for further discussion.
⚫ Once the requirement is clearly understood, the Software Requirement
Specification (SRS) document is created.
⚫ This document should be thoroughly understood by the developers and also
should be reviewed by the customer for future reference.
⚫ The requirement analysis specification will contain:
▬ The proposed system or solution, which has been agreed by the client and
developer.
▬ A list of existing tools, new tools, required facilities and people available
for developing the solution.
▬ A schedule for the next stages of the project, including the deliverables for
each stage.
2. System Design
⚫ The design phase comes after a good understanding of customer’s
requirements, this phase defines the elements of a system, the components,
the security level, modules, architecture and the different interfaces and
type of data that goes through the system.
⚫ A general system design can be done with a pen and a piece of paper to
determine how the system will look like and how it will function, and then a
detailed and expanded system design is produced, and it will meet all
functional and technical requirements, logically and physically.

⚫ Some Types of Design


➢ Architectural design - Identify sub-systems
➢ Interface design - Describe sub-system interfaces
➢ Data structure design - Design data structures to hold problem data
➢ Algorithm design - Design algorithms for problem functions.
3. Implementation or Coding
⚫ Implementation/Coding starts when the developer got the Design
document.
⚫ In this phase:
✓ The actual code is written in this phase, and produce the program that
will make up the system.
✓ the system becomes Complete when all code is written and documented,
and compiles without any errors.
✓ the system becomes ready to be deployed and installed in customer’s
premises, ready to be running, live and productive.
✓ implementation may take a long time, it depends on the complexity of
the system and the solution it presents.
✓ training may be required for end users to make sure they know how to
use the system.
⚫ If the design contains hardware, then the implementation phase will
contain configuration and fine-tuning for the hardware to meet certain
requirements and functions.
4. Testing
⚫ Testing starts when the coding is complete and the modules are
released for testing.

⚫ In this phase, the developed software is tested thoroughly and


any defects found are assigned to developers to get them fixed.

⚫ Retesting, regression testing is done until the point at which the


software is as per the customer’s expectation.

⚫ The software testers team refer the software requirement


specification (SRS) document to make sure that the software to
be delivered is as per the customer’s standard or
expectations.
4. Testing (cont’d)
⚫ Program testing involves two steps, namely, debugging, and testing.

✓ Testing: –done by testing team to making sure that the program does what
is intended for. The task of locating and identifying of bugs/errors.
✓ Debugging:- done by development team for finding and removing
errors/bugs from the program.
⚫ Errors in a program are called bug, and process of locating and removing
errors is called debugging.
⚫ When the program is completed and all separate modules have been tested, a
full test of the program is performed.
▬ Any errors in the program will be corrected and the test repeated.

⚫ Types of tests:
▬ Alpha test

▪ Test of the finished application completed internally.

▬ Beta test

▪ Tested externally.
5. Deployment
 Once the product is tested, it is ready to deploy in the production
environment or first UAT (User Acceptance testing) is done depending
on the customer expectation.

 In the case of UAT, a replica of the production environment is created


and the customer along with the developers does the testing.

 If the customer finds the application as expected, then sign off is


provided by the customer to go live.
6. Support/Maintenance
➢ Once the program has been delivered (installed in the user’s machine), it
will be monitored for some time to ensure that program is error-free.

➢ Support/Maintenance includes error fixing, updating, and modification.


➢ There are many reasons why programs must be continuously modified
and maintained
✓ New user needs
✓ Previously undiscovered bugs
✓ Changes in hardware platform
✓ Efficiency improvements
✓ Documenting, commenting, etc.
7. Documentation

⚫ All processes in all stages during the system development must


be documented/written down.

⚫ This documentation is vital for future reference or future


maintenance of the program.
➢ Problem solving methods

⚫ Problem solving
⚫ Algorithm
√ Pseudocode
√ flowchart
➢ Problem Solving
⚫ Problem solving is the process of transforming the description of a
problem into the solution by using our knowledge of the problem
domain and by relying on our ability to select and use appropriate
problem-solving strategies, techniques, and tools.

⚫ In this approach, possible solutions are carefully evaluated & one of


them is chosen for implementation. The situation is carefully
monitored over time to ensure the initial & continued effectiveness of
the solution.

⚫ Problem solving is the act of defining a problem, determining the


cause of the problem; identifying, prioritizing, and selecting
alternatives for a solution, and implementing a solution.
➢ Problem Solving process
Problem Solving process
1. Problem definition:
⚫ In this first step, there is a need to write down what exactly the
problem entails, which helps to identify the real problem that is under
study & needs an immediate solution.

2. Problem analysis:
⚫ To analysis how the problem affects the researcher & his or her
current situation & other people involved in the situation.

⚫ The gravity of the problem & all the factors that are contributing to
the problem are determined
Problem Solving process
3. Generating possible solutions
⚫ Focus must be on identifying & generating all possible solutions for a
problem.

⚫ Each potential idea for solution of a problem must be considered


without discarding it through value judgment.
4. Analyzing the solutions
⚫ Various factors about each of the potential solutions are investigated,
wherein all the positive & negative aspects of each solution are
analyzed.
5. Selecting the best solutions
⚫ An attempt is made to compare the available solutions, & eventually
the best solutions is selected based on the careful judgment.
Problem Solving process
6. Implementing the solutions
⚫ The final step of the problem-solving process is to practically solve
the problem by implementing the selected solutions.
7. Evaluation and revision
⚫ After implementation of the most potential solution, an evaluation is

⚫ made to judge the effectiveness of the solution in resolving the


problem.

⚫ It also helps to redefine the problem & revise the problem solving
process in case the initial solution fails to manage the problem
effectively.
Algorithm
What is an Algorithm?
⚫ The sequence of steps to be performed in order to solve a problem by the
computer is known as an algorithm.
⚫ Algorithm is a finite set of unambiguous steps for solving a particular
problem. It is a step-by-step analysis of the process.
⚫ To make a computer do anything (i.e. solve a problem), you have to write a
program: In a computer program, you have to tell a 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.
⚫ Algorithm has the following attributes:
▬ Input: An algorithm may or may not require input
▬ Output: Each algorithm is expected to produce at least one result
▬ Definiteness: Each instruction must be clear and unambiguous.
▬ Finiteness: It should be terminate after finite number of steps.
Flow of Control Structures
⚫ Though instructions in an algorithm appears in sequence, they may not
execute in that order.
⚫ An instruction that alters the order of an algorithm is called flow of control
structure.

⚫ Flow of control structure in an algorithm:


1. Sequence: In the sequence structure, statements are placed one after the
other and the execution takes place starting from up to down.
2. Branching (Selection): In branch structure, there is a condition and
according to a condition, a decision of either TRUE or FALSE is
performed. In the case of TRUE, one of the two branches is executed; but
in the case of FALSE condition, the other alternative is taken.
3. The Loop or Repetition allows a statement(s) to be executed repeatedly
based on certain loop condition e.g. do…while, while, and for loops.
Advantage of Algorithm
⚫ It uses a definite procedure.

⚫ It is not dependent on any programming language, so it is easy to


understand for anyone even without programming knowledge.

⚫ Every step in an algorithm has its own logical sequence so it is easy to


debug
How to Express Algorithms?
⚫ Algorithms can be expressed in many different notations, including:
1. Natural languages
▪ tend to be too verbose and ambiguous,
▪ too "context-sensitive"- relies on experience of reader
2. formal programming languages
▪ too low level
▪ requires us to deal with complicated syntax of programming language
3. Flowcharts
▪ A graphical tool that diagrammatically depicts/illustrate the steps
and structure of an algorithm or program
4. Pseudo-Code
▪ Natural language constructs modeled to look like statements
available in many programming languages
Steps to develop an Algorithm
❖ Define the problem: State the problem you are trying to solve in
clear and concise terms.

❖ List the inputs (information needed to solve the problem) and


the outputs (what the algorithm will produce as a result)

❖ Describe the steps needed to convert or manipulate the inputs to


produce the outputs.

❖ Test the algorithm: choose data sets and verify that your
algorithm works.
➢ Example 1: Write an algorithm that should read any two integer
numbers from the input and compute the sum of the two numbers.
Solution:
Step-1: Start
Step-2: Define the algorithm as Sum
Step-3: Define any three Variables
step-4: input any two integer numbers
Step-5: Add the two numbers
Step-6: Store the result in the third Variable
Step-7: Display the result
step-8: Stop
➢ Example 2: Write an algorithm that should read any two
numbers from the input and return the greater one.
Solution:
step-1: Start
step-2: Define any two variables num1 and num2
step-3: input any two numbers
step-4: if num1>num2 Then
Display “ num1 is greater” ;
else
Display “ num2 is greater” ;
End if
step-5: Stop
What is Pseudocode?
Pseudocode is a method used to define an algorithm, written in a
form that can easily be converted into real programming
statements. But it cannot be compiled nor executed.

Algorithm vs Pseudocode
Both Algorithm and Pseudocode describe the logical sequence
how to solve a problem

✓ An algorithm is written in a natural language

✓ Pseudocode can be written in HLPL syntax.


Example 1: Develop the pseudocode which will read any integer
number from the user and check whether the number divisible by 4.
Solution:
step 1: Begin
step 2: define variable N as integer type
step 3: Display “Enter any integer N”
step 4: input integer number
step 5: if (N % 4 = = 0)
print “ The number is divisible” ;
else
print “ The number is not divisible” ;
step 6: end
Flowchart
Algorithm can be designed by using flowchart, which is a
graphical way of expressing the steps needed to solve a
problem.

Flowchart is a diagrammatic/graphical representation of an


algorithm or process, showing the steps as boxes of various kinds,
and their order by connecting those with arrows.

This diagrammatic representation can give a step-by-step solution


to a given problem.

Different symbols are used for different states in flowchart, For


example: Input/output and decision making has different symbols
Rules for Developing a Flowchart of an Algorithms

⚫ There are some basic shape and boxes included in the flowchart
so as to explain the steps of the algorithm.

⚫ Knowing how to use them while drawing the flowchart is


crucial . Here are some rules that should be known.

▬ All boxes of the flowchart should be connected with arrow


to show the logical connection between them.

▬ It must start with a start box and end with a terminal box.
Symbols Used In Flowchart
➢ Example 1: Draw the flowchart for an algorithm that should read
any two integer numbers from the input and compute the sum of
the two numbers.
solution:
➢Example 2: Draw the flowchart for an algorithm that should read
any two numbers from the input and return the greater one.
Solution:
Activities:
1) Develop an algorithm which will read any number N from the
keyboard and compute the sum of numbers between 0 and the number
N. And also draw the corresponding flowchart.

2) Draw flowchart to find the sum of first 100 natural numbers.

3) Write an algorithm to find the sum of first 50 even numbers and also
draw the corresponding flowchart.
Individual Assignment:
Instruction: You must show important steps and flows.
1. Develop an algorithm which will read any number N from the
user and print all its divisors, and draw the corresponding
flowchart.

2. Develop an algorithm which will read any natural number N from


the keyboard and compute the factorial N, and draw the
corresponding flowchart. [Where N! = 1*2*3*.........*(N-1)*N].

3. Design a flowchart for an algorithm that will print the English


alphabet from ‘Z’ to ‘A’ , horizontally. Z Y X W …… B A.

4. Design a flowchart for an algorithm that will generate the


following series, as it is. 99 96 93 90 … 21 18 15.
Introduction to C++ Programming
C++ Basics:
• C++ programming language
• Use of C++ language
• Structure of C++ program
• Keywords
• Identifiers
• Inputs-Outputs
• Comments
• Data types
• Variables, & Constants
• Operators
➢ What is C++?
⚫ C++ is a computer programming language developed in 1980 by
Bjarne Stroustrup at the Bell Telephone Laboratories.

⚫ It is Object Oriented Programming (OOP) Language, which follow


OOP concept, like inheritance, encapsulation, abstraction, and
polymorphism.

⚫ C++ can runs on a variety of platforms, such as Windows, Mac


OS, and the various versions of Unix.

⚫ C++ is an extended version of C programming language.

⚫ The programs written in C programming language can also run in


C++ compiler.
Use of C++ Language

➢ C++ is used by programmers to develop computer software,


mainly to design Operating System, and Utilities, Language
Compiler, Database, specific applications, Video games, and so
on, for various computer devices.

➢ It has a relatively clear and mature standard.

➢ Modularity, Reusability, and readability


Structure of C++ program
➢ C++ program contains four sections:
I. Include files

II. Class declaration (optional)

III. Member function definition and/or variables declaration (optional)

IV. Main function program

syntax:
#include<iostream.h> // Preprocessor directive
#include<conio.h>
Class declaration (optional)
Function definition variable (optional)
return_type main( )
{ // used to start the block of code in main( ) function
clrscr( ); //It clears the previous output screen.
Program code will be written here
getch(); //It holds the final output screen until any key is pressed
by user.
Structure of C++ program (cont’d)
➢ Simple C++ Program

Actual execution of a program starts


from here (from main( ) function)
Rules of C++ Language

♦ Programs in C++ are written in block.

♦ Every program should have main( ) function.

♦ Every statement should be ended with semicolon (;)


♦ All letters in reserved words should be in lowercase; C++ is
case sensitive.
♦ All variables must be declared before used in the program.

♦ Programmers can space more than one variables of the same


type by separating the variable names as the comma.

♦ The size of the memory space allocated and types of value for a
variable depends on the data type.
Scope of Variables in C++
⚫ In C++, Scope of a variable refers to the visibility of the
variables.
⚫ i.e. Scope is a region of the program, and variables can be
defined:
1. Local variables:- declared inside a function or a block.
✓ Do not exist outside the block in which they are
declared, i.e. they can not be accessed or used outside
that block.
2. Global variables:- declared outside of all function.
✓ Declared at the top of the program outside all of the
functions or blocks, and can be accessed from any
portion of the program.
Example: Identify the Scope of Variables
Tokens in C++
➢ C++ Program is a collection of Tokens, Comments, and White
Space.
➢ A token is the smallest unit/element of a C++ program that is
meaningful to the compiler. In fact, every unit that makes a
sentence in C++ is a Token.

➢ C++ has six types of Tokens as given below.


Keywords/Reserved words in C++

⚫ Keywords are the reserved identifiers that have special meanings,


but cannot be used as a variable name in a program.

⚫ All keywords are written in lower case.


Identifiers
 Identifier refers to the name given to any program elements
such as:

 Name of functions

 Name of arrays these are created by

 Name of variables programmers

 Name of classes

 Each programming language has its own rules for naming


identifiers.
C++ Rules for identifier
1) The first letter of the identifiers' name must always be
alphabetic or underscore ( _ ) symbol, and followed by any
alphabet character, digits or underscore.

2) Case sensitive. i.e. uppercase and lower case letters are


different.

3) Special character such as *, / , ( , @, +, > … etc are not


allowed for naming a variable/identifiers.

4) Identifiers can be declared anywhere.


Constant / Literals
➢ Constants refer to fixed values that the program may not alter
during its execution. These fixed values are also called literals.

➢ Constants can be of any of the basic data types like an


integer constant, a floating constant, a character constant, or a
string literal.

➢ Some kinds of C++ literals include:

● Integers- constant: 1,2,456,0xffff

● Character-constant: ‘A’, ‘B’

● Floating-constant: 4.67,3.14E-05

● String-constant: "ABC", "TOTAL“


Strings in C++
⚫ A String is one of the most useful data types that stores a sequence of letters or
other characters, such as "Hello" or "May 10th is my birthday!".
Example: string testString;
testString = "This is a string." ;
We can combine these two statements into one line:
string testString = "This is a string." ;
Separators/ Special Symbols
➢ Separators are symbols used to indicate where groups of code
are divided & arranged

➢ C++ separators include:


✓ ( ) parentheses. Methods, precedence in expression.

✓ { } braces . Arrays in it, block of codes, scopes.

✓ ; semicolon.

✓ , comma. Séparâtes multiple identifier, more than one statements.

✓ . Period. Data members, methods.

✓ [ ] Brackets.. Array referencing/dereferencing.


OPERATORS IN C++
➢ An Operator is a symbol that tells the compiler to perform
specific mathematical or logical calculation on operands/variables.

➢ C++ is rich built-in operators.

● Arithmetic Operators

● Relational Operators

● Logical Operators

● Assignment Operators

● Increment/ Decrement Operator

● Scope resolution(::), sizeof( ), Conditional, Bitwise operators

● Shift operator, Comma operator, Misc operator


OPERATORS IN C++
➢ Arithmetic Operators
▪ The operator which performs arithmetic operations include +,
-, *, /, and %.
➢ Unary operators - work on a single operand.
▪ C++ provides two unary operators for which only one
variable is required.
▪ It is used to increment or decrement the value of a single
variable. For example a++; ++b; d--; ++c.
➢ Binary Operators - they work on two operands.
▪ Two operands and one operator is required.

➢ Relational Operators
▪ Relational/comparison operators such as >, <, >=, =<, ==, !=,
… etc are used to compare two operands, values or
expressions to evaluate the relationship.
Example: if(x % 2 != 0) then x is odd
or if(x % 2 = = 0) then x is even
➢ Logical operator

▪ Logical/Boolean operators such as && (AND) || (OR) , and !


(NOT ) are used to perform logical comparisons.
Example: if ((x>y) && (x>=z) ) then x is greatest
if ((n==0) ||(n==1)) then a is binary number
➢ Assignment Operators

▪ Assignment operator such as =, +=, -=,*=, /=, %=, etc are used to
assign/initialize a value to a variable during the program
execution.

Example: c+=b ( means c=c+b), x/= y (means x= x/y)


➢ Increment Operator (++)

▪ This operator is used for increment the value of an operand

Example: if A=20, then ++A= 21, and A++=20


✓ ++A is pre-increment, but A++ is post-increment

➢ Decrement Operators (- -)

▪ This operator is used for decrement the value of an operand

Example: if B=14, then - -B=13 and B- - =14


✓ - - B is pre-decrement, but B- - is post-decrement
➢ Scope resolution operator (::)
▪ This operator is used to differentiate a local variable from the global
variable. Example: int a = 20;
int main() {
Output int a = 10;
Value of local a: 10 cout << "Value of local a: " << a << endl;
Value of global a: 20 cout << "Value of global a: " << ::a ; }
▪ Note: the variable having the same name can have different meaning at
different block.

➢ The sizeof() Operator


 This operator is used for calculating the size of any data item or type.
 It takes a single operand and returns the size of the specified entity in
bytes. The outcome is totally machine dependent.
Example: sizeof(char) = 1 sizeof(float) = 4
sizeof(short int) = 2 sizeof(long int) = 4
sizeof(double) = 8 sizeof(bool) = 1
➢ Conditional operator

⚫ The conditional operator (?: )is called ternary operator as it


requires three operands.

⚫ The syntax of the conditional operator is:

Conditional_ expression ? expression1 : expression2;

⚫ If the value of conditional expression is true, then the expression1


is evaluated, otherwise expression2 is evaluated.
Example: int a = 5, b = 6;
big = (a > b) ? a : b;
 The bigger number from the above conditional expression is the
value of b, which is 6
VARIABLES AND VARIABLE DECLARATION
 A variable is a symbol or a word that represents a reserved place
in the computer’s memory to store variety of values in.
 All variables have three important properties:

➢ Data Type:

♦ A data type is established when the variable is defined.

♦ Data type describes the property of the data and the size of

the reserved memory


➢ Name: is a unique identifier for the reserved memory location
➢ Value: is something which can be stored in the reserved memory location.

General Syntax of variable declaration:


Datatype variable_Name;
Variables must be declared before they are used in a program.

Example: int num ;


Variables in C++
⚫ Variable is the name of memory location allocated by the compiler
depending upon the datatype of the variable. It is a location in
computer memory where a value can be stored.

⚫ Variables must be declared before they are used in a program.


Variables in C++
DATA TYPES IN C++
 In computer programming, information is stored in a computer
memory with different types.
 A data type defines which kind of data will store in variables and
also defines size of memory for data.
 Generally, there are three kinds of data types:

▪ Primitive/Built-in,
▪ Derived, and
▪ User-defined data types.
●Primitive data types: ● Derived data types: ● User defined data
❖ Integer ✓ Array types:
✓ Short int ✓ Pointer ✓ Struct
✓ Long int ✓ Class
❖ Floating types
✓ enum
✓ Float
✓ Double
❖ Char
❖ bool
 Built-in data types:
► char: For characters. occupy 1 byte.
Example: char ch = 'A';
► int: For integers. Occupies (sizes) 2 bytes.
Example: int num = 100;
► Long int: For integers. Occupies (sizes) 4 bytes.
Example: int num = 200000;
► float: For single precision floating point. Occupies (sizes) 4 bytes.
Example: float num = 123.78987;
► double: For double precision floating point. Occupies (sizes) 8 bytes.
Example: double num = 10098.98899;
► bool: For booleans, true or false. Occupy 1 byte
Example: bool b = true;
► const: for fixed value through the program execution.
example: const int day=7;
BUILT IN DATA TYPES
➢ Character data type:

 A keyword char is used to define character data type.

 A character variable occupies 1 byte of memory, which can


hold exactly one character such as ‘b’ or ‘B’.

• Example: To declare a variable of type char:

• Char ch ;

 Suppose we want to store a character value ‘M’ in a char data


type of variable ch, the value should enclosed within a single
quote.

Example: char ch= ‘M’ ;


BUILT IN DATA TYPES
➢ Integer data types:
 The keyword int is used to define integer type.

 An integer variable occupies 2 byte of memory.

 This data type consists of the values ranging from -32768 to


32767. This range is for the small integer. For long integer, the
type long or long int can be used.

Example: int x; x= 300 or long int x; x=25000000;

 The range of long int is too big that is from -2147483648 to


2147483647, which occupies 4 bytes in memory.
 Integers have no decimal part and they can be positive or
negative. Like 12 or -12.
BUILT IN DATA TYPES
➢ Floating point data types:
 The keyword float is used to define a number with fractional part.
Example: float num;
num=3.5;
 A variable with type float occupies 4 bytes of memory.
➢ Constant - is a data type whose value is never changes (fixed
value) and remains the same through the program execution.
➢ Constant must have to be initialized at the time of
creating it, and new values cannot be assigned later to it.
Example: - Area of the circle (π*r2):
const float pi=3.14,
Area=pi*r*r
- Total number of days in a week:
const int day=7;
EXPRESSION
 An expression is a combination of operator and operands
(constants or variables) arranged as per the rules of the language.
 Every expression consists of at least one operand and can have
one or more operators.
 Operands are values or variables, while operators are symbols
that represent particular actions. Example: x + 5 is expression. In
the expression, x and 5 are operands, and + is an operator.
➢ First C++ Program

▪ //write a c++ program that display the string “Hello world,


welcome to Ethiopia”.

Ans:
#include<iostream.h>
void main( )
{
cout<< “Hello world, welcome to Ethiopia”;
}
Output:

Hello world, welcome to Ethiopia


➢ Input/output operator

▪ The symbol ‘<<’ is the output operator, also called insertion


operator, which is used to display the processed data.

▪ The symbol ‘>>’ is the input operator, also called extraction


operator, which is used to accept value from the user.

Exercise:
write a C++ program that add given two numbers and display the
result.
➢ Comment in C++

▪ Comments, in Programming, are explanatory statements that help


anyone who read the source code.

▪ C++ comments start with // for single line

Example: //This is my first C++ program.

▪ C++ comments start with /* and end with */ for multiple lines
Example: /* This is a my first “Hello World” program using C++
programming language */

▪ All characters available inside any comment are ignored by C++


compiler.
➢ How to use Comment more efficiently in C++
Programming?
⚫ Using of Comments in C++ :
1. Comment for User Documentation.
2. Hiding Non-usable Code.
3. Hiding Single Statement.
4. Comment used to explain particular language statement
➢ Semicolons & Blocks in C++

▪ In C++, semicolon is a statement terminator.


▪ Each individual statement must be ended with a semicolon.
▪ A block is a set of logically connected statements that are
surrounded by opening and closing braces.
Example:
{
Cout<< “This is my first program”
{
cout << "Hello World"; Inner Outer
} Block Block
}
CONTROL STRUCTURE
 Control Structures in C++ is a Statement that used to control the
flow of execution in a complex program.

 All programs could be written using three control structures:

1. Sequence structures

2. Selection structures

3. Iteration structures
Sequence structure
■ Sequence structure is the construct where statements are executed
one after the other in the order in which they are written.
Example: Write a program in C++ that will print the phrase shown below:
“Welcome to Bahir Dar University
Engineering Faculty, Department of Fashion Technology”
Ans:
#include<iostream.h>
void main( )
{
cout<< “Welcome to \n”;
cout<< “ Bahir Dar University Engineering Faculty \n”;
cout<< “EiTEX Department of Fashion ”;
} Output
Welcome to
Bahir Dar University Engineering Faculty
EiTEX Department of Fashion
Selection statement
 The selection statements allow you to choose a set of statements
for execution depending on a condition.
 Selection structure includes if…else, else if, nested if, and
switch.
If…else statement is a conditional branching statement used to
execute a set of code when the condition is true, otherwise executes
the code in the "else" part.
Flowchart
Syntax
SELECTION STATEMENT
Example: Write a program in C++ that read any two number from the
keyboard and then display the greater one using if…else statement.
Ans: #include <iostream.h>
void main()
{ int b,c;
cout<<“Enter any two numbers one by one:”;
cin>>b>>c;
if (b>c)
cout << "B is greater than C";
else
cout << "C is greater than B";
}
SELECTION STATEMENT
 else if statement is an extension of the "if…else" conditional
branching statement.
 When the expression in the "if" condition is "false" another "else
if " construct is used to execute a set statements based on an
expression.
Syntax
if(condition_1) flowchart
{ block statement_1; }
else if(condition_2)
{ block statement_2; }
else if(condition_n)
{ block statement_n; }
else
default statement;
SELECTION STATEMENT
 Example: write a program which will ask the user to input the
student’s mark and then find the grade in letter.
Ans:
#include <iostream.h>
int main() {
float mark;
cout<<"Enter student's mark: ";
cin>>mark;
if (mark < 40)
cout<<“Grade = F";
else if (mark < 50)
cout<<“Grade = E";
else if (mark < 60)
cout<<“Grade = D";
SELECTION STATEMENT
else if (mark < 70)
cout<<“ Grade = C";
else if (mark < 85)
cout<<“ Grade = B";
else
cout<<“ Grade = A";
cout<<"\n";
return 0;
}
SELECTION STATEMENT
Nested if…else statement is if…else statement inside another if
statement.
Syntax and flowchart:
if(condition_1) {
if(condition_2)
{ block statement_1; }
else
{ block statement_2; }
}
else
{ block statement_3; }
Block statement_3;
SELECTION STATEMENT
Example: Write the program which will accept three numbers from
the user and return the greatest number among them.
Ans:
#include<iostream.h>
int main() {
int x, y, z;
cout<<"Enter values for x, y, and z\n";
cin >>x>>y>>z;
if(x>=y)
{ {
if(x>=z)
{
cout<<"The greatest number is:"<<x<<endl;
} else
SELECTION STATEMENT
{
cout<<"The greatest number is:"<<z<<endl;
}
}
else if(y>z)
{
cout<<"The greatest number is:”<<y<< endl;
} else
{
cout<<"The greatest number is:”<<z<< endl;
} Output
return 0; Enter values for x, y, and z
7
} 9
8
The greatest number is: 9
SWITCH STRUCTURE
 Switch statement compares the value of an expression against a list
of integers or character constants.

 The lists of constants are listed using the "case" statement along with a
"break" statement to end the execution. If no conditions match then the
code under the default statement will be executed.

 Note: The switch statement has four components: Switch, Case,


Default, and Break.
SWITCH STRUCTURE
Syntax flowchart
Switch (expression)
{
stmt
case constant1: Statements; Case1

break;
Case2 stmt
case constant2: Statements; .
break; .
.
.
Case n stmt
.
case statement n: statements;
default
break;
Default: Statements;
}
SWITCH STRUCTURE
Example: write a C++ program which will ask the user to input the grade
in letter (A,B,C,D, or F) as input and return the string ‘Excellent’, ‘Best
done’, ‘passed’, ‘Poor’, ‘Better try again’, ‘invalid grade’ for the input
‘and any other key respectively using switch statement.
Solution: #include <iostream.h>
int main () {
char grade ; // local variable declaration
cout<<" what is the grade in letter? ";
cin>>grade;
switch(grade)
{
case 'A' : cout << "Excellent!" << endl;
break;
SWITCH STRUCTURE
case 'B' : cout<< “Best done“<<endl;
break;
case 'C' : cout << “Passed" << endl;
break;
case 'D' : cout << “Better try " << endl;
break;
case 'F' : cout << “ Fail, do it again" << endl;
break;
default : cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
GOTO STATEMENT
 The goto statement is used for unconditional branching or
transfer of the program execution to the labeled statement.
Syntax:
GOTO STATEMENT
Example: Write a program in C++ that read any number and check
whether the number is even or odd.
#include <iostream.h>>
int main(){
ineligible:
cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age;
if (age < 18)
goto ineligible;
else
cout<<"You are eligible to vote!";
}
ITERATION STATEMENTS
■ Iteration or loops statements help to accomplish repetitive
execution.
■ There are three loop structures, which are while, do-while
and for loop.
While Loop
 While statement is iteration structure that executes a set of code only
when the condition is true.
 It is also known as "Entry controlled loop" since it is executed only
inside the loop if the condition is satisfied. Start
Syntax:
While (condition)
While loop statement
{
flowchart
Statement1;
Statement 2;
}

Stop
■ The flow diagram indicates that a condition is first evaluated.
■ If the condition is true, the loop body is executed and the condition is
re-evaluated; otherwise it exit.
Example:
#include <iostream.h>
int main()
{
int i=1;
while(i<5)
{
cout<<"Value of variable i is: "<<i<<endl;
i++;
} Output:
Value of variable i is: 1
return 0; Value of variable i is: 2
} Value of variable i is: 3
Value of variable i is: 4

 In the above example the “while" statement iterates starting with the
value of i=1 till i is less than 5 every time increasing the value of i by 1.
Do…While Loop
 The Do…While statement is an iteration statement that executes a set of code
first, then it checks the condition. This statement is also known as "Exit
controlled loop" since the condition is checked only after executing the
loop at least once.
 This statement is similar to while loop except that the test condition occurs at
the end of the loop.
 Therefore, Do …while loop is guaranteed to execute the loop body at least
once before testing the condition. Start
Syntax:
do {
Statement 1;
Statement 2;
} While (test condition);

Stop

Do…while loop statement flowchart


Example:
#include <iostream.h>
int main()
{
int num=2;
do{
cout<<"Value of num is : "<<num<<endl;
num++;
}while(num<=7);
return 0; Output:
} Value of num is : 2
Value of num is : 3
Value of num is : 4
Value of num is : 5
Value of num is : 6

 In the above example the “do…while" statement iterates starting with the
value of i=2 till i is less than 7 every time increasing the value of i by 1.
For loop
 The For Loop Statement is an iteration statement that executes a
set of code (block of statements) repeatedly until a particular
condition is satisfied.
Syntax:
for (initial value; test condition; increment/decrement)
{
Statement;
}

For loop statement flowchart


Example:
#include <iostream.h>
int main()
{
int i;
for(i= 0;i<5;i++)
{
cout << "for loop has looped:" << i << " :times" << endl;
}
return 0; Output:
} for loop has looped: 0 :times
for loop has looped: 1 :times
for loop has looped: 2 :times
for loop has looped: 4 :times
 In the above example the "for" statement iterates starting with the value
of i=0 till i is less than 5 every time increasing the value of i by 1.
Example:
#include <iostream.h>
int main()
{
int i=0 ;
int j=0 ;
for(i= 0;i<5;i++)
{
cout << “alue of j is:" << j++ << endl;
} Output:
return 0; Value of j is: 0
} Value of j is: 1
Value of j is: 2
Value of j is: 3
Value of j is: 4
 In the above example, since the value of "i" is initialized before, the
initialization value of the for loop is left blank. This is another way of declaring
the for loop statement.
EXERCISE
1. Write a C++ program that ask the user to input any integer number and compute the sum
of the series between 1and the number using while, do…while or for loop.

2. Write a C++ program that should find the sum of the number between 1 and 99
using while loop.

3. Write a program in C++ that should read any number from the input and compute
the factorial of that number using for loop.

4. Write a program in C++ that should print English Alphabet from ‘A’ to ‘M’.

ABCDEFGHIJKLNM

5. Write a program that should ask the user to input his/her name and print 10 times

6. Write a program in C++ that print display the result shown below using for, do…while
or while loop.
FUNCTION
➢ In programming, a function is block of code/statements which is
used to perform a particular task.

➢ Each C++ program has at least one function, which is main(),


and can define additional function.
▪ C++ allows programmer to define their own function, called
user-defined function.
▪ A user-defined function groups code to perform a specific task
and that group of codes should have a name(identifier).
▪ Every programming language lets you create blocks of code that,
when called, perform tasks.
▪ When the function is invoked from any part of program, it all
executes the codes defined in the body of function.
Parts of function

parts Explanation
Return type the type of data that the function returns

Function name the actual name of the function


Parameters allow passing arguments to the functions from
the location where it is called from

Function body Contains a collection of statements that define


what the function does.
USER-DEFINED FUNCTIONS
Function prototype/declaration:
➢ A function declaration, called function prototype, is done to tell
the compiler about the existence of the function (about the name,
return type, and parameters of the function).
➢ This statement can be written after #include<iostream.h> and
before the main function or inside the main() function before the
function calling line.
➢ Function prototype should terminate with semicolon.

Function definition:
● A function definition is done to tell the compiler what task the
function will perform.
▬ It provides the actual body of the function.
▬ Function definition consists of the function header and its
body.
● A function prototype and a function definition must agree
EXACTLY on the return type, the name, and the parameters.
FUNCTION CALLING
► A function is called (invoked) by providing the function name,
followed by the parameters being sent enclosed in parentheses.
► To call a function, you simply need to pass the required
parameters along with function name.
► If the function is without parameters, it can be called directly
using its name.
► But for functions with arguments, there are two ways to call a
function:
■ Call by Value:

▬ The call by value method pass the value of the

actual parameters (arguments) into the formal


parameters of the function.
■ Call by Reference

▬ pass the address of the variable as arguments.


USER-DEFINED FUNCTIONS
How user-defined function works in C++ Programming?
#include<iostream.h>

void function_name( ) { // function definition

…………………

…………………

int main ( ) {

………………….

function_name ( ); // Calling function

………………..

}
FUNCTION
 When a program begins running, the system calls
the main() function and then the system starts executing
codes from main() function.

 When control of the program reaches to a called function


inside main ( ) function, it move to the user-defined
function and all codes inside the user-defined function is
executed.

 Then, the program control moves back to the main


function to execute the codes/statements after the called
function line, as shown in the figure above.
CALLING FUNCTION
Example: write a C++ program to add two integer numbers. Create
a function add() to add two integers values.
#include<iostream.h>
add(int, int); //Function prototype (declaration)
int main( ) {
int num1, num2, sum;
cout<<"Enters two numbers to add: ";
cin >> num1 >> num2;
sum = add(num1, num2); // Function call
cout << "Sum = " << sum;
return 0;
}
FUNCTION
// Function definition
int add(int a, int b) {
int add;
add = a + b;
// Return statement
return add;
}
 In C++, function prototype is a declaration of function
without its body to give compiler information about user-
defined function.
 Function prototype in the above example is:

int add(int, int);


 you can also declare function prototype as below:

int add(int a, int b);


FUNCTION
Function Definition
 The function itself is referred as function definition.

e.g: // Function definition


int add(int a, int b)
{
int add;
add = a + b;
return add;
}
Function Call
 To execute the codes of function body, the user-defined
function needs to be invoked(called in side the main( )
function.
e.g: sum = add(num1, num2); // Function call
FUNCTION
Example: Write a function that should ask the user to input
any two numbers, and compute the sum of the two numbers.
Solution:
#include<iostream.h>
int add(int, int); //This is called function prototype.
void main( ) {
int n, m;
cout<<”Enter the numbers\n” ;
cin>>n>>m ;
int sum=add(n, m) ; //This function calling.
cout<<"The sum of the numbers is:"<<sum ;
}
int add (int x, int y) //This is function definition
{
return ( x+y);
}
CONT…
In other way, you can rewrite the function as:
#include<iostream.h>
int add (int x, int y) { //This is function definition.
int temp=x+y;
return (temp) ;
}
void main() {
int n, m;
cout<<”Enter the numbers\n” ;
cin>>n>>m ;
int sum=add(n, m) ; // function calling.
cout<<"The sum of the numbers is:"<<sum ;
}
FUNCTION
Function parameters
 In programming, parameter (argument) refers to the data
which is passed to a function (function definition) while
calling it.
 But the different between parameter and argument is:

 Function parameter is a variable declared in the prototype


or declaration of function.

 Function Argument is the value or expression that passed


to a function call in place of a parameter.

 When a function is called, all of the parameters of the


function are created as variables, and the value/arguments
are copied into the parameters.
CONT…
Example:
#include<iostream.h>
Int add(int, int);
Void main( ) {
…………………
int sum=add(num1,num2); //actual parameters num1 & num2
…………………
}
Int add(int a, int b) { // formal parameter a and b.
………………….
m=a+b;
………………….
}
CONT…
▪ The two variables, num1 and num2 are passed to function during
function call.
▪ These arguments are known as actual arguments or actual
parameters.
▪ The value of num1 and num2 are initialized to variables a and b
respectively.
▪ Notes:
 The numbers of actual arguments/parameters and formal
parameters should be the same.
 The type of first actual argument should match the type of first
formal arguments. Similarly, type of second actual argument
should match the type of second formal argument and so on.
 You may call function a without passing any argument. You
may assign default values to the argument.
 These arguments are known as default arguments.
CONT…
Example:
void mul(int x, int y) // x & y function or formal parameters
{
return(x+y);
}
Calling: mul(4, 9); // 4 & 9 are arguments

 When mul( ) is called with arguments 4 and 9, mul’s


parameter x is created and assigned the value of 4, and
mul’s parameter y is created and assigned the value of 9.
CONT…
Example: Write a function, Area ( ), in C++ that will read the
height and base of a triangle and find the area of the triangle.
Solution:
#include <iostream.h>
void Area (int n1,int n2) // n1 & n2 are function (formal) parameters
{ cout<<"Enter value for 1st & 2nd numbers ";
cin>>n1>>n2;
float A = (n1 * n2) / 2 ;
cout << “The area is of triangle is: " << A;
}
int main ( ) {
int x,y;
Area(x,y ); // x and y are arguments for function Area.
return 0; // x & y also called actual parameters
}
EXERCISE
1. Write a fucntion, Area( ), in C++ that should ask the user to input the radius of the
circle and compute its area.

2. Write a function, sum( ), in C++ that should get the number from the user and calculate
the sum from “0” to number given by the user.

3. Write a function, Sqr_toot( ), in C++ that should get value of a, b, and c from the user
and find the roots of the following quadratic equation.
F=ax2+bx+c

4. Write a function, find( ), in C++ that accept three numbers from the user and Find the
largest, and smallest, and average of the numbers.

5. Write a function, isEven( ), in C++ that should get the number from the user and
determine whether the number is even or not.

6. Develop a program in C++ that has function printTemp() which prints "Cold" on if the
temperature is below 10, "OK" if the temperature is in the range 20 -> 30,"Hot" if the
temperature is above 30.
ARRAYS
➢ Arrays: An array is a collection of data that holds fixed
number of values of same type.

➢ A data structure which allow a common name to be given


to a collection of elements which all have similar type
with in the consecutive memory.

 An Array can be any data type, but it should be the


collection of similar items.

 Each item in an array is termed as ‘element’, but each


element in an array can be accessed individually.
CONT…
▪ The size or number of elements in an array can be varied
according to the user needs.
How to declare an array in C++?
▪ Syntax for array declaration:

dataType arrayName[arraySize];
- array size refers to number of element in the array.
Example: int m [5] ; - ‘int’ is the data type.
- ‘m’ is the array name.
- 5 is number of elements.
How to initialize an array in C++? We can initialize
an array during declaration:
example: int mark[5] = {19, 10, 8, 17, 9};
NOTE: Elements within brackets [ ] in an array must be
a constant value.
CONT…
▪ int a[5] means a[0], a[1], a[2], a[3], a[4] or
Int int int int int
a[0] a[1] a[2] a[3] a[4]

▪ 0, 1, 2, 3, and 4 are called subscript or index, which are


used to define an array element position and also called
Dimension.

▪ Array index in C++ starts from 0 to n-1 if the size of array


is n.

▪ An individual element of an array is identified by its own


unique index (or subscript)
CONT…
Example1: Write an array in C++ that should ask the user
to input his/her name and print the user’s initials.
Ans: #include <iostream.h>
int main() {
char first[20]; // Holds the first name
char last[20]; // Holds the last name
cout << "What is your first name? \n";
cin >> first;
cout << "What is your last name? \n";
cin >> last;
// Print the initials
cout << "Your initials are " << first[0] << " "<< last[0];
return 0;
}
CONT…
Example2: Write a C++ program that will ass the
user to input five numbers and compute the sum of
the numbers using arrays.
#include <iostream.h>
int main() {
int numbers[5], sum = 0;
cout << "Enter 5 numbers: "; .
for (int i = 0; i < 5; ++i)
{
cin >> numbers[i]; // enter 5 numbers
sum += numbers[i]; // Find the sum of five Nos
}
cout << "Sum = " << sum << endl; return 0;
}
CONT…
Write a program that should ask the user to input five random
numbers and return the largest one using array.
Ans: #include<iostream.h>
int main( )
{
int i, n; float arr[100];
cout << "Enter total number of elements(1 to 5): ";
cin >> n;
for(i = 0; i < n; ++i)
{
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}
CONT…
// Loop to store largest number to arr[0]
for(i = 1;i < n; ++i) {
// Change < to > if you want to find the smallest element
if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << "Largest element = " << arr[0];
return 0;
}

You might also like