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

10/10/2023

Lecture-1
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

The Academic Calendar

1
10/10/2023

Text and Reference Books


Text Book
Object Oriented Programming in C++
(Fourth Edition)
Author: Robert Lafore

Reference books
2. Object-Oriented Programming Exercises
with C++, by Haris Tsetsekas
3. Any good book on C++
4. Let Us C (For practice programs only)
By Yashavant Kanetkar

Assessments
• Sessional Assessment (40 Marks)
– Assignment/s
– Quizzes
– Mid Term (20 marks)
• Final Assessment (60 Marks)
– Exam(60 Marks)

2
10/10/2023

Computer
• It is an electronic device
• It Manipulates information
• It has the ability to store, retrieve,
and process data.
• It Converts data into information -
useful to people
• It is controlled by programmed
instructions which tell it what to do.
• It can be used to create or change
documents, play games, browse the
Web, social media access, business,
health care.
5

Basic Functional Units of Computer

3
10/10/2023

Basic Functional Units of Computer cont.


Input Unit:
• Computer accepts encoded information
through input unit. The standard input device
is a keyboard. Whenever a key is pressed,
keyboard controller sends the code to
CPU/Memory.
• Examples
– Mouse
– Joystick
– Tracker ball
– Light pen/Digitizer
– Scanner etc.
Output Unit:
• Computer after computation returns the
computed results, error messages, etc. via
output unit.
• The standard output device is a video monitor,
LCD/TFT monitor.
• Other output devices are printers, plotters etc.
7

Basic Functional Units of Computer cont.


Memory Unit
• Memory unit stores the program Code, data and results of
computations etc.
• Memory unit is classified as:
– Primary /Main Memory
– Secondary /Auxiliary Memory
Primary memory
• It is semiconductor memory that provides access at high speed.
• Run time program instructions and operands are stored in the main
memory.
• Main memory is classified as ROM and RAM.
• ROM holds system programs and firmware routines such as BIOS,
POST, I/O Drivers that are essential to manage the hardware of a
computer.
• RAM is termed as Read/Write memory or user memory that holds
run time program instruction and data. While primary storage is
essential, it is volatile in nature and expensive.
Secondary memories
• It is non volatile in nature.
• It is Secondary is known as a Backup memory or Additional memory
or Auxiliary memory.
• Hard Drive, SSD, Flash, Optical Drive, USD Drive 8

4
10/10/2023

Basic Functional Units of Computer cont.


Arithmetic and Logic Unit (ALU)
• Most computer operations are
executed in ALU of the processor
like addition, subtraction,
division, multiplication, etc.
• Operation is performed in
sequence
– Load the operands into memory
– bring them to the processor
– perform operation in ALU
– store the result back to memory or
retain in processor.

Basic Functional Units of Computer cont.


Control Unit
• It effectively is the nerve center that sends signals to
other units and senses their states.
• Control unit co-ordinates activities of all units by
issuing control signals.
• Control signals issued by control unit govern the
data transfers and then appropriate operations take
place.
• Control unit interprets or decides the
operation/action to be performed.
• The actual timing signals that govern the transfer of
data between input unit, processor, memory and
output unit are generated by the control unit.
• To perform a given task an appropriate program
consisting of a list of instructions is stored in the
memory.
• Individual instructions are brought from the
memory into the processor, which executes the
specified operations. Data to be stored are also
stored in the memory. 10

5
10/10/2023

Generations of Computers
• Generation includes both hardware and software, which
together make up an entire computer system.
• There are totally five computer generations known till date.

11

Generations of Computers cont.


First Generation:
• The computers of first generation used vacuum tubes as the
basic components for memory and circuitry for CPU (Central
Processing Unit).
• These tubes, like electric bulbs, produced a lot of heat and were
prone to frequent fusing of the installations, therefore, were very
expensive and could be afforded only by very large organizations.
• Punched cards, paper tape, and magnetic tape were used as
input and output devices.
• The computers in this generation used machine code as
programming language.
• Unreliable
• Slow input and output devices
• Huge size
• Non-portable
• Consumed lot of electricity
• Some computers of this generation were:
• ENIAC
• EDVAC
• UNIVAC
• IBM-701
• IBM-650 12

6
10/10/2023

Generations of Computers cont.


Second Generation

• The main features of second generation are:


• Use of transistors
• Reliable in comparison to first generation computers
• smaller size as compared to first generation computers
• Generated less heat as compared to first generation computers
• Consumed less electricity as compared to first generation
computers
• Faster than first generation computers
• costly
• Supported machine and assembly languages
• Some computers of this generation were:
• IBM 1620
• IBM 7094
• CDC 1604
• CDC 3600
• UNIVAC 1108

13

Generations of Computers cont.


Third Generation
• The computers of third generation used integrated circuits (IC's)
in place of transistors.
• A single IC has many transistors, resistors and capacitors along
with the associated circuitry.
• In this generation remote processing, time-sharing, multi-
programming operating system were used. High-level languages
(FORTRAN-II TO IV, COBOL, PASCAL PL/1, BASIC, ALGOL-68 etc.)
were used during this generation.
• More reliable in comparison to previous two generations
• Smaller size
• Generated less heat
• Faster
• Consumed lesser electricity
• Supported high-level language
• Some computers of this generation were:
• IBM-360 series
• Honeywell-6000 series
• PDP(Personal Data Processor)
• IBM-370/168
• TDC-316
14

7
10/10/2023

Generations of Computers cont.


Fourth Generation
• The computers of fourth generation used Very Large Scale Integrated
(VLSI) circuits.
• Associated circuits on a single chip made it possible to have
microcomputers of fourth generation.
• it gave rise to personal computer (PC) revolution. In this generation time
sharing, real time, networks, distributed operating system were used.
• All the high-level languages like C, C++, DBASE etc., were used in this
generation
• The main features of fourth generation are:
• Very cheap
• Portable and reliable
• Very small size
• Concept of internet was introduced
• Great developments in the fields of networks
• Some computers of this generation were:
• DEC 10
• STAR 1000
• PDP 11
• CRAY-1(Super Computer)
• CRAY-X-MP(Super Computer)
15

Generations of Computers cont.


Fifth Generation
• VLSI technology became ULSI (Ultra Large Scale Integration)
technology
• Resulted in the production of microprocessor chips having ten
million electronic components.
• AI is an emerging branch in computer science, which interprets
means and method of making computers think like human beings.
• All the high-level languages like C and C++, Java, .Net etc., are
used in this generation.
• The main features of fifth generation are:
– Development of true artificial intelligence
– Development of Natural language processing
– Advancement in Parallel Processing
– More user friendly interfaces with multimedia features
– Some computer types of this generation are:
– Desktop
– Laptop
– NoteBook
– UltraBook
– ChromeBook

16

8
10/10/2023

Classification of Computers
• Supercomputers.
• Mainframe computers
• Minicomputers
• Personal computers (PCs) or microcomputers

17

Classification of Computers cont.


Supercomputers
• a powerful computer that can process large amounts of data and
do a great amount of computation very quickly.
• Supercomputers are used for areas related to:
• Science
• Engineering
• Education
• Defence
• Aerospace
• Supercomputers are useful for applications involving very large
databases or that require a great amount of computation.
• Supercomputers are used for complex tasks, such as:
• Weather forecasting
• Climate research
• Scientific simulation
• Oil and gas exploration
• Quantum mechanics
• Cryptanalysis
18

9
10/10/2023

Classification of Computers cont.


Mainframe computers
a high-performance computer used for large information
processing jobs.
Mainframe computers are primarily used in :
Institutions
Research
Academics
Health care
Libraries
Large businesses
Financial institutions
Stock brokerage firms
Insurance agencies
Mainframe computers are useful for tasks related to:
Census taking
Industry and consumer statistics
Enterprise resource planning
Transaction processing
e-business and e-commerce 19

Classification of Computers cont.


Minicomputers
• This term is not much used now a
days.
• It is between a mainframe and a
microcomputer.
• minicomputers are often referred to
as small or midsize servers (that
provides information to other
computers).
• a mid-range computer that is
intermediate in size, power, speed,
storage capacity, etc.,
• Minicomputers are used by small
organizations.

20

10
10/10/2023

Classification of Computers cont.


Personal computers (PCs) or
microcomputers
• Microcomputer is now primarily
used to mean a Personal computer
• It is designed for use by a single
user at a time.
• A PC or microcomputer uses a
single chip (microprocessor) for its
central processing unit (CPU).
• it can refer to any kind of small
computer, such as
– desktop computer
– laptop computer
– Tablet
– Smartphone
– Personal digital assistant(PDA)
– wearable.
21

THE END

22

11
10/12/2023

Lecture-2&3
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

Classification of Software Systems


• Software is a code or a set of instructions that tells a
computer or hardware how to operate.
• Software is usually generic, but it can also be custom-
built.
• Generic software is open to the market, and the
programmer designs its specifications.
• They are mainly designed for a broad customer
market.
• Customized software is software whose specifications
are designed according to a particular firm or
organization.
• It is not an operator at all.
• They are mainly designed for specific business
purposes.
• Software is mainly classified into seven categories –
System software, Application software,
Engineering/scientific software, embedded software,
Product line software, Web applications, and Artificial
intelligence software.

1
10/12/2023

Classification of Software Systems


cont.
Software is mainly classified into
seven categories
1. System software
2. Application software
3. Engineering/scientific
software
4. embedded software
5. Product line software
6. Web applications
7. Artificial intelligence software

Classification of Software Systems


cont.
1. System Software
• It directly interacts with computer hardware.
• It is primarily concerned with the efficient
management of the computer system.
• It is machine dependent.
• The system software is further classified into
three categories
– The operating system, which acts as an
interface between the User and the hardware
and provides different services to users.
– system support software which manages the
hardware more efficiently.
– System development software which supports
a programming development environment for
the User.

2
10/12/2023

Classification of Software Systems


cont.
2. Application Software
• The software is designed to solve user
problems according to their requirements.
• Application software can be generic or
customized.
• application software is classified into two
categories
– general-purpose software that users
utilize for a wide range of tasks and
provides numerous features.
– special-purpose software, specifically
designed for a particular purpose (User’s
programs)

Classification of Software Systems


cont.
3. Engineering/Scientific Software
• It deals with processing requirements in a specific
application.
• Users utilize this software in mechanical, electrical,
drafting, engineering, and analysis.
• They run on mainframes, general-purpose
workstations, and PCs (Personal computers).
• These software are used for
– Drawing
– Modeling
– Drafting
– load calculations
– analyzing engineering and statistical data for
interpretation and decision-making.
• For example, CAD (Computer Aided Design), CAM
(Computer Aided Manufacturing), and CAE
6
(Computer Aided Engineering).

3
10/12/2023

Classification of Software Systems


cont.
4. Embedded Software
• Developers embed this software into hardware as a part of larger systems to
control their various functions.
• The systems’ ROM (Read Only Memory) embeds this type of software.
• For example, Keypad control software embedded in a microwave oven or washing
machine where there is a need to take input, analyze and decide and take action,
which allows the product to perform in the desired manner

Classification of Software Systems cont.


5. Product Line Software
• It refers to software engineering methods, tools, and techniques for
creating a collection of similar software systems from a shared set
of software assets using a standard means of production.
• It is a set of software products that share standard features but
differ from each other in some way.
• For example, a specific customer or embedded software (Word
document, spreadsheet, computer graphics, personal and business
applications) may develop them.

4
10/12/2023

Classification of Software Systems cont.

6. Web Applications
• Users access it as an application via web browsers over a network such as the Internet or an
intranet.
• It is also a computer software application that developers code in a browser support language
and that relies on a common web browser to render the application executable.
• The first generation of web applications allows the business to post the information publicly.
• Anyone with a web browser and internet access can see this information.

Classification of Software Systems cont.


7. Artificial Intelligence Software
• This software uses non-numerical
algorithms that use the data generated in
the system to solve complex problems
that are not amenable to problem-solving
procedures and require specific Analysis
and interpretation of the problem to
solve it.
• For example,
– Artificial neural networks
– Robotics
– expert systems
– computer games.
• All this software can run either in real-
time mode or offline mode.
• Users can share these software programs
free of charge through storage.

10

5
10/12/2023

Software Development Process


• Software development is the process to build computer
programs.
• The process, also known as the Software Development Life
Cycle (SDLC).
• This process includes several phases that provide a method
for building products that meet technical specifications and
user requirements.
• It offers a defined structure for development teams to
follow in the design, creation and maintenance of high-
quality software.
• The aim of the IT software development process is to build
effective products within a defined budget and timeline.

11

Steps of Software Development


Process
1. Analysis
It involves understanding the problem which the software is intended to solve,
i.e., the requirements in context, with validation as the means to check that
understanding.
2. Design
It involves describing, conceptually, a software solution that meets the
requirements of the problem.
3. Implementation
It involves realizing such a solution in software.
4. Testing
It involves making sure that the solution has certain inherent qualities, with
verification as a means to check its adequacy with respect to the specified
requirements and validation as a means to check that the solution does address
the problem.
5. Deployment
It involves making the developed solution available in its context of operation and
use.

12

6
10/12/2023

Steps of Software Development


Process

13

The Number System


• Number systems are simply ways to
count things.
• We use base 10 system , We count
1,2,3,4,5,6,7,8,9, and then put a 0 in the
first column.
For example
1,357,896 = 1 x one million + 3 x one hundred thousand
+ 5 x ten thousand + 7 x one thousand + 8 x one hundred
+ 9 x ten + 6 x one.

• It is not used in Computers, because digital electronics


use a binary number system where the base (or radix) is 2
14

7
10/12/2023

The Computer Number System


• Computers uses binary number system because digital electronics use
a binary number system where the base (or radix) is 2
• each binary digit is called a BIT

• Computer memory is measured in terms of how many bits it can store.


Here is a chart for memory capacity conversion.

15

Number Systems used in Computer


• binary
• octal
• hexadecimal

16

8
10/12/2023

Number Systems used in Computer

Binary Number System


In binary number system:
• digits (symbols) allowed: 0, 1
• base (radix): 2
• each binary digit is called a BIT
• the order of the digits is
significant
• numbering of the digits
• MSB LSB
• n-1 0
where n is the number of digits in
the number
MSB stands for most significant bit
LSB stands for least significant bit
17

Number Systems used in Computer

Binary Number System


• Binary to decimal Conversion
• 1011012 =45
• 100112 =???
• 110002 =???
• 1010102 = ???

18

9
10/12/2023

Number Systems used in Computer

Binary Number System


• Binary fractions to decimal Conversion
• ( 1100.0101 )2 = (?? )10

• (0.1010000 )2 = ( ?? )10

19

Number Systems used in Computer

Binary Number System


• Decimal to binary Conversion
• 14= ( 1110 )2

• Try these;
• 99 = ( ?? )2
• 185= ( ?? )2

20

10
10/12/2023

Number Systems used in Computer

Binary Number System


• Decimal fractions to binary Conversion
• (0.3125)10 =

• (14.25)10= ( ?? )2

0.25 X2 =0.5 0
0.5 X 2 =1.0 1
0 X 0= 0 0

(14.25)10= ( 1110.0100)2

• Try these
• ( 99.15)10 = ( ?? )2
• (1990.86)10 = ( ?? )2 21

Binary to Decimal Examples

22

11
10/12/2023

THE END

23

12
10/20/2023

Lecture-4&5
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

Number Systems used in Computer

Octal Number System


Octal to Decimal Conversion
“Octo” means 8 (Latin word)
digits (symbols) allowed: 0 1 2 3 4 5 6 7
base (radix): 8

(37)8 = (31)10

(37246)8 = (16038)10

1
10/20/2023

Number Systems used in Computer

Octal Number System

Number Systems used in Computer

Octal Number System


Decimal to Octal Conversion

(33)10 = (041)8 or (41)8

(973)10 = (1715)8

2
10/20/2023

Number Systems used in Computer

Octal Number System


Binary to Octal Conversion
Every one octal digit corresponds to 3 binary digits

=1204758
100 010 111 (binary)
Try these 4 2 7 (octal)

10 101 110 (binary)


?? 2 5 6 (octal)

00000101110000002= ???

Number Systems used in Computer

Octal Number System


Octal to Binary Conversion

(120475 )8 = (001010000100111101 )2

5 0 1
101 000 001

3
10/20/2023

Number Systems used in Computer

Hexadecimal Number System


In Hexadecimal number system:
digits (symbols) allowed: 0 1 2 3 4 5 6 7 8 9 A B
CDEF
base (radix): 16
Decimal to Hexadecimal Conversion

(1973)10 = (7B5)16

Number Systems used in Computer

Hexadecimal Number System


In Hexadecimal number system:
digits (symbols) allowed: 0 1 2 3 4 5 6 7
89 ABCDEF
base (radix): 16

4
10/20/2023

Number Systems used in Computer

Hexadecimal Number System


Binary to Hexadecimal Conversion

Number Systems used in Computer

Hexadecimal Number System


Hexadecimal to binary Conversion
(9AF)16 = ( ?? )2

10

5
10/20/2023

Programming Languages

11

Programming Languages
• Computer programs are instructions which tell the computer what
to do.
• Programs are written in a language which computer can use.
• There are hundreds of programming languages, and they were
developed to make the programming process easier for people.
• All programs are converted into a language which computer can
understand.

12

6
10/20/2023

Name Some programming Languages ?

13

Machine Language
• Machine Language is computers’s native
language.
• It is a set of built-in primitive instructions.
• These instructions are in the form of
binary code.
• For example, to add two numbers, we
have to write an instruction in binary
code, like this:
• For example: 1101101010011010
• Programming in machine language is a
tedious process.
• Programming in machine language are
very difficult to read and modify.

14

7
10/20/2023

Low Level Language


• Low level language are an alternative to machine languages.
• They use a short descriptive word, known as mnemonic, to represent each of
the machine language instructions.
• Assembly language is an example of low level language
• For example, the mnemonic add typically means to add numbers and sub
means to subtract numbers.
• To add the numbers 2 and 3 and get the result, you might write an instruction
in assembly code like this: add 2, 3, result
• The computer cannot understand assembly language, another program—
called an assembler—is used to translate assembly-language programs into
machine code

15

High-Level Language
• High-level languages are English-like
and easy to learn and use.
• A high-level languages are platform-
independent.
• we can write a program in a high-
level language and run it in different
types of machines.
• The instructions in a high-level
programming language are called
statements.
• Example to compute area of a circle
with a radius of 5:
• area = 5 * 5 * 3.1415

16

8
10/20/2023

Popular High Level Languages

17

Programming Concept Evolution


1. Unstructured
2. Procedural
3. Object-Oriented

18

9
10/20/2023

Programming Concept Evolution cont.


1-Unstructured
• It is a type of programming which
generally executes in sequential order.
• These programs do not jump from any
line of code.
• In this each line gets executed
sequentially
• Such programs cannot be used for
medium and complex projects.
• Instead, they can be used for small
and easier projects.

19

Programming Concept Evolution cont.


2-Procedural
• The main program coordinates calls to
procedures and hands over appropriate data
as parameters.
• In this, programmers are allowed to code a
program simply by dividing the program into
modules or smaller units.
• Such programs can be used for small and
medium-scale projects and also for complex
projects.
• Facilities to
– Pass arguments to functions
– Return values from functions
C, Pascal, Basic, FORTRAN, and similar
languages are procedural languages.

20

10
10/20/2023

Programming Concept Evolution cont.


2- Object Oriented
• An object is an encapsulation of both functions and
data
• Objects of the program interact by sending messages to
each other
• Objects are an Abstraction
– represent real world entities
– Classes are data types that define shared common
properties or attributes
– Objects are instances of a class
• Objects have State
– have a value at a particular time
• Objects have Operations
– associated set of operations called methods that
describe how to carry out operations
• Objects have Messages
– request an object to carry out one of its operations by
sending it a message
– messages are the means by which we exchange data 21
between objects

Example Object Oriented Code


class Rectangle int area()
{ {
private: return width*length;
int width, length; }
public: };
Rectangle(int w, int l)
{
width = w; main()
length = l; {
} Rectangle rect(3, 5);
cout << rect.area()<<endl;
}
22

11
10/20/2023

Characteristics of Object Oriented Languages

The major elements of object-oriented


languages are;
Objects
Classes
Inheritance
Reusability

23

Characteristics of Object Oriented Languages cont.


Objects:
Objects are reusable self-contained programming modules with data and
functions.
Classes
Classes are blue-print for objects with common properties, attributes,
operations and behaviors.

24

12
10/20/2023

Characteristics of Object Oriented Languages cont.


Inheritance:
The capability of a class to derive properties and
characteristics from another class is called
Inheritance.
Inheritance is a feature or a process in which, new
classes are created from the existing classes.
The new class created is called “derived class” or
“child class” and the existing class is known as the
“base class” or “parent class”.
The derived class now is said to be inherited from
the base class.
When we say derived class inherits the base class, it
means, the derived class inherits all the properties
of the base class, without changing the properties
of base class and may add new features to its own.
These new features in the derived class will not
affect the base class.
The derived class is the specialized class for the
base class.

25

Characteristics of Object Oriented Languages cont.


Reusability:
Once a class has been written, created, and debugged, it can be
distributed to other
programmers for use in their own programs. This is called reusability.
It is similar to the way a library of functions in a procedural language can
be incorporated into different
programs.
the concept of inheritance provides an important extension to the idea of
reusability.
A programmer can take an existing class and, without modifying it, add
additional
features and capabilities to it.
This is done by deriving a new class from the existing one.
The new class will inherit the capabilities of the old one, but is free to add
new features of its own.

26

13
10/20/2023

THE END

27

14
10/20/2023

Lecture-6
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

C++ Programming
• C++ is derived from the C language.
• C++ is a superset of C
• every correct statement in C is also a
correct statement in C++, although
the reverse is not true.
• It Supports Data Abstraction
• It Supports OOP
• greatly influenced development of C#
and Java
• applications: systems software,
application software, device drivers,
embedded software, high-
performance server and client
applications, entertainment software
such as video games, native code for
Android applications

1
10/20/2023

Applications of C++

C++ Libraries
• C++ class libraries are modular components of
reusable code.
• Using class libraries, we can integrate blocks of
code that have been previously built and tested.
• C++ library consists of one or more header files
and an object library.
• The header files provide class and other
definitions needed to access the library functions.
• The object library provides compiled functions
and data that are linked with your program to
produce an executable program.
4

2
10/20/2023

C++ Libraries cont.

• The C++ Standard Library can be


categorized into two parts

• The Standard Function Library − This library


consists of general-purpose, stand-alone
functions that are not part of any class. The
function library is inherited from C.

• The Object Oriented Class Library − This is a


collection of classes and associated
functions.
5

The Standard Function Library


• The standard function library is divided into the
following categories −
– I/O
– String and character handling
– Mathematical
– Time, date, and localization
– Dynamic allocation
– Miscellaneous
– Wide-character functions

3
10/20/2023

The Object Oriented Class Library


• Standard C++ Object Oriented Library defines an extensive set of classes that
provide support for a number of common activities, including I/O, strings, and
numeric processing. This library includes the following −

– The Standard C++ I/O Classes


– The String Class
– The Numeric Classes
– The Standard Template Library (STL) Container Classes
• The STL Algorithms
• The STL Function Objects
• The STL Iterators
• The STL Allocators
– The Localization library
– Exception Handling Classes
– Miscellaneous Support Library
7

Types of codes in C-Language


1. Source Code
2. Object code
3. Executable code

4
10/20/2023

Source code
• Source code is written by programmer by
using any High Level Language or
Intermediate language which is human-
readable.
• source code is a set of instructions or
commands or statements which is written
by a programmer by using a computer
programming language like C, C++, Java,
Python, Assembly language etc.
• Source code is easy to read and modify.
• Source code contains comments that
programmer puts for better understanding.
• Computer can not directly understand
source code
9

Object Code
• Source code is provided to language translator which converts it into
machine understandable code which is called machine code or object
code.
• the compiler converts the source program into an object program.
• object code is a program or a file that is created after compiling the source
code
• It contains the instructions for the machine to perform. These instructions
are in the form of binary digits.

10

5
10/20/2023

Executable code
• The machine understands thd object code and the
computer execute this code.
• Executable code is a file or a program that indicates
tasks according to encoded instructions.
• The CPU can directly execute an executable file to
defined tasks.

11

12

6
10/20/2023

Compiling and linking


• Compilation is a three step process to transform the source code into executable code. These three
steps are: Preprocessing, compiling and linking.
• Preprocessing - Processes directives (commands that begin with a # character) which can modify
the source code before it is compiled.
• Compiling - The modified source code is compiled into binary object code. This code is not yet
executable.
• Linking - The object code is combined with required supporting code to make an executable
program. This step typically involves adding in any libraries that are required.

13

Preprocessor Directives
• C++ source code is pre-processed before it is compiled into object code .
• A preprocessor directive, which begins with a # sign (such as #include, #define), tells the preprocessor to perform
a certain action (such as including a header file, or performing text replacement), before compiling the source
code into object code.
• Preprocessor directives are not programming statements, and therefore should NOT be terminated with a semi-
colon.
• #include <iostream> // To include the IO library header
• #include <cmath> // To include the Math library header
• #define PI 3.14159265 // To substitute the term PI with 3.14159265 in this file
• // DO NOT terminate preprocessor directive with a semi-colon
• In almost all of the C++ programs, we use #include <iostream> to include the input/output stream library header
into our program, so as to use the IO library function to carry out input/output operations (such as cin and
cout).

14

7
10/20/2023

Complete Compilation Process

15

Structure of a C Program
A C-Language program basically consists of the following parts
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Example

Output
#include <iostream>
int main( )
{ This is my first program
cout << “this is my first program “;
return (0);
}

8
10/20/2023

A First ProgramHeader File:In almost all of the C++ programs, we


use #include <iostream> to include the input/output
stream library header into our program, so as to use
the IO library function to carry out input/output
#include <iostream> operations (such as cin and cout).
int main( ) On startup, control always goes to main(). If there is no
{ function called main() in program, an error
cout << “this is my first program “; will be reported when you run the program.
return (0); The program may consist of many functions, classes,
} and other program elements.
main() calls member functions in various objects to
carry out the program’s real work. The main() function
may also contain calls to other standalone
functions.
The last statement in the cout means character output,
open and close braces function body is return 0;. cout is in the c++ header iostream
mark the beginning This tells main() to return << is called insertion operator
and end the value 0 to cout is an object and it is used along
whoever called it, in this with the insertion operator << in order
case the operating system to display a stream of characters.
or compiler.

THE END

18

9
Lecture-7,8 & 9
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

1
Structure of a C Program
A C-Language program basically consists of the following parts
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Example

Output
#include <iostream>
int main( )
{ This is my first program
cout << “this is my first program “;
return (0);
}
A First Program Header File:In almost all of the C++ programs, we
use #include <iostream> to include the input/output
stream library header into our program, so as to use
the IO library function to carry out input/output
#include <iostream> operations (such as cin and cout).
int main( ) On startup, control always goes to main(). If there is no
{ function called main() in program, an error
cout << “this is my first program “; will be reported when you run the program.
return (0); The program may consist of many functions, classes,
} and other program elements.
main() calls member functions in various objects to
carry out the program’s real work. The main() function
may also contain calls to other standalone
functions.
The last statement in the cout means character output,
open and close braces function body is return 0;. cout is in the c++ header iostream
mark the beginning This tells main() to return << is called insertion operator
and end the value 0 to cout is an object and it is used along
whoever called it, in this with the insertion operator << in order
case the operating system to display a stream of characters.
or compiler.
But a Complete Program

#include <iostream>
using namespace std;
int main( )
{
cout << “this is my first program “;
cout << “It is a simple program”;
cout<< “I will make advance programs in future”;
return (0);
}
The header File
• The first line of the program is #include <iostream>
• It is not part of a function body and doesn’t end with a
semicolon.
• it starts with a number sign (#) which is called a preprocessor
directive.
• A preprocessor directive is an instruction to the compiler.
• A part of the compiler called the preprocessor deals with these
directives before it begins the real compilation process.
• The preprocessor directive #include tells the compiler to insert another file into your source file.
• The type of file usually included by #include is called a header file.
• The preprocessor directive #include tells the compiler to add the source file IOSTREAM to the
source code file before compiling.
• IOSTREAM is a header file concerned with basic input/output operations, and contains
declarations that are needed by the cout identifier and the << operator.
• Without these declarations, the compiler won’t recognize cout and will think << is being used
• incorrectly.
• There are many such header files in include directory.

5
using namespace std;
• Namespace is a sort of directory in which identifiers
are defined.
• A namespace is a part of the program in which certain
names are recognized; outside of the namespace
they’re unknown.
• Using namespace std; we are telling the compiler to
look for cout in the std namespace, in which many
standard C++ identifiers are defined.
• A C++ program can be divided into different
namespaces.
• with each concerned statement in our program
• A clever alternative is to add (using namespace std;)
above int main() instruction
• This line tells the compiler that it should look in the std
namespace for any identifier we haven’t defined. If we
do this, we can omit the std:: prefix when writing cout.
This is the recommended practice.
• If we do not type (using namespace std;) in the
beginning of a program then whenever we want to
access an identifier defined in a namespace, we tell
the compiler to look for It in that namespace using the
scope resolution operator (::)

6
main()
• When we run the program the first statement that is
executed at the beginning of a function called main().
• Other than the function main a program may consist
of many functions, classes, and other program
elements.
• But on startup, control always goes to main().
• If there is no function called main() in your program, an
error will be reported when you run the program.
• main() calls member functions in various objects to
carry out the program’s real work.
• The main() function may also contain calls to other
standalone functions.
7
return 0;
• The return value of 0 indicates
normal termination
• non-zero (typically 1) indicates
abnormal termination.
• If C++ compiler will automatically
insert a "return 0;" at the end of the
the main() function, thus, it
statement can be omitted.
• Instead of using numeric value of
zero and non-zero, you can also use
EXIT_SUCCESS or EXIT_FAILURE,
which is defined in the cstdlib header
(i.e., you need to "#include
<cstdlib>".

8
Adding Comments
• Comments are used to document and explain your
codes and program logic.
• Comments are not programming statements and
are ignored by the compiler, but they are VERY
IMPORTANT for providing documentation and
explanation for others to understand your program
(and also for yourself few days later).

• There are two kinds of comments in C/C++:

• Multi-line Comment: begins with a /* and ends


with a */ and can span several lines.
• single-line Comment: begins with // and lasts till
the end of the current line.
• You should use comments liberally to explain and
document your codes.
• During program development, instead of deleting a
chunk of statements permanently, you could
comment-out these statements so that you could
get them back later, if needed. 9
cout; object

• it is used to display/print the output


• an insertion operator (<<) is used with it.
• cout stands for character out i.e. we can print
one or more characters on the screen
• this function comes from header file
iostream.h

10
Examples of cout object
// printing a statement using cout
#include <iostream> output
using namespace std;
int main()
{ this is my first program
cout<<“this is my first program “;
return 0;
}
// printing a constant using cout
#include <iostream>
using namespace std; output
int main()
{ the value of a is = 2
int a=2; the value of b is = 3.24
float b=3.24; the value of c =p
char c=‘p’;
cout<< “the value of a is = ”<< a;
cout<< “\nthe value of b is = “<< b;
cout<<“\nthe value of c is =“<<c;
return 0;
11
}
Escape sequence
• These special characters are used
in cout statement to obtain the
result printed in our desired form
• Escape sequences can be used as
separate characters or embedded
in string constants
• Examples:

12
The endl Manipulator
• endl is a manipulator.
• manipulators are instructions to the output
stream that modify the output in various ways.
• this causes a linefeed to be inserted into the
stream, so that subsequent text is displayed on
the next line.
• They are used with insertion operators (<<).
• it has the same effect as sending the ‘\n’
character, but is somewhat clearer.
• in most cases endl and ‘\n’) are equivalent.

13
Examples \n and endl
output

the value of a is = 2
the value of b is = 3.24
the value of c =p

// printing a constant using cout


#include <iostream>
using namespace std;
int main()
{
int a=2;
float b=3.24;
char c=‘p’;
cout<< “the value of a is = ” << a << endl
<< “the value of b is = “ << b <<endl
<< “the value of c is = “ << c << endl ;
return 0;
} 14
The setw Manipulator
• setw is a manipulator
• it is used with insertion operators (<<)
• it changes the field width of output.
• the setw manipulator causes the number (or
string) that follows it in the stream to be
printed within a field n characters wide, where
n is the argument to setw(n).
• for using setw we must include the header file
#include <iomanip>
15
The setw Manipulator
// printing a constant using printf();
#include <iostream>
#include <iomanip>
output
using namespace std;
int main()
{

int num1 = 10;


float num2 = 9.23;
cout << setw(2) << num1<<endl
<< setw(5) << num1 <<endl
<< setw(10) << num1<<endl
<< setw(8) << num2 <<endl
<< setw(12) << num2 <<endl;
return 0;
}

16
cin object
cin object is used to accept the input from
keyboard.
It is associated with the standard C input stream
stdin.
The extraction operator(>>) is used along with
the object cin for reading inputs.

17
Cin object
// taking inputs using cin object;
#include <iostream>
using namespace std; // taking inputs using cin object;
int main() #include <iostream>
{ using namespace std;
int a; int main()
float b;
char c; {
cout<< “enter integer a “; int a;
cin>>a; float b;
cout”\nenter a floating point number b ”; char c;
cin>>b; cout<< “enter integer a, float b and character c”;
cout<<“\nenter a single character c=“ cin>>a>>b>>c;
cin>>c; cout<<“\nthe value of a is = “<<a;
cout<<“\nthe value of a is = “<<a; cout<<“\nthe value of b is = “<<b;
cout<<“\nthe value of b is = “<<b; cout<<“\nthe value of c is = “<<c;
cout<<“\nthe value of c is = “<<c; return 0;
return 0; }
}

18
Operators
1. Arithmetic operators
– Assignment operator
– Increment/decrement
operators
2.Relational operators
3.Logical operators

19
Arithmetic operators

20
Arithmetic operators cont.
increment/Decrement operators

21
Arithmetic operators cont.
Assignment operators

22
THE END

23
11/5/2023

Lecture-10,11 &12
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

Operators
1. Arithmetic operators
– Assignment operator
– Increment/decrement
operators
2.Relational operators
3.Logical operators

1
11/5/2023

Arithmetic operators

Relational Operator

2
11/5/2023

Relational
operators
Let A=3
B=5

Example
#include <iostream>
using namespace std;
int main( )
{
int a = 5, b = 5, c = 10;
cout<< “\n a=5, b=5 and c=10”;
cout<< “\n is The value of a=b\t” << (a==b);
cout<< “\n is a=c\t” << (a==c);
cout<< “\n is a>b\t” << (a>b);
cout<< “\n is a>c\t” << (a>c);
cout<< “\n is a<c\t” << (a<c);
cout<< “\n is a!=b\t” << (a!=b);
cout<< “\n is a!=c\t” << (a!=c);
cout<< “\n is a>=b\t” << (a>=b);
return (0);
}
6

3
11/5/2023

Logical operators

#include <iostream>
Example using namespace std;
int main( )
{
int a = 5, b = 5, c = 10, result;

result = ( (a == b) && (c > b) );


cout<< “\n (a == b) && (c > b) is =“<<result;

result = ( (a == b) && (c < b) );


cout<< “\n(a == b) && (c < b) is =“<<result;

result = (a == b) || (c < b);


cout<< “\n(a == b) || (c < b) is =“<<result;

result = (a != b) || (c < b);


cout<< “\n(a != b) || (c < b) is =“<<result;
return (0);
}

4
11/5/2023

Basic Data types in C++


• Integer Data Types
• Floating Point Data Types
• Logical Data Types
• Character Data types
• Text Data types

Basic Data types in C++ cont.


• integer data types: a whole number not a fraction
– char
– short
– int
– long
– unsigned char
– unsigned short
• floating point data types: positive or negative number
with decimal point
– float
– double
– long double

10

5
11/5/2023

Basic Data types in C++ cont.


• Logical Data Types
– Bool constraints
• True
• false
• Character Data types
– Char constraints in single quotes ‘a’
• Text Data types
– String constraints in double quotes “Pakistan Zindabad”

11

C++ Data Types

simple structured

integral enum floating array struct union class

char short int long bool

address
float double long double

pointer reference
12

6
11/5/2023

C++ data Types

13

Examples of cout object

// printing a constant using cout


#include <iostream>
using namespace std; output
Int main( )
{ the value of a is = 2
int a=2; the value of b is = 3.2400000
float b=3.24; the value of c =p
char c=‘p’;
cout<< “the value of a is = ”<< a;
cout<< “\nthe value of b is = “<< b;
cout<<“\n the value of c is =“<<c;
}

14

7
11/5/2023

Variables Declaration
• These are named memory location
• Variables declared in global or local declaration sections
• Basic types: char, int, float
• Syntax: Type Name;
• Examples:
int sum;
float avg;
char dummy;

Multiple Variable Declarations


• Can create multiple variables of the same type
in one statement:
int x, y, z;
is a shorthand for
int x;
int y;
int z;
- stylistically, the latter is often preferable

8
11/5/2023

Variable Initialization
• Giving a variable an initial value is called initialization
• Variables not necessarily initialized when declared
(value is unpredictable - garbage)
• We Can initialize in declaration:
Example:
int x=2; int x=0; float a=2.43;
int y=5; int y=0; float b=3.20;
int z=7; int z=0;
or
Or Or float a=2.43, b=3.20;
int x=2, y=5, z=7; int x=0, y=0, z=0;

Or
int x, y, z = 0;

Examples of variables

// printing
#include <iostream.h>
int main()
output
{
int a=2;
the value of a is = 2
float b=3.24;
the value of b is = 3.24
char c=‘p’;
the value of c =p
char name[ ] =“pakistan zindabad”;
The name is = Pakistan Zindabad
cout<< “the value of a is = ”<< a;
cout<< “\nthe value of b is = “<< b;
cout<<“\nthe value of c is =“<<c;
cout<<“\nthe name is =“<< name;
return 0;

18

9
11/5/2023

Program 1
Write a program which takes four(4) numbers as
input and prints their sum and Average. Using
simple assignment operators

19

Program 2
Write a program which takes two (2) numbers as
input and exchanges their values.

20

10
11/5/2023

Library Functions
• Many activities in C++ are carried out by library functions.
• These functions perform mathematical computations, and data
conversion, among other things.
• # include <cmath> is to be included when calling library functions
• sqrt(x): for square root
of a number x
• pow (m,n): calculates
power of a number, m
is base and n is power.
• cbrt(x): calculates cube
root of a number x.
• log(x)
• round(x)

21

Program 3
write a program which solves a quadratic equation.
take a, b and c as input from user

help: the function for square root in c-language is sqrt();


example: t=sqrt(s); // square root of number s will be stored in t
2. For calculating power function pow( ) is used
Example: q=pow(6,4); // it will evaluate 64 i.e 6x6x6x6 will be evaluated

header files for sqrt() and pow()


ax 2  bx  c
cmath.h

 b  b 2  4ac
x
2a
22

11
11/5/2023

THE END

23

12
11/12/2023

Lecture-13,14&15
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

Loops

1
11/12/2023

Loops
Loops are used to repeat a block of code.
There are three types of loops:

1. for
2. while
3. do…..while.

For loop
for (initialization; condition; step)
{
Statement 1; #include <iostream> Output
Statement 2; 0
int main() 1
…………...
{ 2
Statement n; int x; 3
} for ( x = 0; x < 10; x++ ) 4
{ 5
cout<< “\n” << x ; 6
} 7
return 0; 8
} 9
{
cout<< “\n ” << x;
x++;
}
4

2
11/12/2023

For loop
#include <iostream> The loop will run from x=0 to x=9, i.e 10 times
using namespace std;
int main()
{
int x;
{ // first time { // second time { // third time
x=0; x=1; x=2;
for ( x = 0; x < 10; x++ )
cout<< “\n“ << x;
{ cout<< “\n“ << x; cout<< “\n“ << x;
x++;
cout<< “\n“ << x;
x++; }
} x++;
return 0; } Output
}
} 0
{ // tenth time 1
x=9; 2
cout<< “\n“ << x; 3
.......... 4
5
x++;
6
} 7
cout<< “\n outside loop x=” << x; // What will be 8
printed here??? 9
Outside loop 10 5

Program 3.1
Write a program to print all the 256 ASCII
characters in C-Language using for loop.
#include <iostream> #include <iostream>
using namespace std; Using namespace std;
int main()
int main() {
{ int x;
Make changes in this int x;
for ( x = 0; x < 256; x++ )
program {
for ( x = 0; x < 10; x++ ) cout<< x<< “ “ << (char) x <<“\t”;
{ }
return 0;
cout<< “\n“ << x; }
}
return 0;
}

3
11/12/2023

ASCII Character
chart

Program 3.2
Write a program, by using for loop, which takes
five(5) integers as input and prints their sum and
average.

4
11/12/2023

Program 3.3
Write a program to print alphabets in upper case
from A to Z.
ASCII code of A is 65

Using for loop


Form Comment
for ( i=0 ; i < 10 ; i++ )
Single Statement
Statement1;
for ( i=0 ;i <10; i++) Multiple Statements within for
{
Statement1;
Statement2;
Statement3;
}

for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look at the Semicolon )
for (i=0,j=0;i<100;i++,j++) Multiple initialization & Multiple
Statement1; Update Statements Separated by Comma
for ( ; i<10 ; i++) Initialization not used
for ( ; i<10 ; ) Initialization & Update not used
for ( ; ; ) Infinite Loop,Never Terminates

10

5
11/12/2023

Nested for loop

for ( initialization; condition; increment )


{

for ( initialization; condition; increment )


{

// statement of inside loop


}

// statement of outer loop


}

11

Write a program to print the following pattern


// nested loop
#include <iostream>
using namespace std;
int main( )
1 1 1 1 1 1 1 1 1 1 {
2 2 2 2 2 2 2 2 2 2 int i,j;
3 3 3 3 3 3 3 3 3 3 for(i = 1; i<10; i++) // controls rows
. {
.
for(j =1; j <=10; j++) // controls printing
. {
. cout << i;
. } // end of internal loop

9 9 9 9 9 9 9 9 9 9 cout <<“\n”;
}// end of external loop

return 0;
}
12

6
11/12/2023

Write a program to print the following pattern


// nested loop
a a a a a a a a a a #include <iostream>
using namespace std;
b b b b b b b b b b int main( )
. {
. int i,j;
for(i = 1; i<10; i++) // controls rows
. {
.
for(j =1; j <=10; j++) // controls printing
{
k k k k k k k k k k cout << i;
} // end of internal loop

cout <<“\n”;
Make changes in this }// end of external loop
program
return 0;
}
13

Write a program to print the following pattern


// nested loop
#include <iostream>
using namespace std;
int main( )
A B C D {
int i,j;
E F G H
int k=65;
.
for(i = 1; i<=7; i++) // controlling rows
. {
. for(j =1; j <=4; j++) // printing alphabet
. {
Y Z cout << (char)k;
k++;
} // end of internal loop

cout <<“\n”;
Question: }// end of external loop
How to stop printing at “Z” ?
return 0;
} 14

7
11/12/2023

Write a program to print the following pattern


// nested loop
#include <iostream>
using namespace std;
int main( )
A {
int i,j;
AA
int k=65;
AAA
for(i = 1; i<=7; i++) // controlling rows
AAAA {
AAAAA for(j =1; j <=4; j++) // printing alphabet
. {
. cout << (char)k;
. k++;
.9 lines } // end of internal loop

cout <<“\n”;
How to modify this code }// end of external loop

return 0;
} 15

Write a program to print the following pattern

A
BB
CCC
DDDD
EEEEE
.
.
.
.
15 lines

16

8
11/12/2023

Decisions
• Decision making is about deciding the order of execution of
statements based on certain conditions or repeat a group of
statements until certain specified conditions are met.
• In a program a decision causes a onetime jump to a different
part of the program, depending on the value of an expression.
• Decisions can be made in C++ in several ways.

1. if statement
2. switch statement
3. conditional operator statement (? : operator)

17

Decisions
1-if statement
• The if statement may be implemented in
different ways depending on the complexity of
conditions to be tested.
• The different forms are,
– Simple if statement
– if....else statement
– Nested if....else statement
– Using else if statement (else if ladder)

18

9
11/12/2023

THE END

19

10
11/17/2023

Lecture-16,17&18
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

Decisions
• Decision making is about deciding the order of execution of
statements based on certain conditions or repeat a group of
statements until certain specified conditions are met.
• In a program a decision causes a onetime jump to a different
part of the program, depending on the value of an expression.
• Decisions can be made in C++ in several ways.

1. if statement
2. switch statement
3. conditional operator statement (? : operator)

1
11/17/2023

Decisions
1-if statement
• The if statement may be implemented in
different ways depending on the complexity of
conditions to be tested.
• The different forms are,
– Simple if statement
– if....else statement
– Nested if....else statement
– Using else if statement (else if ladder)

Decisions
1-if statement cont.
The if statement enables you to test for a condition and branch to different
parts of code, depending on the result.

expression is the conditional criterion. If expression is logical TRUE the


statements inside the braces such as statement1 and statement2 are
executed.
If expression is logical FALSE (zero), then the statements are skipped

if (expression)
{
statement1;
statement2;
.
.
}

2
11/17/2023

Decisions
1-if statement cont.
• The if statement enables you to test for a condition and branch to
different parts of code, depending on the result.
• Test expression is the conditional criterion.
• If expression is logical TRUE the statements inside the braces are
executed.
• If expression is logical FALSE (zero), then the statements are skipped

if (expression)
{
statement1;
statement2; No
. Semicolon
here (;)
.
}

Decisions
1-if statement cont.
Example:
Write a program which takes an integer as input and checks whether it
is even.
// decisions
#include <iostream>
using namespace std;
int main( )
{ output
int a;
cout<<“ enter an integer ”;
cin>>a; enter an integer 22
if(a%2 == 0) the number is even
{
cout<<“the number is even”;
}
return 0;
} 6

3
11/17/2023

Decisions
2-if – else statement
If the expression is true, the statement-block1 is
executed, else statement-block1 is skipped and
statement-block2 is executed.

Condition
statement not
to be written
with else

Decisions
2-if –else statement cont.
Example:
Write a program which takes an integer as input and checks
whether it is even or odd.
// decisions output
#include <iostream>
using namespace std; enter an integer 22
int main( ) the number is even
{
int a;
cout<<“ enter an integer ”;
cin>>a; output
if(a%2 == 0)
{ cout<<“the number is even”;} enter an integer 13
else the number is odd
{cout<<“the number is odd”; }
return 0;
} 8

4
11/17/2023

Decisions
3-Nested if –else statement cont.
When if expression is true
then execution continues
and enters inside the first
if to perform the check for
the next if block, where if
expression 1 is true the
statement-block1 is
executed otherwise
statement-block2 is
executed.
If the expression given in
first if is false then else in
the last will be execute
the statements of block-3

if(a > b)
Decisions {
if(a > c)
3-Nested if –else statement {
cont. }
cout<<“the largest number is << a;

Example: Write a program which takes else


{
three integers as input and checks and cout << “the largest number is” <<c;
prints the largest integer }
}
/*this is a program to print the else
largest number from three {
integers*/ if(b > c)
#include <iostream> {
using namespace std; cout<< “ the largest number is “<<b;
int main( ) }
{ else
int a,b,c; {
cout<<“ enter first integer” ; cout << “the largest number is” <<c;
cin>>a; }
cout<<“ enter second integer” ; }
cin>>b;
cout<<“ enter third integer” ; return 0;
cin>>c; }
10

5
11/17/2023

Decisions
4- else-if ladder
if(expression1)
Else if ladder is usually made when {
multiple conditions are checked to statement block1;
make a decision }
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;

11

Decisions /*this is a program to print the largest


number from three integers*/
4- else-if ladder #include <iostream>
using namespace std;
int main( )
Example: Write a program which takes {
three integers as input and checks and int a,b,c;
prints the largest integer cout<<“ enter three integers”;
cin>>a>>b>>c;
if( (a>b) && (a>c) )
{
cout<<“the largest number is << a;
}
else if( (b>c) )
{
cout<< “ the largest number is “<<b;
}
else
{
cout << “the largest number is” <<c;
}
return 0;
}

12

6
11/17/2023

/*to check divisibility of a number by 7 and 8*/


Decisions #include <iostream>
using namespace std;
4- else-if ladder int main( )
{
int a;
Example: Write a program cout<<“ enter an integers”;
which takes an integer as cin>>a;
input and checks whether it is if((a%7 == 0) && (a%8==0))
divisible by 7 or 8. {
cout<<“the number is divisible by 7 and 8 ”;
}
else if(a%7 == 0)
{
cout<<“the number is divisible by 7 ”;
}
else if(a%8 == 0)
{
cout<<“the number is divisible by 8”;
}
else
{
cout<< “ the number is not divisible by 7 and 8”;
}
return 0;
} 13

Decisions
Conditional Statement
max=(num1 > num2) ? num1:num2;

14

7
11/17/2023

Decisions
else-if ladder vs Conditional statement
Example: Write a program which takes three integers as input and checks and prints the largest
integer

/*this is a program to print the largest


number from three integers*/
#include <iostream>
using namespace std;
int main( )
{
int a,b,c,max;
cout<<“ enter three integers”;
cin>>a>>b>>c;
max= (a>b) ? a:b;
max= (max>c) ? max:c;
cout<<“the largest number is << max;
return 0;
}

15

Decisions
Conditional Statement cont.
Write a program which takes 5 integers as input and
prints the largest
#include <iostream.h>
main()
{
int max=0,i, num;

for(i=1;i<=5;i++)
{
cout<< “\n enter integer”;
cin>> num;
max=(max > num) ? max:num;
}

cout<<“the largest number is ”<<max;


}
16

8
11/17/2023

Exercise: Write a program which takes 5 integers as


input and prints the largest

Exercise: Write a program which takes 5 integers as


input and prints the largest ( it should be able to handle
both negative and positive numbers)

17

statements with loops or conditions


break;
exit(0); // header file stdlib.h or process.h
continue; // used with loops
goto location; // not recommended

18

9
11/17/2023

Program: write a program which takes an integer as input and checks whether it is
prime or not

#include<iostream.h>
int main ( )
{
int i, j;
cout<< “enter an integer greater than or equal to 2”;
cin>>i;
for(j = 2; j <= (i-1);j++)
{
if(i%j==0)
{
cout<<“the number is not prime”;
exit(0);
}
}
cout<< “the number is prime”;
return 0;;
}

19

Practice Program

Important: Try to develop a new logic


Write a program which takes an integer as
input and check whether it is prime or not

20

10
11/17/2023

Decisions
Switch Case
In if-else / else-if ladder as the number of
alternatives increases the complexity of program
increases drastically.
• Switch statement is a multi-way decision
statement

21

Decision
if(Condition 1)
Switch Case cont.
Statement 1 switch ( expression )
else {
{ case label1 :
Statement 2 body1
if(condition 2) break;
{
if(condition 3) case label2 :
statement 3 body2
else break;
if(condition 4) case label3 :
{ body3
statement 4 break;
} default :
} default-body
else break;
{ }
statement 5
} next-statement;
22
}

11
11/17/2023

23

Rules of Using Switch Case


1. Case Label must be unique. switch ( expression )
2. Case Labels must ends with Colon. {
3. Case labels must have constants / constant expression. case label1 :
4. Case label must be of integral Type ( Integer, Character). body1
5. Case label should not be ‘floating point number ‘. break;
6. Switch case should have at most one default label.
case label2 :
7. Default label is Optional.
body2
8. Default can be placed anywhere in the switch.
break;
9. Break Statement takes control out of the switch.
case label3 :
10. Two or more cases may share one break statement. body3
11. Nesting ( switch within switch ) is allowed. break;
12. Relational Operators are not allowed in Switch default :
Statement. default-body
13. Macro Identifier are allowed as Switch Case. break;
14. Const Variable is allowed in switch Case Statement. }
15. Empty Switch case is allowed.
next-statement;

24

12
11/17/2023

//to check course from curse id


#include <iostream>
Decision using namespace std;
int main( )
Switch Case cont. {
int id;
cout<<“ enter course id from 1-3”;
cin>>id;
Example: Write a program switch(id)
{
which takes a course id (1-4) case 1:
as input and prints its cout<<“turbo c programming language”;
break;
respective course case 2:
cout<<“c++ programming language";
1. turbo c programming break;
language case 3:
cout<<“visual Basic";
2. c++ programming break;
case 4:
language cout<<“web technology";
3. Visual Basic break;
default :
4. web technology cout<<“incorrect course id";
break;
}
return 0;
}

25

Example: Write a program which takes a character as input and


checks whether it is vowel or consonant.
//to check vowel and consonant //to check vowel and consonant
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main( ) int main( )
{ {
char ch; char ch;
cout<<“ enter an alphabet”; cout<<“ enter an alphabet”;
cin>>ch; cin>>ch;
if(ch==‘a’ ||ch==‘e’||c==‘i’||ch==‘o’ ||ch==‘u’) switch(ch)
cout << “the character is a vowel”; {
else case ‘a’:
cout << “the character is not a vowel”; case ‘e’:
return 0; case ‘i’:
} case ‘o’:
case ‘u’: cout<<“the character is a vowel”;
break;
default : cout << “the character is not a vowel”;
}
return 0;
}

26

13
11/17/2023

getch() and getche();


• these functions are used to take a single
character as input.
• headerfile
• #include <conio.h>
• a=getch();
• b=getche();
• difference ?

27

Example: Again write the following programs, takes a character as


input and checks whether it is vowel or consonant. Using getch(); ,
getche(); //to check vowel and consonant
#include <iostream>
using namespace std;
int main( )
//to check vowel and consonant {
#include <iostream> char ch;
using namespace std; cout<<“ enter an alphabet”;
int main( ) cin>>ch;
{ switch(ch)
char ch; {
cout<<“ enter an alphabet”; case ‘a’:
cin>>ch; case ‘e’:
if(ch==‘a’ ||ch==‘e’||c==‘i’||ch==‘o’ ||ch==‘u’) case ‘i’:
cout << “the character is a vowel”; case ‘o’:
else case ‘u’: cout<<“the character is a vowel”;
cout << “the character is not a vowel”; break;
return 0; default : cout << “the character is not a vowel”;
} }
return 0;
}

28

14
11/17/2023

Practice program
Write a program to make a simple calculator to
perform following basic functions
• Addition
• Subtraction
• Multiplication
• division

29

THE END

30

15
11/23/2023

Lecture-19,20 &21
Corse Title: Computer and Programming Language
Course Code: EL-105
Course Teachers: Dr. Sadia Muniza Faraz
Semester: Fall-2023
Offered to: F.E. (Electronic Engineering)

Department of Electronic Engineering


NED University of Engineering and Technology Karachi, Pakistan

While loop
Syntax
while (expression) //to check working of while loop
#include <iostream>
Output
0
{ using namespace std;
int main( )
1
2
Statement 1; {
3
int x = 0; // initialization of counter
Statement 2; while(x<10) // limit of loop 4
{ 5
…………... cout<< x<< “\n” ; 6
x++; //increment of counter 7
Statement n; } 8
return 0;
} }
9

1
11/23/2023

Nested while loop

while(condition)
{

while ( condition )
{

// statement of inside loop


}

// statement of outer loop


}

// nested while loop


Write a program to print the #include <iostream>
using namespace std;
following pattern using while loop
int main( )
{
1 1 1 1 1 1 1 1 1 1 int i, j;
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 i=1;
. while( i<10) // controls rows
. {
.
. j=1;
. while ( j <=10) // controls column

9 9 9 9 9 9 9 9 9 9
{
cout<< i;
j++;
} // end of internal loop
cout <<“\n”;
i++;
}// end of external loop
return 0; } // end of main 4

2
11/23/2023

Practice program: Write a program to print the


following pattern using nested while loop

A B C D
E F G H
.
.
.
.
Y Z

do while loop
• the loop condition is tested at the
end of the body of the loop.
• the loop is executed at least one.

Syntax :
do
{
Statement 1;
Statement 2;
…………...
Statement n;
}
while(expression);

3
11/23/2023

Do-while loop, examples


/* "hello, world!" is printed at least one time even though the
condition is false */

#include <iostream>
using namespace std;
int main()
{
int x;
x = 0;
do
{
cout<< “hello, world!" ;
}
while ( x != 0 );

return 0;
}
7

Practice Program
• Write a program which prints prime numbers
less than 100.

4
11/23/2023

// all prime numbers less than 100


#include <iostream>
using namespace std;
int main()
{
Write a program int i, j=2,k;
which prints do
prime numbers {
less than 100. k=0; // this is a flag variable
for(i = 2; i<=(j-1);i++)
{
if(j%i==0)
{ k++; // the value of flag will be changed
}
} What changes can be made here ?
if(k==0) Can we remove this flag?
{ cout << “\t”<< j; Can we use break statement ?
} Any other logic for making this
j++; // it is generating numbers program ?
} // end of do-while loop
while(j<=100);
return 0;
} // end of main

// all prime numbers less than 100


#include <iostream>
using namespace std;
int main()
Program: write a {
int i, j=2,k;
program to print int count=1; // the counter
first 100 prime do
{
numbers k=0; // this is a flag variable
for(i = 2; i<=(j-1);i++)
{
if(j%i==0)
{ k++; // the value of flag will be changed
}
}
if(k==0)
{ cout << “\t”<< j;
count++; // the counter will count when prime number is printed
}
j++; // it is generating numbers
} // end of do-while loop
while(count<=100); // checking that counter is at 100 or not
} // end of main

10

5
11/23/2023

Home Work

Write a program which takes some text as input and


count total number of vowels and consonants in the text

Write a program which takes some text as input and


counts each vowel separately and prints their count.

11

#include <iostream>
#include <conio.h>
using namespace std;
int main()
program: {
take some char ch;
int ca=0,ce=0,ci=0,co=0,cu=0; // initialize all counters
text as input cout<< “ type some text and press enter”;
and counts do
{
each vowel ch=getche();
cin should not be used to take
character input multiple times
separately switch(ch) here
{
and prints case ‘a’: ca++; break;
their count. case ‘e’: ce++; break;
……….
……….
case ‘u’: cu++; break;
default : break;
} // end of switch
} // end of do-while
while (ch !=‘\r’);
cout<< "\n number of a=" << ca << "\n number of e=" << ce << "\n number of i=" <<
ci << "\n number of o=" << co<< "\n number of u=" << cu;
return 0;
} // end of main
12

6
11/23/2023

Practice Programs
Practice all the programs given in “Exercises” in
the end of chapter-3 (Loops and decisions) of
text book

Object Oriented Programming


in C++ (Fourth Edition)
Author: Robert Lafore

13

THE END

14

You might also like