0% found this document useful (0 votes)
11 views

C++ Chap 1 3

Uploaded by

hellenyared2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

C++ Chap 1 3

Uploaded by

hellenyared2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Fundamentals of C++ Programming

Chapter One
Introduction

The Fundamentals of C++ Programming course is designed to provide students with a solid
foundation in the principles and concepts of C++ programming. This course is ideal for
beginners who have little to no prior programming experience and want to learn one of the
most widely used programming languages in the world. Throughout the course, students will
learn the fundamental building blocks of C++ programming, including variables, data types,
control structures, functions, arrays, pointers, object-oriented programming concepts,
file operations, and error and exception handling . The course will cover both the
theoretical concepts and practical implementation of these topics through hands-on
programming assignments and projects.

C++ is a general-purpose programming language with a rich set of features that allow developers to write
efficient and high-performance code.

Some key aspects of the fundamentals of C++ programming include the


following:
1. Syntax: C++ follows a syntax similar to the C programming language, but with added
features and improvements. It includes various elements such as variables, data types,
operators, control structures (loops and conditional statements), functions, and classes.

2. Data Types: C++ provides both built-in data types (such as integers, floating-point
numbers, characters) and user-defined data types (classes, structures, enumerations,
unions). It also supports type modifiers, such as const and volatile, to specify data
properties.

3. Memory Management: C++ gives you control over memory management. You can allocate
memory dynamically using the new keyword and deallocate it using the delete keyword. C++
also introduces the concept of constructors and destructors, which are used for
initializing and cleaning up objects, respectively.

4. Standard Template Library (STL): The STL is a powerful library that provides generic
algorithms and data structures, such as vectors, lists, maps, and algorithms like sorting
and searching. It simplifies common programming tasks and promotes code reuse.

5. Exception Handling: C++ supports exception handling, allowing you to handle errors and
exceptional conditions in a structured manner. You can use try-catch blocks to catch and
handle exceptions, ensuring that your program continues to execute gracefully even in the
presence of errors.

Prepared by: Tesfay Gidey 1


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
6. Templates: C++ templates enable generic programming by allowing you to write code that
works with different types. Templates provide a way to write reusable functions and classes
that can operate on different data types without sacrificing performance.

7. Input/Output (I/O): C++ provides I/O functionality through the iostream library. You
can use cout for output and cin for input, making it easy to interact with the user and
display information on the screen.

8. Object-Oriented Programming (OOP): C++ supports object-oriented programming, which


allows you to organize your code into objects that encapsulate data and behavior. You can
define classes to create objects, and utilize concepts like inheritance, polymorphism,
and encapsulation.

N.B
C++ is a versatile language with many additional features and libraries that offer a wide range of capabilities,
making it suitable for various types of application development.
1.1 Overview of programming languages and their uses
When providing an overview of programming languages and their uses, some key issues that
can be discussed include:

1. Purpose and Domain: Each programming language is designed with a specific purpose or
domain in mind.

• Discussing the purposes and domains for which each language is commonly used can
help readers understand the context in which these languages are applied.

2. Features and Paradigms: Programming languages have different sets of features and
support different programming paradigms (e.g., procedural, object-oriented, functional).

3. Syntax and Readability: Programming languages have different syntax rules and
conventions.

4. Ecosystem and Community: Programming languages often have associated ecosystems and
communities that provide libraries, frameworks, and tools.

5. Performance and Efficiency: Some languages are known for their performance and
efficiency, while others prioritize developer productivity.

6. Platform and Compatibility: Some languages are platform-specific, while others are
cross-platform.

7. Popularity and Adoption: The popularity and adoption of programming languages can
influence their usage and support.

Prepared by: Tesfay Gidey 2


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
8. Learning Curve and Resources: Programming languages vary in terms of their learning
curves and the availability of learning resources such as documentation, tutorials, and
online communities.

N.B:
By addressing these issues, an overview of programming languages and their uses can provide readers with a
comprehensive understanding of the landscape and help them make informed decisions about the languages they
choose for their projects or personal learning.
Uses of Programming Languages
Programming languages are versatile tools that allow developers to create software
applications and solve complex problems. Some common uses of programming languages include:

1. Application Development: Programming languages are primarily used to create various


types of software applications, such as desktop applications, mobile apps, web
applications, and enterprise systems.

• Developers write code in programming languages to design the functionality, user


interfaces, and logic behind these applications.

2. Web Development: Programming languages like HTML, CSS, and JavaScript are used to
develop websites and web applications.

• HTML provides the structure and content of web pages, CSS is used for styling and
layout, and JavaScript enables dynamic and interactive features on the web.

3. Data Analysis and Scientific Computing: Programming languages like Python and R are
widely used in data analysis and scientific computing.

• These languages offer rich libraries and frameworks for performing statistical
analysis, data visualization, machine learning, and numerical computations.

4. System Administration and Scripting: Programming languages such as Bash, PowerShell,


and Perl are commonly used for system administration tasks.

• System administrators write scripts in these languages to automate repetitive tasks,


manage servers, and perform system maintenance .

5. Game Development: Programming languages like C++, C#, and Java are popular choices for
developing video games.

• These languages provide the necessary tools and libraries to create game engines,
implement game mechanics, and handle graphics, physics, and audio .

Prepared by: Tesfay Gidey 3


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
6. Artificial Intelligence and Machine Learning: Programming languages like Python and R
are widely used in the fields of artificial intelligence (AI) and machine learning (ML).

• These languages offer powerful libraries and frameworks, such as TensorFlow and
PyTorch, for building and training ML models, natural language processing, computer
vision, and other AI applications.

7. Embedded Systems: Programming languages like C and C++ are commonly used for developing
software for embedded systems, which are computer systems embedded in other devices or
machinery. These languages offer low-level control over hardware, making them suitable
for developing firmware and device drivers.

8. Database Management: Programming languages like SQL (Structured Query Language) are
used for managing and manipulating databases.

• Developers use SQL to create, retrieve, update, and delete data in relational
database management systems (RDBMS).

9. Scripting and Automation: Programming languages like Python, Ruby, and Perl are often
used for scripting and automation tasks.

• These languages provide high-level abstractions and extensive libraries, making it


easier to automate tasks, build scripts, and create command-line tools.

10. Internet of Things (IoT): Programming languages like C, C++, and Python are used in
IoT development.

• These languages enable developers to program IoT devices, connect them to the
internet, and build applications that interact with the physical world.

N.B:
• These are just a few examples of the diverse uses of programming languages.
• Different languages excel in different domains, and the choice of programming
language depends on the specific requirements and goals of the project.

What is programming?
Programming is the process of creating instructions or code that a computer can execute to perform specific
tasks or solve problems.

• It involves writing, testing, and maintaining sets of instructions, known as


programs, that tell a computer how to perform a desired operation or produce a
desired output.

At its core, programming is about giving precise instructions to a computer to carry out a particular sequence
Prepared by: Tesfay Gidey 4
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
of actions.

• These instructions are typically written using a programming language, which serves
as a structured and formalized way of communicating with the computer.

The process of programming involves several steps:


1. Problem Definition: Identifying and understanding the problem that needs to be solved
or the task that needs to be accomplished.

2. Algorithm Design: Developing a step-by-step plan or algorithm that outlines the logical
sequence of operations to solve the problem.

3. Writing Code: Translating the algorithm into a programming language by writing lines
of code that implement the desired logic and operations.

4. Compilation/Interpretation: Depending on the programming language, the code may need


to be compiled or interpreted into a format that the computer can understand and execute.

5. Testing and Debugging: Running the program and testing it with different inputs to
ensure it produces the expected results.

• Debugging involves identifying and fixing any errors or issues in the code.

6. Maintenance and Updates: Programs may need to be maintained and updated over time to
address bugs, add new features, or adapt to changing requirements.

Programming is a creative and problem-solving activity that requires logical thinking, attention to detail, and
the ability to break down complex problems into smaller, manageable components.

• It empowers humans to harness the capabilities of computers, automate tasks, build


software applications, and create innovative solutions across various domains,
including software development, data analysis, artificial intelligence, web
development, and much more.

Why do we need to learn computer programming?


Learning computer programming is a valuable skill that equips you with problem-solving
abilities, opens up career opportunities, fosters creativity and innovation, and provides
a deeper understanding of technology.

• Whether you pursue programming as a career or as a means to enhance your problem-


solving skills, it is a valuable skill set in the digital age.

Learning computer programming offers a range of benefits and is becoming increasingly important in

Prepared by: Tesfay Gidey 5


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
today’s digital world.
Some reasons why learning computer programming is valuable:
1. Problem Solving: Programming teaches you how to break down complex problems into
smaller, more manageable tasks.

• It enhances your analytical and critical thinking skills, enabling you to develop
logical solutions to problems in various domains.

2. Automation and Efficiency: Programming allows you to automate repetitive tasks, saving
time and effort.

• By writing code to perform tasks, you can streamline processes, increase efficiency,
and reduce the potential for human error.

3. Career Opportunities: The demand for programmers and software developers continues to
grow across industries.

• Learning programming opens up a wide range of career opportunities, from software


engineering and web development to data science and artificial intelligence.

4. Creativity and Innovation: Programming provides a platform for creativity and


innovation.

• It allows you to bring your ideas to life by developing software applications,


websites, games, and other digital solutions.
• Programming fuels technological advancements and empowers you to create something
unique and impactful.

5. Understanding Technology: Programming helps you understand how technology works.

• It gives you insights into the underlying principles and mechanisms of computers,
software, and digital systems.
• This knowledge enables you to be more informed and make better use of technology in
your personal and professional life.

6. Computational Thinking: Learning programming promotes computational thinking, which


involves a structured approach to problem-solving that emphasizes algorithmic reasoning,
abstraction, pattern recognition, and data analysis. These skills are valuable not only
in programming but also in various other fields .

7. Collaboration and Communication: Programming often involves collaborating with others


on projects.

Prepared by: Tesfay Gidey 6


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• Learning programming improves your ability to work in teams, communicate technical
concepts effectively, and engage in collaborative problem-solving.

8. Empowerment and Adaptability: With programming skills, you gain the ability to create
your own tools and solutions.

• Programming empowers you to take control of technology, adapt it to your needs, and
build custom solutions that address specific challenges.

9. Understanding the World: Programming is increasingly intertwined with various aspects


of our lives.

• Learning programming helps you better understand and navigate the digital world,
including concepts like cybersecurity, data privacy, and the ethical implications
of technology.

10. Continuous Learning: Programming is a field that constantly evolves.

• Learning programming equips you with a mindset of continuous learning, as you need
to stay updated with new technologies, languages, and frameworks.
• This adaptability and willingness to learn are valuable skills in today’s fast-
paced technological landscape.

What is a programming language?


A programming language is a formalized system of rules, syntax, and semantics that allows humans to
communicate instructions to a computer or a machine. It provides a set of symbols, keywords, and grammar that
programmers use to write code, which can be executed by a computer to perform specific tasks or solve problems.

Programming languages can be classified into several categories based on their design and
purpose. Some common categories of programming languages include:

1. High-level languages: These languages are designed to be more human-readable and


are closer to natural language.

• They provide abstractions and higher-level constructs that make it easier for
programmers to write code.
• Examples include Python, JavaScript, Java, and Ruby.

2. Low-level languages: These languages are closer to the machine’s hardware and provide
more direct control over the system.

• They often require a deeper understanding of the computer’s architecture and are
used for tasks that require fine-grained control and performance optimization.
• Examples include Assembly language and C.
Prepared by: Tesfay Gidey 7
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
3. Object-oriented languages: These languages support the object-oriented programming
paradigm, which organizes code around objects that encapsulate data and behavior.

• Object-oriented languages provide features like classes, inheritance, and


polymorphism.
• Examples include Java, C++, and Python.

4. Functional languages: These languages emphasize functional programming, where


computation is treated as the evaluation of mathematical functions.

• They focus on immutability and the absence of side effects. Examples include Haskell,
Lisp, and Erlang.

5. Scripting languages: These languages are often used for scripting or automating tasks.

• They have dynamic typing, and high-level abstractions, and are typically interpreted
rather than compiled.
• Examples include Python, Perl, and Ruby.

6. Domain-specific languages (DSLs): These languages are designed for specific domains or
specialized tasks. They provide focused abstractions and syntax tailored to the problem
at hand.

• Examples include SQL for database queries and HTML/CSS for web development.

Each programming language has its own syntax, rules, and capabilities, and is suited to different types of
applications and problem domains. The choice of a programming language depends on factors such as the task at
hand, the ecosystem and libraries available, performance requirements, and personal preference.
Generations of programming language
Programming languages can be categorized into different generations based on their
development and evolution over time. It is categorized into five generations: (1st, 2nd,
3rd, 4th and 5th generation languages)

1. First Generation (1940s-1950s):

• First-generation programming languages, also known as machine languages, are the


lowest-level languages.
• They consist of binary code that directly corresponds to the machine instructions
executed by the computer’s hardware.
• Machine languages are specific to a particular computer architecture and require a
deep understanding of the computer’s instruction set.

2. Second Generation (1950s-1960s):

Prepared by: Tesfay Gidey 8


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• Second-generation programming languages, known as assembly languages, introduced
mnemonic codes to represent machine instructions.
• Assembly languages use symbolic names (mnemonics) for operations and memory
locations, making it easier for programmers to write and understand code compared
to machine languages.
• However, assembly languages are still closely tied to the underlying hardware.

3. Third Generation (1960s-1970s):

• Third-generation programming languages are high-level languages that abstract away


the complexities of the underlying hardware .
• They provide more powerful and expressive constructs, making programming more
accessible and efficient.
• Examples of third-generation languages include Fortran, COBOL, C, and Pascal.
• These languages introduced features like structured programming, data types, control
structures, and libraries.

4. Fourth Generation (1970s-1990s):

• Fourth-generation programming languages (4GLs) are designed for specific domains or


specialized tasks, known as Domain-Specific Languages.
• They provide higher-level abstractions and syntax that are tailored to the problem
at hand.
• 4GLs are often used for database querying, report generation, and rapid application
development.
• Examples include SQL (Structured Query Language) and tools like PowerBuilder and
MATLAB.

5. Fifth Generation (1980s-present):

• Known as artificial intelligence (AI) languages.


• The fifth-generation programming languages were originally envisioned to support AI
and expert systems.
• They aimed to enable natural language processing and advanced reasoning capabilities.
• However, the development of true fifth-generation languages has not been as prominent
as initially anticipated, and the term is less commonly used in current discussions
of programming languages.

N.B:
• It’s important to note that these generations do not have hard boundaries, and
there is overlap and ongoing evolution in programming languages.
• New languages continue to emerge, incorporating features from previous generations
while introducing new concepts and paradigms.
Prepared by: Tesfay Gidey 9
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• Additionally, there are also scripting languages, domain-specific languages, and
other specialized languages that don’t neatly fit into these generational
classifications.

Comparison of the generations of programming languages based on their level of abstraction


and programming paradigm:

N.B:
Please note that the fifth generation has no widely adopted languages, so specific characteristics are not
applicable.

Comparing the generations of programming languages based on multiple attributes:

| Generation | Portability | Efficiency | Expressiveness | Community and Ecosystem |


Paradigm Support |
|------------|-------------|------------|----------------|-------------------------|----
--------------------|
| First | Low | High | Low | Limited | Not
applicable |
| Second | Low | High | Low | Limited | Not
applicable |
| Third | Medium | Medium | Medium | Large and Active |
Procedural, Imperative |
| Fourth | High | Varies | High | Varies |
Declarative, Query-based|
| Fifth | Varies | Varies | Varies | Varies | Not
applicable |

Prepared by: Tesfay Gidey 10


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
1.2 Overview of Computers and Computer Organization
Computers have become an integral part of our daily lives, facilitating various tasks and
enabling the development of advanced technologies.

• To understand computers and how they function, it’s essential to grasp the concept
of computer organization.

Computer organization refers to the structural components and operational principles that
make up a computer system.

• It encompasses the hardware, software, and their interaction to perform


computational tasks efficiently.

An overview of the key aspects of computer organization:

1. Hardware Components:

• Central Processing Unit (CPU): The CPU is the brain of the computer, responsible
for executing instructions and performing calculations.
• Memory: Computers have different types of memory, including primary memory (RAM)
for temporary storage and secondary memory (hard drives) for long-term storage.
• Input/Output (I/O) Devices: These devices allow users to interact with the computer
and transfer data, such as keyboards, mice, displays, printers, and storage devices.

2. Instruction Execution Cycle:

• Fetch: The CPU fetches instructions from memory.


• Decode: The CPU decodes the fetched instructions to understand their meaning.
• Execute: The CPU executes the instructions, performing calculations or data
manipulation.
• Store: The CPU stores the results back into memory or transfers them to output
devices.

3. Software Components:

• Operating System: The operating system manages computer resources, controls hardware,
and provides a user interface.
• Application Software: These are programs that perform specific tasks, such as word
processing, spreadsheets, or web browsing.

4. Binary Representation:

• Computers use a binary system, representing data and instructions using 0s and 1s.

Prepared by: Tesfay Gidey 11


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• Binary digits, or bits, are the fundamental units of information in computers.

5. Computer Architectures:

• Von Neumann Architecture: The most common architecture, where instructions and data
are stored in the same memory, and the CPU fetches them sequentially.
• Harvard Architecture: In this architecture, separate memories are used for
instructions and data, allowing simultaneous fetching of both.

6. Parallelism and Pipelining:

• Parallelism: utilizing multiple processors or cores to perform tasks simultaneously,


improving performance.
• Pipelining: Dividing the instruction execution cycle into stages to increase
instruction throughput by allowing multiple instructions to be processed
concurrently.

Understanding computer organization is crucial for computer scientists, engineers, and programmers, as it
provides the foundational knowledge needed to design, build, and optimize computer systems.
It also helps users make informed decisions about hardware upgrades, software compatibility, and overall system
performance.

Despite variations in physical design, computers can generally be divided into six
distinct logical units or sections:

1. Input Unit:

• The input unit is responsible for accepting data and instructions from external
sources, such as keyboards, mice, scanners, or network connections.
• It converts the input into a form that the computer can understand and passes it to
the central processing unit (CPU) for further processing.

2. Output Unit:

• The output unit is responsible for presenting processed data to the user or
transmitting it to external devices.
• It receives data from the CPU and converts it into a human-readable or machine-
readable format, such as text, images, sounds, or signals sent to printers, displays,
speakers, or storage devices.

3. Central Processing Unit (CPU):

• The CPU is the core component of a computer system and performs all the major
computational tasks.

Prepared by: Tesfay Gidey 12


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• It consists of an arithmetic logic unit (ALU) that performs mathematical operations
and logical comparisons, and a control unit that coordinates and manages the
execution of instructions.

4. Memory Unit:

• The memory unit stores data and instructions required for current and future
processing.
• It is divided into two main types: primary memory (or random access memory, RAM)
for temporary storage of data and instructions , and secondary memory (such as hard
drives or solid-state drives) for long-term storage.

5. Arithmetic and Logic Unit (ALU):

• The ALU is a component of the CPU that performs arithmetic operations (such as
addition, subtraction, multiplication, and division) and logical operations (such
as comparisons and boolean operations) on data.

6. Control Unit:

• The control unit manages and coordinates the activities of the other units within
the CPU.
• It fetches instructions from memory, decodes them, and directs the necessary data
to the ALU or other relevant components for execution.
• It also handles the control flow of instructions and manages the input and output
operations of the computer system.

NB:
• These logical units work together to enable the functioning of a computer system,
allowing it to process data, execute instructions, and produce meaningful results.
• Although the physical implementation may vary across different computer
architectures, the fundamental concept of these logical units remains consistent.

1.3. The Evolution of Operating Systems:


Operating systems (OS) have evolved significantly since their inception, adapting to the
changing needs of computer systems and users. An overview of the evolution of operating
systems is given below:

Prepared by: Tesfay Gidey 13


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
1. Batch Processing Systems (1950s-1960s):

• Early computers relied on batch processing systems, where users submitted jobs on
punched cards or tapes.
• The operating system would organize and sequence the jobs for efficient execution,
but user interaction was limited.

2. Multiprogramming Systems (1960s-1970s):

• Multiprogramming allowed multiple programs to reside in memory simultaneously,


enabling faster execution and improved resource utilization.
• Operating systems implemented techniques like time-sharing and spooling to enhance
user interaction and I/O handling.

3. Time-Sharing Systems (1960s-1970s):

• Time-sharing systems enabled interactive computing by rapidly switching between


multiple users.
• Users could access the system through terminals and share the CPU’s processing
time, providing a more interactive computing experience.

4. Distributed Systems (1980s-1990s):

• Distributed systems extended the capabilities of operating systems across multiple


interconnected computers.
• They facilitated communication and resource sharing between different machines,
enabling increased reliability and scalability.

5. Graphical User Interface (GUI) Systems (1980s-1990s):

• GUI-based operating systems, such as Apple Macintosh and Microsoft Windows,


introduced visual interfaces with icons, windows, and menus.
• They made computers more user-friendly and accessible, allowing users to interact
with the system using a mouse and graphical elements.

6. Client-Server Systems (1990s-Present):

• Client-server systems introduced a client-server architecture, where multiple


clients connect to a central server.
• The server provides services, such as file storage or database access, while clients
request and utilize these services.

7. Modern Operating Systems:

Prepared by: Tesfay Gidey 14


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• Modern operating systems, like Windows, macOS, and Linux, incorporate advanced
features like multitasking, virtual memory, and device drivers.
• They support a wide range of applications, provide robust security mechanisms, and
are designed to run on various hardware platforms.

NB:
• The evolution of operating systems reflects the progression of computing technology
and the increasing demand for more efficient, user-friendly, and reliable systems.
• Today’s operating systems continue to evolve, adapting to emerging technologies
such as cloud computing, mobile devices, and the Internet of Things (IoT).

Punched cards and paper tape


1.4. Major Programming Paradigms:
Programming paradigms are approaches or styles of programming that guide the design and
structure of computer programs. There are several major programming paradigms, each with
its own set of principles and techniques. Some of the most common paradigms include:

1. Imperative Programming:

• Imperative programming focuses on describing how a program should accomplish a task


step-by-step.
• It utilizes statements that change the program’s state and manipulate data through
variables and assignment operations .
• Examples include procedural programming and object-oriented programming (OOP).
• Example Languages: C, Fortran, Pascal.

Prepared by: Tesfay Gidey 15


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
2. Functional Programming:

• Functional programming emphasizes the evaluation of mathematical functions and


avoids changing states or mutable data.
• It treats computation as the evaluation of mathematical functions and emphasizes
immutability and higher-order functions.
• Examples include languages like Haskell, Lisp, and Scala.

3. Object-Oriented Programming (OOP):

• Object-oriented programming organizes code into objects that encapsulate data and
behavior.
• It focuses on concepts such as classes, objects, inheritance, and polymorphism.
• OOP promotes modularity, reusability, and maintainability of code.
• Examples include languages like Java, C++, and Python.

4. Procedural Programming:

• Procedural programming structures code around procedures or subroutines that perform


specific tasks.
• It emphasizes the sequence of procedural steps to solve a problem.
• Procedural programming languages include C, Pascal, and Fortran.

5. Declarative Programming:

• Declarative programming focuses on describing what a program should accomplish


rather than how to achieve it.
• It provides a high-level abstraction where programmers define constraints, rules,
or logic.
• Examples include logic programming languages like Prolog and database query
languages like SQL.

6. Event-Driven Programming:

• Event-driven programming focuses on responding to events or user actions.


• Programs are structured around event handlers that execute code when specific events
occur.
• It is commonly used in graphical user interfaces (GUIs) and web development.

7. Concurrent Programming:

• Concurrent programming deals with programs that execute multiple tasks


simultaneously.

Prepared by: Tesfay Gidey 16


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• It involves coordinating and managing multiple threads or processes to achieve
parallelism and improve performance.
• Concurrent programming is crucial for developing efficient and responsive systems.

N.B:

• These programming paradigms provide different approaches to problem-solving and


program design.
• Programmers often choose the paradigm that best fits the requirements of a specific
project or problem domain.

Demo for Imperative Programming:


• Description: Imperative programming focuses on describing how a program operates by
providing a sequence of statements that change a program’s state.
• It emphasizes the use of variables, assignments, loops, and conditional statements.

Some examples of imperative programming languages are: C, Fortran,


Pascal.

#1. C:

• C is a widely used imperative programming language.


• It provides features for low-level memory manipulation and control over the
program’s execution flow.
• Example code snippet in C:

Prepared by: Tesfay Gidey 17


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
#include <stdio.h>

int main() {
int x = 10;
if (x > 0) {
printf("Positive number\n");
} else {
printf("Non-positive number\n");
}
return 0;
}

#2. Fortran:

• Fortran is one of the oldest imperative programming languages, primarily used in


scientific and numerical computing.
• It focuses on mathematical computations and provides features for low-level
control.
• Example code snippet in Fortran:

program main
integer :: x = 10
if (x > 0) then
print *, "Positive number"
else
print *, "Non-positive number"
end if
end program main

#3. Pascal:

• Pascal is an imperative programming language designed for teaching programming


concepts.
• It provides structured control flow constructs like loops, conditionals, and
subroutines.
• Example code snippet in Pascal:

program HelloWorld;
var
x: Integer;
begin
writeln('Enter a number: ');
readln(x);

Prepared by: Tesfay Gidey 18


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
if x > 0 then
writeln('Positive number')
else if x < 0 then
writeln('Negative number')
else
writeln('Zero');
end.

#4. Python (partially imperative):

• Python is a multi-paradigm language but includes imperative features.


• It supports procedural programming and imperative constructs like loops and
conditional statements.
• Example code snippet in Python:

x = 10
if x > 0:
print("Positive number")
else:
print("Non-positive number")
Demo for OOP: Java, C++, and Python.
#1. Java:
• Java is a widely used object-oriented programming language.
• It emphasizes the use of classes, objects, inheritance, and polymorphism.
• Example code snippet in Java:

public class Main {


public static void main(String[] args) {
int x = 10;
if (x > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
}
}
public class HelloWorld {
public static void main(String[] args) {
int x = 10;
if (x > 0) {
System.out.println("Positive number");
} else {
Prepared by: Tesfay Gidey 19
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
System.out.println("Non-positive number");
}
}
}

#2. Python:

• Python is a multi-paradigm language that supports object-oriented programming.


• It provides classes, objects, inheritance, and encapsulation.
• Example code snippet in Python:

class HelloWorld:
def __init__(self, x):
self.x = x

def check_number(self):
if self.x > 0:
print("Positive number")
else:
print("Non-positive number")

hello = HelloWorld(10)
hello.check_number()

#3. C++:

• C++ is a powerful object-oriented programming language.


• It supports classes, objects, inheritance, polymorphism, and templates.
• Example code snippet in C++:

#include <iostream>

class HelloWorld {
private:
int x;

public:
HelloWorld(int x) : x(x) {}

void checkNumber() {
if (x > 0)
std::cout << "Positive number\n";
else
std::cout << "Non-positive number\n";
Prepared by: Tesfay Gidey 20
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
}
};

int main() {
HelloWorld hello(10);
hello.checkNumber();
return 0;
}

#4. C#:

• C# is a modern object-oriented programming language developed by Microsoft.


• It provides features like classes, objects, inheritance, and interfaces.
• Example code snippet in C#:

using System;

class HelloWorld
{
private int x;

public HelloWorld(int x)
{
this.x = x;
}

public void CheckNumber()


{
if (x > 0)
Console.WriteLine("Positive number");
else
Console.WriteLine("Non-positive number");
}

static void Main(string[] args)


{
HelloWorld hello = new HelloWorld(10);
hello.CheckNumber();
}
}

Prepared by: Tesfay Gidey 21


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
1.5 Problem-solving process and software engineering
1.5.1 Software Engineering
Software engineering is a discipline that deals with the systematic approach to designing, developing, testing, and
maintaining software systems.

• It applies engineering principles, methods, and tools to create software solutions


that meet user needs and are reliable, scalable, and maintainable.

Given below are key aspects of software engineering:

1. Requirements Engineering:

• Requirements engineering involves capturing, analyzing, and documenting the


functional and non-functional requirements of a software system.
• It includes understanding user needs, defining system objectives, and specifying
the desired behaviors and capabilities of the software.

2. Software Design:

• Software design focuses on creating a blueprint or plan for the software system
based on the requirements.
• It involves defining the system architecture, component design, and detailed
specifications for modules and interfaces.
• Design decisions consider factors such as modularity, reusability, performance, and
maintainability.

3. Software Construction:

• Software construction involves the actual implementation of the software based on


the design.
• It includes writing code, integrating components, and following coding standards
and best practices.
• Software construction aims to produce clean, efficient, and reliable code that meets
the requirements and design specifications.

4. Software Testing:

• Software testing is a crucial phase in software engineering.


• It involves systematically executing test cases to identify defects, validate
functionality, and ensure the software performs as expected.
• Various testing techniques, such as unit testing, integration testing, system
testing, and acceptance testing, are employed to uncover and fix issues.

5. Software Maintenance:
Prepared by: Tesfay Gidey 22
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• Software maintenance involves managing and updating the software system after its
initial development and deployment.
• It includes bug fixing, performance enhancements, and incorporation of new features
or changes.
• Maintenance aims to ensure the software remains reliable, secure, and aligned with
evolving user needs.

6. Software Project Management:

• Software project management involves planning, organizing, and coordinating the


activities and resources required for successful software development.
• It includes tasks such as project planning, estimation, risk management, team
management, and communication with stakeholders.
• Effective project management ensures that software projects are delivered on time,
within budget, and according to quality standards.

7. Software Quality Assurance:

• Software quality assurance involves ensuring that the software meets specified
quality standards.
• It includes activities such as code reviews, quality audits, and adherence to coding
standards.
• Quality assurance helps identify and rectify issues early in the development process,
improving the overall quality of the software.

8. Software Documentation:

• Software documentation involves creating comprehensive and well-structured


documentation for the software system.
• It includes user manuals, technical specifications, design documents, and API
documentation.
• Documentation guides users, developers, and maintainers, aiding in understanding
and using the software effectively.

NB:
• Software engineering promotes a systematic and disciplined approach to software
development, aiming to deliver high-quality software solutions that are reliable,
maintainable, and aligned with user requirements.
• By following software engineering principles and best practices, organizations can
improve the efficiency, productivity, and success of their software projects.

Prepared by: Tesfay Gidey 23


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming

SDLC Diagram: This diagram illustrates the phases of the SDLC, which typically include stages like idea generation,
planning, market research & analysis, naming, mock-up & wireframing, design, development, testing, deployment,
and maintenance
1.5.2 Problem-solving process
Problem-solving in computer science refers to the process of finding solutions to complex
or challenging problems using computational techniques.

• It involves breaking down a problem into smaller, more manageable parts and devising
algorithms or methods to solve them.
• The two approaches to problem-solving processes are top-down and bottom-up.

1. Top-Down Approach:

• The top-down approach, also known as the deductive approach, involves starting with
a high-level overview of the problem and gradually breaking it down into smaller
subproblems.
• It follows a hierarchical structure where the main problem is divided into
subproblems, and each subproblem is further decomposed until the smallest manageable
units are reached.
• The focus is on understanding the problem domain, identifying the major components,
and designing the overall structure before diving into the implementation details.
• In the top-down approach, the emphasis is on planning, design, and abstraction. It
allows for a systematic and organized approach to problem-solving.

Advantages:

• Provides a clear understanding of the problem’s structure and components.


Prepared by: Tesfay Gidey 24
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• Promotes a systematic and organized approach to problem-solving.
• Allows for early identification of major issues and considerations.
• Supports the identification of reusable components and modular design.

Disadvantages:

• May require more upfront planning and analysis.


• Can be challenging when dealing with complex problems or unfamiliar domains.
• May lead to rigid designs that are difficult to modify or adapt later.

2. Bottom-Up Approach:

• The bottom-up approach, also known as the inductive approach, involves starting with
the smaller components or units and gradually building them up to form a complete
solution.
• It focuses on understanding the details and specific elements of the problem before
considering the higher-level structure.
• The bottom-up approach often involves implementing individual functions, methods,
or modules and then integrating them to form larger components and the final solution.
• It allows for incremental development, testing, and refinement of components,
leading to an iterative and evolutionary problem-solving process.

Advantages:

• Enables early implementation and testing of individual components.


• Supports an iterative and incremental development approach.
• Provides flexibility to adapt and modify designs based on evolving requirements.
• Can be effective for solving complex problems with uncertain requirements.

Disadvantages:

• This may result in a lack of overall structure or coherence until components are
integrated.
• This could lead to increased complexity if proper design and abstraction are not
considered.
• May require additional effort to ensure compatibility and integration between
components.
• The overall system design may be less apparent initially.

N.B:
• Both approaches have their merits and can be used in different situations.
• The choice between the top-down and bottom-up approaches depends on factors such as
the complexity of the problem, familiarity with the problem domain, available
Prepared by: Tesfay Gidey 25
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
resources, and the desired balance between upfront planning and flexibility during
development.
• In practice, a combination of top-down and bottom-up approaches may be employed to
achieve the best results.

1.6. Basic Program development tips


When designing a program in any programming language, there are several important factors
to consider. Key characteristics that a well-designed program should possess:

1. Correctness:

• The program should produce the correct output and behave as expected according to
the requirements and specifications.
• It should accurately solve the problem it was designed to address.

2. Readability:

• The code should be easy to read, understand, and maintain.


• Use clear and meaningful variable and function names, follow consistent indentation
and formatting conventions, and provide appropriate comments to make the code more
readable.

3. Modularity:

• The program should be divided into modular components, with each component
responsible for a specific task or functionality. This promotes code reusability,
and maintainability, and makes it easier to understand and debug.

4. Efficiency:

• The program should be designed to run efficiently, utilizing system resources


optimally.
• Consider algorithms and data structures that offer good performance characteristics.
• Avoid unnecessary computations, minimize memory usage, and optimize code where
possible.

5. Scalability:
— The program should be able to handle increasing workloads or larger datasets without
significant performance degradation. Design the program with scalability in mind,
considering factors such as data structures, algorithmic complexity, and potential
bottlenecks.

Prepared by: Tesfay Gidey 26


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
6. Robustness:

• The program should handle unexpected situations and errors gracefully.


• Implement proper error handling and exception management to prevent crashes and
provide informative error messages to aid in debugging and troubleshooting.

7. Extensibility:

• Design the program to be easily extendable and maintainable.


• Consider future requirements and potential changes to the system.
• Use abstraction and encapsulation to decouple components, making it easier to add
new features or modify existing ones without affecting the entire codebase.

8. Security:

• Consider security aspects when designing a program, especially if it involves


handling sensitive data or interacting with external systems.
• Implement proper authentication, authorization, and data encryption mechanisms to
protect against security vulnerabilities.

9. Testability:

• Design the program to be easily testable.


• Use unit tests, integration tests, and automated testing frameworks to verify the
correctness and functionality of the code.
• This helps catch bugs early and facilitates future modifications or refactoring.

10. Maintainability:

• Ensure that the program is maintainable over its lifecycle.


• Write clean and well-structured code, adhere to coding standards, and document the
code properly.
• This makes it easier for other developers to understand, modify, and maintain the
codebase.

By considering these characteristics during the program design phase, you can create a
well-structured and high-quality software solution in any programming language.

1.7 Algorithm designing and modeling the logic


An algorithm is a step-by-step procedure or a set of rules for solving a specific problem or accomplishing a
particular task.
It is a precise and unambiguous sequence of instructions that takes some inputs and produces desired outputs.

In computer science, algorithms are fundamental to writing programs and solving


computational problems.
Prepared by: Tesfay Gidey 27
Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
They serve as the building blocks for designing efficient and effective software solutions.

Algorithms can be expressed in various forms, including natural language, pseudocode,


flowcharts, or programming languages.

Some key characteristics of algorithms:


1. Input: An algorithm takes some input values or data as the initial information to work
with.

2. Output: An algorithm produces desired results, which are the expected outcomes or
solutions to the problem.

3. Well-defined steps: Algorithms consist of a series of well-defined steps or operations


that are executed in a specific order. Each step represents an unambiguous instruction.

4. Finiteness: Algorithms must terminate after a finite number of steps. They should not
run indefinitely or enter an infinite loop.

5. Determinism: Algorithms should produce the same output for a given set of inputs,
regardless of the system or environment in which they are executed.

6. Correctness: Algorithms should solve the problem correctly and produce the desired
output for all valid inputs.

7. Efficiency: Algorithms strive to be efficient, minimizing the use of resources such as


time, memory, or computational power. The efficiency of an algorithm is often analyzed in
terms of its time complexity and space complexity.

N.B:
• Algorithms can be categorized based on their approach or problem-solving technique,
such as searching, sorting, graph traversal, dynamic programming, and many others.
• Different algorithms may have different trade-offs in terms of their efficiency,
complexity, and suitability for specific problem domains.

1.7.1. Modeling a program's logic using flow chart

• An algorithm could be designed using many techniques and tools.


• One tool for designing algorithms is flowcharts.
• A flowchart is a graphical way of expressing the steps needed to solve a problem.
• A flow chart is a schematic (diagrammatic description) representation of a process.
• Basic flowcharting symbols are:

Prepared by: Tesfay Gidey 28


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming

E.g., Checking whether a number is odd/even.

Prepared by: Tesfay Gidey 29


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
1.8. Compilers and Interpreters
• Any program written in a language other than machine language needs to be translated
into machine language. The set of instructions that do this task are known as
translators.
• There are different kinds of translator software, among which compilers

and interpreters are of interest to most programmers.

Compilers: a compiler is a computer program that translates a series of statements written


in source code (a collection of statements in a specific programming language) into a
resulting object code (translated instructions of the statements in a programming language).

• A compiler changes or translates the whole source code into executable machine code
(also called object code) which is output to a file for later execution.
• Example: C++, Pascal, FORTRAN, etc.

Interpreters: is a computer program that translates a single high-level statement executes


it and then goes to the next high-level language line etc. E.g. QBASIC, Lisp, etc.

1.9. Mechanics of Creating a Program (C++)


• C++ programs typically go through five phases to be executed: these are

edit, preprocess, compile, link, load:

• Edit: this is accomplished with an editor program. The programmer types C++
statements with the editor and makes corrections if necessary.
• The program's source file is then stored on a secondary storage device such as a
disk with a “.cpp” file name.
• After the program is edited, C++ is principally compiled in three phases:
preprocessing, translation to object code, and linking (the last two phases are
what is generally thought of as the “compilation” process).
• Preprocess: In a C++ system, a preprocessor program executes automatically before
the compiler’s translation phase begins.
• The C++ preprocessor obeys a command called preprocessor directives, which indicates
that certain manipulations are to be performed on the program before compilation.
• The preprocessor is invoked by the compiler before the program is converted to
machine language.
• The C++ preprocessor goes over the program text and carries out the instructions
specified by the preprocessor directives (e.g., #include).
• The result is a modified program text that no longer contains any directives.
• Compile: Then, the C++ compiler translates the program code.

Prepared by: Tesfay Gidey 30


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming
• The compiler may be a true C++ compiler that generates native (assembly or machine)
code.
• The outcome may be incomplete due to the program referring to library routines that
are not defined as part of the program.
• For example, the << operator, which is defined in a separate IO library.
• Linking: C++ programs typically contain references to functions and data defined
elsewhere, such as in the standard libraries.
• The object code produced by the C++ compiler typically contains “holes” due to
these missing parts.
• A linker links the object code with the code for the missing function to produce an
executable image (with no missing pieces).
• Generally, the linker completes the object code by linking it with the object code
of any library modules that the program may have referred to.
• The final result is an executable file
• Loading: the loader takes the executable file from disk and transfers it to memory.
• Additional components from shared libraries that support the program are also loaded.
• Finally, the computer, under the control of its CPU, executes the program.

In practice all these steps are usually invoked by a single command and the user will not even see the
intermediate files generated.

N.B:
In summary, when we say that the object code produced by the C++ compiler contains “holes,” it means that
certain sections of the code are not yet fully resolved and will be filled during the linking stage to create a
complete executable.

Prepared by: Tesfay Gidey 31


Addis Ababa Science and Technology University, Department of Software Engineering
Fundamentals of C++ Programming

ADDIS ABAB SCIENCE AND


TECHNOLOGY UNIVERSITY

Worksheet 1
Course Title: Introduction to Programming / Fundamentals of Programming
Course No : Comp 4136

For each of the problems below, develop a flow chart

1) Receive a number and determine whether it is odd or even.


2) Obtain two numbers from the keyboard, and determine and display
which (if either) is the larger of the two numbers.
3) Receive 3 numbers and display them in ascending order from smallest to
largest
4) Add the numbers from 1 to 100 and display the sum
5) Add the even numbers between 0 and any positive integer numbergiven
by the user.
6) Find the average of two numbers given by the user.
7) Find the average, maximum, minimum, and sum of three numbersgiven
by the user.
8) Find the area of a circle where the radius is provided by the user.
9) Swap the contents of two variables using a third variable.
10) Swap the content of two variables without using a third variable.
11) Read an integer value from the keyboard and display a message
indicating if this number is odd or even.
12) Read 10 integers from the keyboard in the range 0 - 100, and count how
many of them are larger than 50, and display this result.
13) Take an integer from the user and display the factorial of that number

Prepared by: Tesfay Gidey 32


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Chapter Two
2. Variables, Data Types, and Operators

2.1 Introduction to the Basic Components of a C++


Program
In this lecture, we will explore the fundamental components of a simple program written in C++. By

examining the following code, we can gain a better understanding of these essential parts and their

roles in a C++ program.


Code Example 1:

#include <iostream>

int main() {
// Print a message to the console
std::cout << "This is a General Structure of a Simple C++ Program!" << std::endl;

// Return 0 to indicate successful program execution


return 0;
}

Now, let’s break down the different parts of this program:


1. #include <iostream>: This line includes the iostream header file, which provides

functionality for input and output operations.


• It allows us to use the std::cout and std::endl statements later in the program.

2. int main() { ... }: The main function is the entry point of every C++ program. It acts

as the starting point for program execution.


• In this example, the main function is defined as returning an integer (int) value. The empty

parentheses () indicate that this function does not take any arguments.

3. std::cout << “This is a General Structure of a Simple C++ Program!”" << std::endl;: This line

uses the std::cout object to output the message "This is a General Structure of a Simple C++

Program!" to the console.

Prepared by: Tesfay Gidey 33


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• The << operator is used to insert the message into the output stream. std::endl is used to

insert a newline character and flush the output stream.


4. return 0;: This statement indicates the end of the main function and returns the value 0 to the

operating system. A return value of 0 conventionally signifies that the program was executed

successfully.

5. Any C++ program file should be saved with a file name extension “.CPP ”

6. Type the program directly into the editor, and save the file as hello.cpp, compile it, and then run it.

It will print the words This is a General Structure of a Simple C++ Program on the

computer screen.

7. The first character is the #. This character is a signal to the preprocessor. Each time you start your

compiler, the preprocessor runs through the program and looks for the pound (#) symbols, and acts

on those lines before the compiler runs.

8. The ‘include’ instruction is a preprocessor instruction that directs the compiler to include a copy

of the file specified in the angle brackets in the source code.

9. If the path of the file is not specified, the preprocessor looks for the file under the

‘c:\tc\include\’ folder or in the ‘include’ folder of the location where the editor is stored.
N.B:
The main function is the starting point of the program, and it typically contains the code that you

want to execute.

Code Example 2:

#include<iostream.h>
#include<conio.h>

void main() {
cout << "\n Hello World!";
getch();
}

Prepared by: Tesfay Gidey 34


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

1. Header Inclusion:
The code starts with the inclusion of two header files: iostream.h and conio.h.

The iostream.h header file provides functionality for input and output operations, while

the conio.h header file contains functions for console input and output.

2. Main Function:
The program defines the main function as follows:

void main() {
// Code goes here
}

• The void keyword indicates that the function does not return a value.

• In older versions of C++, this was a valid way to define the main function, although it is no

longer recommended in modern C++ standards.

3. Output Statement:

Within the main function, the code uses the cout object to display the message "Hello World!" to the

console:

cout << "\n Hello World!";

The << operator is used to insert the message into the output stream, and the escape

sequence \n represents a newline character that adds a line break before the message is displayed.

4. Console Input:

Following the output statement, the getch() function is used to wait for a user input before the

program terminates. This function is part of the conio.h library and is commonly used to pause

program execution until a key is pressed.

Prepared by: Tesfay Gidey 35


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

2.2. A brief look at “cout” and “cin”


cout and cin are objects that are part of the iostream library in C++. They are used for output

(printing to the console) and input (reading from the console), respectively.

A brief explanation of cout and cin:

1. cout (Character Output):

cout is an object of the ostream class, which is used for output operations.

• It is associated with the standard output stream, typically the console, and is used to display

information to the user.

Example usage of cout:

#include <iostream>

int main() {
int number = 10;
std::cout << "The value of the number is: " << number << std::endl;
return 0;
}

• In this example, std::cout is used with the << (stream insertion) operator to display the

message "The value of the number is: " followed by the value of the number variable.

• The std::endl manipulator is used to insert a newline character and flush the output.

2. cin (Character Input):


cin is an object of the istream class, which is used for input operations.

• It is associated with the standard input stream, typically the console, and is used to read input

from the user.

Example usage of cin:

#include <iostream>

int main() {
int number;
Prepared by: Tesfay Gidey 36
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;
return 0;
}

• In this example, std::cin is used with the >> (stream extraction) operator to read an integer

input from the user and store it in the numbervariable.

• The user is prompted to enter a number using std::cout, and the entered number is displayed

back to the user using std::cout.

• It’s important to note that cout and cin are part of the standard library and do not require

any additional header inclusion beyond <iostream>.

• cout and cin used for output and input operations respectively.

• The iostream library provides many more features and functionalities for formatted

input/output, error handling, and more.

2.3 Comments on C++ programs


C++ comments are sections of code that are ignored by the compiler and serve as

explanatory or descriptive text within the source code.

• Comments are not executed as part of the program and do not affect the program’s

functionality.
• They are intended for human readers to understand the code better and provide additional

context or explanations.

• There are two types of comments in C++:


1. Single-line comments:
Use double slashes (//) to create single-line comments. Anything after the // on the same line will

be treated as a comment.

Prepared by: Tesfay Gidey 37


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

// This is a single-line comment

int number = 10; // Assigning a value to the 'number' variable

2. Multi-line comments:
• Enclose multi-line comments within /* and */ symbols.

• Everything between these symbols will be treated as a comment, even if it spans across multiple

lines.

/*
This is a multi-line comment.
It can span across multiple lines.
*/

int number = 10;


/*
Multiple lines of comments can be used to
provide detailed explanations of the code.
*/

3. Commenting out code:


• You can also use comments to temporarily disable or “comment out” a block of

code. This is useful when you want to exclude certain lines of code from being executed without

deleting them.

int number = 10;


// int anotherNumber = 20; // Commented out code

// Commented out code block


/*
for (int i = 0; i < 10; i++) {
// Do something
}
*/

// Only the 'number' variable will be executed

Prepared by: Tesfay Gidey 38


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

2.2 Overview of Functions


Functions in C++ are blocks of code that perform specific tasks. They help in organizing code

into modular units, making it more manageable, reusable, and easier to read.

Functions have a name, a set of parameters (optional), and a return type (optional).

• Below is an overview of functions in C++:


1. Function Declaration and Definition:
• A function is declared by specifying its name, return type, and parameters (if any), followed by

the function body, which contains the code to be executed.


Example:

int add(int a, int b) {


int sum = a + b;
return sum;
}

• In this example, the function add is declared with a return type of int and two

parameters a and b of type int.

• The function adds the values of a and b, stores the result in the variable sum, and returns it.

2. Function Call:
To execute a function, you need to call it by using its name followed by parentheses.

If the function has parameters, you pass the required arguments within the parentheses.

Example:

int result = add(5, 3); // Calling the add function with arguments 5 and 3

• In this example, the add function is called with arguments 5 and 3.

• The returned value, which is the sum of 5 and 3, is stored in the variable result.

Prepared by: Tesfay Gidey 39


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

3. Function Return:
• Functions can optionally return a value using the return statement.

• The return type specified in the function declaration determines the type of the value to be

returned.

Example:

int square(int x) {
return x * x;
}

• In this example, the square function takes an integer x as a parameter and returns the square

of x.
4. Function Parameters:
• Function parameters allow you to pass values or variables to the function for it to operate

on.

• Parameters are specified in the function declaration and used within the function body.

Example:

void greet(std::string name) {


std::cout << "Hello, " << name << "!" << std::endl;
}

• In this example, the greet function takes a name parameter of type std::string and prints a

greeting message with the provided name.

• Functions provide code reusability and allow you to break down complex tasks

into smaller, manageable parts.

• They promote modular and organized code structures, making it easier to

understand, test, and maintain your programs.

Prepared by: Tesfay Gidey 40


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Example 2: Second approach

void greet(const std::string& name) {


std::cout << "Hello, " << name << "!" << std::endl;
}

• In this example, the greet function takes a name parameter of type const std::string& (a

constant reference to a string) and prints a greeting message with the provided name.

The difference between the two code snippets above (Example 1 & 2) lies in the function

parameters:

1. `void greet(const std::string& name)`

• In this code, the `name` parameter is passed as a constant reference (`const std::string&`).

• By using a reference, the function avoids making a copy of the `name` argument, which can be

more efficient for large objects.

• Additionally, the `const` qualifier ensures that the `name` parameter cannot be modified within

the function.

• This version of the function is useful when you want to avoid unnecessary copying and

ensure that the original `name` argument remains unchanged.

2. `void greet(std::string name)`

• In this code, the `name` parameter is passed by value (`std::string`).

• This means that a copy of the `name` argument is made when the function is called.

• Any modifications made to the `name` parameter within the function will not affect the original

argument passed to the function.

• This version of the function is suitable when you need to modify or manipulate the `name`

parameter within the function without affecting the original argument outside the

function.

N.B:

The key difference between the two versions is that the second version (`const std::string&

name`) avoids unnecessary copying and ensures that the original argument remains
Prepared by: Tesfay Gidey 41
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

unchanged, while the first version (`std::string name`) creates a copy of the argument

and allows modifications to the parameter within the function.


Tips:
• Functions are typically invoked or called during the execution of a program after the program

has started running.

• Program commands are executed sequentially (line by line), following the order in which they

appear in the source code. However, when a function is encountered, the

program branches off to execute the function before continuing with the remaining

commands.

• Once a function completes its execution, it returns “control” to the line of code that

immediately follows the function call.

In programming, “control” refers to the flow of execution within a program. It determines

which statements or blocks of code are executed and in what order.

• Functions are composed of two main parts: the header and the body. The header consists of the

return type, function name, and parameters of the function.

• Parameters in a function allow values to be passed into the function.

• A parameter serves as a declaration that specifies the type and name of the value that

will be received by the function.

• On the other hand, the actual value provided by the calling function when it invokes or calls the

function is called an argument.

• Arguments are the concrete values that are passed to the function and assigned to the

corresponding parameters.

• Functions return either a value or void (i.e. they return nothing).


N.B
A function that adds two integers might return the sum, and thus would be defined to return an

integer value. But, a function that just prints a message has nothing to return and would be

declared to return void.

Prepared by: Tesfay Gidey 42


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• A function may return a value using a return statement; a return statement also causes the

function to exit.

• If there is no return statement at the end of a function, the function will automatically

return void.

Example:

#include<iostream.h>
#include<conio.h>

void main()
{
cout << "\n In main function";
demoFunction();
cout << "\n Back in main function";
getch();
}

void demoFunction()
{
cout << "\n demoFunction";
}

In this code, there are two functions: main() and demoFunction(). Here's what happens when the

program runs:

1. The main() function is the entry point of the program.

2. The statement cout << "\n In main function"; prints the message "In main function" on the

console.

3. The demoFunction() is called using the statement demoFunction();.

4. The program jumps to the demoFunction() and executes its code.

5. The statement cout << "\n demoFunction"; prints the message "demoFunction" on the console.

6. After the execution of demoFunction() completes, the program returns to the next line

in main().

7. The statement cout << "\n Back in main function"; is executed, printing the message "Back in

main function" on the console.


Prepared by: Tesfay Gidey 43
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

8. The getch() function is called, which waits for a key press before the program exits.
Remark:
The above code demonstrates the flow of control between the “main function” and a

separate function (“demoFunction”) when the program is executed.

2.5. Variables and Constants

2.5.1 Variables
• In C++, variables are fundamental building blocks used to store and manipulate data.
• They provide a means of storing values that can be accessed and modified throughout the

program.

• This lecture note will provide a detailed overview of variables in C++, including

their declaration, initialization, types, scope, and lifetime.

A variable is a named storage location in a computer’s memory that can hold a value of a specific

type. It acts as a container for data within a program, allowing the programmer to store,

manipulate, and access values during the execution of the program.

• Variables are used to represent and work with different types of data, such as numbers,

characters, or user-defined objects.

• They provide a way to store temporary or permanent data that can be used in calculations,

comparisons, or other operations within the program.

• Each variable has a unique identifier, known as its name, which is used to refer to and

access its stored value.

• The name must follow certain rules and conventions defined by the programming

language, such as starting with a letter and consisting of letters, digits, or

underscores.

• Variables can be declared with a specific type, specifying the kind of data they can hold,

such as integers, floating-point numbers, characters, or booleans.

• They can also be assigned an initial value at the time of declaration or later in the program.
Prepared by: Tesfay Gidey 44
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• Throughout the program’s execution, variables can be modified, reassigned, and

manipulated to store and process data dynamically.

• The value stored in a variable can be accessed and utilized in various parts of the

program, allowing for flexible and interactive programming.

All variables have three important properties:

- Data type: a type that is established when the variable is defined. For instance, integer, real,

character, etc. It describes the property of the data and the size of the reserved memory.

- Name: a name that will be used to refer to the value in the variable. A unique identifier for the

reserved memory location.

- Value: a value that can be changed by assigning a new value to the variable.

2.5.1.1. Fundamental Variable Types


• In C++, fundamental variable types are the building blocks for storing and manipulating

different kinds of data.

• This lecture note provides a comprehensive overview of the fundamental variable types in C++,

including integer types, floating-point types, character types, boolean types, and

void types.
1. Integer Types:
• Integer types represent whole numbers without fractional parts.
• C++ provides several integer types, including:

— `int`: represents signed integers.

— `short`: represents short signed integers.

— `long`: represents long signed integers.

— `long long`: represents long long signed integers.

• The range and size of these types depend on the specific implementation and the platform.

Prepared by: Tesfay Gidey 45


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

2. Floating-Point Types:
• Floating-point types represent numbers with a fractional part.

• C++ provides two floating-point types:


— float: represents single-precision floating-point numbers.

- double: represents double-precision floating-point numbers.

• Floating-point types offer greater precision and a wider range of values compared to integer

types.

3. Character Types:
• Character types represent individual characters and symbols.

• C++ provides two-character types:

— `char`: represents a single character.

— `wchar_t`: represents wide characters.

• Characters are represented using the ASCII or Unicode character encoding system.

• Character variables hold a single byte.

• They are used to hold 256 different characters and symbols of the ASCII and extended ASCII

character sets.

4. Boolean Type:
- The boolean type represents logical values, either `true` or `false`.

- In C++, the `bool` type is used for boolean variables.

- Boolean variables are commonly used in conditional statements and logical operations.

5. Void Type:
• The void type represents the absence of a value.

- It is primarily used as a return type for functions that do not return a value.

- Void variables cannot be declared, but void pointers are used to point to data of

unknown type.
Prepared by: Tesfay Gidey 46
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Table: C++ Variable Types and Storage Sizes with Value Ranges.

Remarks:
Integer types handle whole numbers, floating-point types handle decimal numbers, character

types handle individual characters, boolean types handle logical values, and the void-type

represents the absence of a value.

Prepared by: Tesfay Gidey 47


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

N.B
Understanding the fundamental variable types in C++ is crucial for effectively storing and

manipulating data in programs.

By utilizing these variable types appropriately, programmers can write robust and efficient

C++ programs to handle a wide range of data and operations.


2.5.1.2. Signed and Unsigned variable types
In C++, the terms “signed” and “unsigned” are used to specify the range and interpretation of integer

types.

1. Signed Types:

• Signed types can represent both positive and negative numbers, including zero.

• They use a sign bit to indicate the sign of the value.

• The most significant bit (MSB) is reserved as the sign bit, and the remaining bits store

the magnitude of the value.

• Examples of signed types include `char`, `int`, `long`, and `long long`.

• For example, a signed `char` can represent values from -128 to 127.

2. Unsigned Types:

• Unsigned types can only represent positive numbers or zero.

• They don’t use a sign bit, so all bits are used to represent the magnitude of the value.

• As a result, unsigned types can represent a larger range of positive values compared to their

signed counterparts.

• Examples of unsigned types include `unsigned char`, `unsigned int`, `unsigned long`, and

`unsigned long long`.

• For example, an unsigned `char` can represent values from 0 to 255.

When choosing between signed and unsigned types, consider the range and nature of the

data.

- Signed types are for values that can be positive or negative, while unsigned types are for values

that are always positive or zero.

Prepared by: Tesfay Gidey 48


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

- Mixing signed and unsigned types in expressions can lead to unexpected results due to

different interpretations of negative numbers.


Remark:
The magnitude of the largest number that can be stored in an unsigned integer of the same size is

equal to the magnitude of the largest positive number that can be stored in a signed integer.

However, it is important to note that signed integers allocate half of their range for negative

values, while unsigned integers allocate the entire range for positive values (including zero).

Let’s consider an example with an 8-bit integer type.

Signed integer (char):

• The range for a signed 8-bit integer (char) is from -128 to 127. The largest positive number that

can be stored is 127.

Unsigned integer (unsigned char):

• The range for an unsigned 8-bit integer (unsigned char) is from 0 to 255. The largest number

that can be stored is 255.

• As you can see, the magnitudes of the largest positive number in a signed integer (127) and the

largest number in an unsigned integer (255) are the same, despite the fact that the signed integer

has both positive and negative values within its range.

Example: Lets us have only 4 bits to represent numbers. See details @ [email protected].
1. Declaration and Initialization:
• Variables are declared by specifying their type and name.

• Declaration associates a name with a memory location that can hold a value of the specified

type.

• Variables can be initialized at the time of declaration or later in the program.

• Initialization assigns an initial value to a variable at the time of its creation.

Declaration and initialization are fundamental concepts in programming that

involve creating variables and assigning them initial values.

Prepared by: Tesfay Gidey 49


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Declaration refers to the act of introducing a variable to the program by specifying its name

and data type.

It informs the compiler or interpreter that a variable with a specific name and type will be used

in the program.
Example:

int num;

In this case, num is declared as an integer variable.

• Initialization, on the other hand, involves assigning an initial value to a declared variable at the

time of declaration.

• It sets the initial state or value of the variable. Initialization is optional, and if no initial value is

assigned, the variable will have an undefined value.


Example:

int num = 10;

Here, num is both declared and initialized with an initial value of 10.
Remarks:
1. Syntax:

• To declare a variable, you need to specify its data type and name using the following syntax:
`DataType VariableName;`.

• For example, to declare a float variable named `myIncome`, you would write: `float

myIncome;`.

• This informs the computer to reserve a memory location with the specified name and size for the

variable.

2. Memory Allocation:

• When you declare a variable, the computer sets aside memory to store its value.

Prepared by: Tesfay Gidey 50


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• The size of the memory allocated depends on the data type of the variable.

• For example, an `int` typically requires 4 bytes of memory.

3. Variable Naming:

• Good variable names are crucial for code readability and understanding.

• They should indicate the purpose or meaning of the variable. For example, `myIncome` is a

descriptive variable name that suggests it is used to store someone’s income.

• Meaningful and self-descriptive variable names make code more maintainable and easier to

comprehend.

4. Identifier Uniqueness:

• Each variable name is referred to as an identifier and should be unique within a program.

• You cannot have multiple variables with the same name within the same scope.

• For example, you can’t declare two variables as `float myIncome;` in the same block.

5. Reserved Keywords:

• Certain words in programming languages, known as reserved keywords, have predefined

meanings and cannot be used as variable names.

• These keywords are reserved for specific purposes in the language.

• For example, in C++, words like `int`, `if`, `for`, and `while` are reserved keywords and

cannot be used as identifiers.


Tips
By following proper naming conventions and understanding reserved keywords, you

can create meaningful and unique variable names, ensuring clarity and avoiding conflicts in

your code.

Prepared by: Tesfay Gidey 51


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Identifiers
• A valid identifier is a sequence of one or more letters, digits, or underscores. The length of an

identifier is not limited.

• Spaces and special characters (such as punctuation marks) cannot be part of an identifier.

• Variable identifiers should always begin with a letter or an underscore.

• They should not begin with a digit.

• Keywords (also known as reserved words) should not be used as names for identifiers.

Prepared by: Tesfay Gidey 52


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• C++ is case-sensitive. This means that lowercase and uppercase letters are considered

different.

• For example, the variable “Income” is not the same as the variable “income.”
3. Scope and Lifetime:
What is a Variable Scope?
Definition:

• Variable scope refers to the portion of code within which a variable is visible and can be

accessed.

• Scope determines the lifetime and visibility of variables, ensuring they are used correctly and do

not conflict with other variables in the program.

• Scope defines the region of the program where a variable is accessible.

• Variables can have local or global scope.


1. Local Scope:
• Local variables are declared inside a specific block of code, such as a function or loop.

• They are only accessible within the block they are declared in.

• Local variables have a limited lifetime and are destroyed once the block is exited.
2. Global Scope:
• Global variables are declared outside of any specific block, making

them accessible from anywhere in the program.

• Global variables have a longer lifetime and persist throughout the execution of the

program.

• Lifetime refers to the period during which a variable exists in memory.

Local variables have a limited lifetime and are created when their scope is entered and

destroyed when the scope is exited.

Global variables have a lifetime throughout the execution of the program.


Example:

Prepared by: Tesfay Gidey 53


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

#include <iostream>

int globalVariable = 10; // Global variable

void myFunction()
{
int localVariable = 20; // Local variable within the function

std::cout << "Inside myFunction:" << std::endl;


std::cout << "localVariable: " << localVariable << std::endl;
std::cout << "globalVariable: " << globalVariable << std::endl;
}

int main()
{
int localVariable = 30; // Local variable within the main function

std::cout << "Inside main:" << std::endl;


std::cout << "localVariable: " << localVariable << std::endl;
std::cout << "globalVariable: " << globalVariable << std::endl;

myFunction();

return 0;
}

In this example, we have both local and global variables. Here’s how the scope works:

• globalVariable is declared outside any function, making it a global variable. It is accessible

throughout the entire code.

• localVariable is declared within the main function, making it a local variable specific to

the main function's scope.

• localVariable is also declared within the myFunction function, making it a different local

variable specific to the myFunction function's scope.

• When the program runs, the main function is executed first. It prints the value of its local

variable (localVariable) and the global variable (globalVariable). Then, it calls

the myFunction function.

Prepared by: Tesfay Gidey 54


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• Inside the myFunction function, it prints the value of its local variable (localVariable) and the

global variable (globalVariable). These are separate variables from those in the main function.

The output of the program will be:

Inside main:
localVariable: 30
globalVariable: 10
Inside myFunction:
localVariable: 20
globalVariable: 10

2.5.1.6 User defined data type


User-defined data types offer a powerful way to structure and organize data, promoting

code reuse, abstraction, and maintainability. So, let’s delve into the world of user-defined

data types!
1. What are User-Defined Data Types?
• User-defined data types are data structures created by the programmer to represent a specific

entity or concept in a program.

• Unlike built-in data types (e.g., integers, floats), user-defined data types allow developers to

define their own data structures with custom properties and behaviors.
2. Benefits of User-Defined Data Types:
• Enhanced Code Organization:

User-defined data types help organize related data and operations together, improving code

structure and readability.

• Reusability:

Once defined, user-defined data types can be used in multiple parts of a program, promoting code

reuse and reducing redundancy.

• Abstraction:

User-defined data types allow programmers to abstract complex data structures, hiding

implementation details and providing a simplified interface for easier usage.

Prepared by: Tesfay Gidey 55


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

3. Creating User-Defined Data Types:


• Structs: Structs are a common form of user-defined data types that group together multiple

variables of different types under a single name. They provide a convenient way to represent

entities with multiple attributes.

• Classes: Classes, typically found in object-oriented programming languages, go beyond structs

by encapsulating data and associated functions (methods) into a cohesive unit.

• Classes support concepts like inheritance, polymorphism, and encapsulation.


4. Examples of User-Defined Data Types:
• Student Record:

Create a struct or class to represent a student record, including attributes such as name, ID, and

grade. Demonstrate how to create instances of the user-defined data type and access its attributes.

• Bank Account:

Define a class that represents a bank account, encapsulating properties like account number,

balance, and operations like deposit and withdrawal.


5. Encapsulation and Data Hiding:
• Encapsulation is a key principle in object-oriented programming, enabling the bundling of data

and methods together within a class.

• Data hiding (access modifiers) allows developers to control the accessibility of data and

methods, providing encapsulation and preserving the integrity of the user-defined data type.
6. Customizing User-Defined Data Types:
• Adding Member Functions: User-defined data types can have member functions (methods) that

operate on the data within the type. These functions can provide behavior and perform

operations specific to the data type.

• Overloading Operators: By overloading operators, user-defined data types can define custom

behavior for operators like +, -, *, etc., allowing intuitive and expressive operations on the data.
Remarks:
User-defined data types play a crucial role in designing and implementing well-

structured, reusable, and maintainable programs.


Prepared by: Tesfay Gidey 56
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

They enable developers to create custom data structures tailored to their specific needs,

providing organization, abstraction, and encapsulation.

By leveraging user-defined data types effectively, you can enhance code modularity, improve

code reuse, and build more robust and flexible software systems.
Example: Struct

#include <iostream>
#include <string>

struct Student {
std::string name;
int age;
float gpa;
};

int main() {
Student student1;
student1.name = "John";
student1.age = 20;
student1.gpa = 3.8;

std::cout << "Student Information:" << std::endl;


std::cout << "Name: " << student1.name << std::endl;
std::cout << "Age: " << student1.age << std::endl;
std::cout << "GPA: " << student1.gpa << std::endl;

return 0;
}

In this example, we define a user-defined data type Student using a struct. The struct contains

attributes such as name, age, and gpa. We then create an instance of the Student struct

called student1 and assign values to its attributes. Finally, we print the student's information.
Example: Class

#include <iostream>
#include <string>

class BankAccount {
private:
std::string accountNumber;
Prepared by: Tesfay Gidey 57
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
double balance;

public:
BankAccount(std::string accNum, double initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}

void deposit(double amount) {


balance += amount;
}

void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
} else {
std::cout << "Insufficient balance." << std::endl;
}
}

double getBalance() {
return balance;
}
};

int main() {
BankAccount account("123456789", 1000.0);

account.deposit(500.0);
std::cout << "Current balance: $" << account.getBalance() << std::endl;

account.withdraw(200.0);
std::cout << "Current balance: $" << account.getBalance() << std::endl;

account.withdraw(2000.0); // Insufficient balance


std::cout << "Current balance: $" << account.getBalance() << std::endl;

return 0;
}

• In this example, we define a user-defined data type BankAccount using a class.

• The class encapsulates the account number and balance as private data members. Public
member functions such as deposit, withdraw, and getBalance provide operations on the

data.

Prepared by: Tesfay Gidey 58


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• We create an instance of the BankAccount class called account and perform operations like

depositing, withdrawing, and retrieving the balance.


N.B:
User-defined data types, such as structs and classes, enable the creation of custom data

structures and operations, promoting abstraction and code organization in programming.

The presented examples demonstrate the practical implementation of user-defined data types to

define specific entities (e.g., student records, bank accounts) and their associated attributes

and behaviors.

• The `typedef` keyword allows a programmer to create an alias or alternative name for an

existing data type in a programming language.

• This feature is beneficial when there is a need to repeatedly use a complex or lengthy type

declaration, such as `unsigned short int`, for multiple variables in a program.

• In C++, the `typedef` keyword, which stands for “type definition,” enables the substitution of an

alias for such a declaration, improving code readability and reducing repetition.

#include <iostream>

typedef unsigned short int USHORT;

int main() {
USHORT width = 9;
USHORT height = 5;

USHORT area = width * height;

std::cout << "The area is: " << area << std::endl;

return 0;
}

• In this example, we use typedef to create an alias USHORT for the data type unsigned short

int. By doing so, we can use USHORT as a shorthand notation for unsigned short

int throughout the program.

Prepared by: Tesfay Gidey 59


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• Instead of repeatedly writing unsigned short int when declaring variables, we use USHORT.

This not only reduces the amount of code we need to write but also improves code readability

and maintainability.
• In the main function, we declare two variables width and height of type USHORT. We then

calculate the area by multiplying them together and storing the result in the area variable.

Finally, we print the area to the console.


Thanks to typedef, we can use USHORT as a more concise and descriptive alternative

to unsigned short int, making the code easier to understand and reducing the potential for

errors in type declarations.


2.5.1.7. Wrapping around in signed integers:
• Signed integers have both positive and negative values.

• When a signed integer reaches its maximum positive value and you increment it, it wraps

around to the largest negative value and continues counting back toward zero.

For example:

32767 + 1 = -32768

-32768–1 = 32767

-32768–8 = -32776

-32776–1 = 32767

And so on, until it reaches 0.


Remarks:
• The note explains the concept of wrapping around in signed integers.

• In this example, the maximum positive value that a signed integer can hold is 32767.

• When you add 1 to this maximum value, it wraps around to the largest negative value, which is -

32768.

• Similarly, when you subtract 1 from the largest negative value (-32768), it wraps around to the

maximum positive value (32767).

• The same principle applies when subtracting larger numbers.

Prepared by: Tesfay Gidey 60


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• For example, if you subtract 8 from -32768, it wraps around to -32776. And if you subtract 1

from -32776, it wraps around to 32767 again.

This wrapping-around behavior continues until the signed integer reaches 0, and the cycle repeats.
2.5.1.8. Wrapping around in unsigned integers:
• Unsigned integers only have positive values.

• When an unsigned integer reaches its maximum value and you increment it, it wraps around to

zero and continues counting from there.

For example:

65535 + 1 = 0

0–1 = 65535

0–8 = 65528

65528 + 1 = 65529

And so on, until it reaches 65535 again.


Remarks:
• The note explains the concept of wrapping around in unsigned integers.

• In this example, the maximum value that an unsigned integer can hold is 65535. When you add 1

to this maximum value, it wraps around to 0.

• Similarly, when you subtract 1 from 0, it wraps around to the maximum value (65535).

• The same principle applies when subtracting larger numbers.

• For example, if you subtract 8 from 0, it wraps around to 65528. And if you add 1 to 65528, it

wraps around to 65529.

This wrapping-around behavior continues until the unsigned integer reaches 65535 again, and the

cycle repeats.
2.5.1.10. Special Printing characters:
• In C++, there are special characters that are used for formatting purposes.

• These characters are represented by escape sequences, which start with a backslash (\) followed

by a specific character.

Prepared by: Tesfay Gidey 61


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• Some commonly used special printing characters are:

— \n: represents a new line.

— \t: represents a tab.

— \b: represents a backspace.

— \”: represents a double quote.

— \’: represents a single quote.

— \?: represents a question mark.

— \\: represents a backslash.

For example:

- “\n” is used to move the cursor to the beginning of the next line.

- “\t” is used to insert a tab space.

- “\b” is used to delete the previous character.

- “\”” is used to print a double quote character.

- “\’” is used to print a single quote character.

- “\?” is used to print a question mark character.

- “\\” is used to print a backslash character.


2.5.2.1. Defining constants
• The `#define` directive is used to define constants in C++.

• It performs a simple text substitution, where the defined constant is replaced with its

corresponding value during preprocessing.

• The `#define` directive can define any type of constant, but in our example, it defines an

integer constant.
Example 1: Defining constants with #define

#include <iostream>

#define studentPerClass 15

int main() {
int totalStudents = studentPerClass * 5;

Prepared by: Tesfay Gidey 62


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
std::cout << "Total students in 5 classes: " << totalStudents <<
std::endl;
return 0;
}

• In this example, we define a constant named studentPerClass using the #define directive with a

value of 15.

• When we use the identifier studentPerClass in the code, it gets replaced by the value 15

during preprocessing.

• In the main() function, we calculate the total number of students in 5 classes by

multiplying studentPerClass with 5.


2.5.2.2. The const keyword
• The `const` keyword is used to define constants in C++.

• Constants defined with `const` have a specific type, and the compiler enforces type checking

and ensures that the constant is used correctly.

• For example, `const unsigned short int studentPerClass = 15;` defines a constant named

`studentPerClass` with a type of `unsigned short int` and a value of 15.

• Using `const` allows for stronger type checking and can provide better compile-time error

detection.

• The constant value cannot be modified during program execution.


Example 2: Defining constants with the const keyword

#include <iostream>

const unsigned short int studentPerClass = 15;

int main() {
unsigned short int totalStudents = studentPerClass * 5;
std::cout << "Total students in 5 classes: " << totalStudents <<
std::endl;
return 0;
}

Prepared by: Tesfay Gidey 63


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Remarks
Both methods, `#define` and `const`, can be used to define constants in C++.

However, using `const` is generally considered more modern and preferable, as it provides better

type safety and is checked by the compiler.

That information you provided is correct. Here’s a summary of enumerated constants in C++:
2.5.3. Enumerated constants
• Enumerated constants are used to declare multiple integer constants using a single line with

different features.

• They allow programmers to define variables and restrict their values to a set of possible integer

values.

• The enum type can only take integer values.

• Enum types can be used to set up collections of named integer constants.

• The traditional way of defining integer constants was using `#define` directives, but an alternate

approach is to use the `enum` keyword.

• With `enum`, you can declare a group of constants without explicitly assigning values to each

one.

• For example, instead of using `#define` directives like `#define SPRING 0`, `#define SUMMER

1`, and so on, you can use `enum` to define them all in one line: `enum Season { SPRING,

SUMMER, FALL, WINTER };`

• By default, if you don’t assign explicit values, the first constant will have a value of 0, and the

subsequent constants will increment by 1.

• However, you can also assign different integer values to each constant explicitly.

• For example: `enum COLOR { RED = 100, BLUE, GREEN = 500, WHITE, BLACK };`

• In this case, RED will have a value of 100, BLUE will have a value of 101, GREEN will have a

value of 500, and so on.

Enumerated constants provide a way to define a set of named integer values and make the code

more readable and maintainable by using meaningful names instead of plain numbers.

Prepared by: Tesfay Gidey 64


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Example: Enumerated constants

#include <iostream>

enum Season { SPRING, SUMMER, FALL, WINTER };

int main() {
Season currentSeason = SPRING;

switch (currentSeason) {
case SPRING:
std::cout << "It's springtime!" << std::endl;
break;
case SUMMER:
std::cout << "It's summertime!" << std::endl;
break;
case FALL:
std::cout << "It's fall season!" << std::endl;
break;
case WINTER:
std::cout << "It's winter season!" << std::endl;
break;
default:
std::cout << "Invalid season!" << std::endl;
}

return 0;
}

• In this example, we declare a variable currentSeason of type Season and initialize it with the

value SPRING. We then use a if-else ladder to check the value of currentSeason and print a

corresponding message based on the season.


2.6. Setting aside memory/memory concept
• A computer provides Random Access Memory (RAM) for storing executable program code and

the data that the program manipulates.

• Memory can be viewed as a contiguous sequence of bits, with each bit capable of storing a binary

digit (0 or 1).

• Typically, memory is divided into groups of 8 consecutive bits, which are called bytes.
Prepared by: Tesfay Gidey 65
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• Each byte can store 8 bits or a single character.

• The bytes in memory are sequentially addressed, meaning each byte has a unique address.

• The address of a byte allows it to be accessed and manipulated by the computer’s processor or

other components.

• The size of memory is typically measured in bytes, kilobytes (KB), megabytes (MB), gigabytes

(GB), and so on, representing increasing powers of 2.

• Programs and data are stored in memory as a series of bytes, with the program code residing in

one part of memory and the data manipulated by the program stored in another part.

• The processor fetches instructions and data from memory during program execution, performs

computations, and stores results back into memory.

Memory can be conceptualized as a large array of bytes, where each byte has a unique

address, starting from the lowest address and incrementing sequentially.

Address: 0 1 2 3 4 5 6
7 ...
Data: 01010101 11001100 00110011 11110000 10101010 01010101 11111111
00000000 ...
Bits: 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 ...

Prepared by: Tesfay Gidey 66


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Understanding the concept of memory and how it is organized is crucial for developing and

understanding computer programs, as memory is where programs and data reside during

execution.
2.7. Expressions and Statements
• In C++, statements control the sequence of execution, evaluate expressions, or perform no

action (null statement).

• All C++ statements end with a semicolon, indicating the end of the statement.

• For example, `x = a + b;` is a statement that assigns the value of the sum of `a` and `b` to `x`.

• White spaces (spaces, tabs, new lines) in statements are generally ignored and not visible.

However, using white spaces can improve the readability and maintainability of programs.

• Blocks of code are enclosed within opening and closing curly braces ({ and }).

• Expressions are computations that yield a value. Essentially, any statement that evaluates to a

value is an expression.

• For example, the statement `3 + 2;` returns the value 5, making it an expression.

• Expressions can include variables, constants, mathematical operations, function calls, and more.

• Examples of expressions include `3.2` (returns the value 3.2), `PI` (returns the value 3.14 if the

constant is defined), and `secondsPerMinute` (an integer constant that returns 60 if declared).

• Complicated expressions can involve multiple operations and assignments, such as `x = a + b;`

and `y = x = a + b;`.

• In the expression `y = x = a + b;`, the evaluation order is as follows:

1. Add `a` to `b`.

2. Assign the result of the expression `a + b` to `x`.

3. Assign the result of the assignment expression `x = a + b` to `y`.

Understanding expressions and statements is fundamental in programming, as they form the

building blocks for executing logic and manipulating data in C++ programs.
2.8. Operators:
• An operator is a symbol that instructs the computer to perform a specific action or operation.

Prepared by: Tesfay Gidey 67


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• Operators in C++ act on one or more operands and can belong to different categories.

• C++ provides several categories of operators, including but not limited to:

— Assignment operators: Used to assign values to variables, such as the `=` operator.

— Arithmetic operators: Perform mathematical operations like addition, subtraction,

multiplication, division, and more. Examples include `+`, `-`, `*`, `/`.

— Relational operators: Compare the relationship between operands and return a Boolean

value (true or false). Examples include `<`, `>`, `<=`, `>=`, `==`, `!=`.

— Logical operators: Combine conditions and perform logical operations. Examples include

`&&` (logical AND), `||` (logical OR), `!` (logical NOT).

— Increment/decrement operators: Used to increment or decrement the value of variables.

Examples include `++` (increment), ` — ` (decrement).

— Conditional operator: Also known as the ternary operator (`?:`), it provides a shorthand

way to express conditional statements.

— Comma operator: Evaluates multiple expressions and returns the result of the last

expression.

— Size of operator: Returns the size of a data type or variable in bytes using the `sizeof`

operator.

— Explicit type casting operators: Used to convert values from one data type to another

explicitly.

Operators allow you to perform a wide range of operations, manipulate data, make decisions,

and control program flow.


2.8.1. Assignment Operator (=):
- The assignment operator (=) is used to assign a value to a variable.

- It causes the operand on the left side of the assignment statement to have its value changed to the

value on the right side of the statement.

- The syntax for the assignment operator is: Operand1 = Operand2;

- Operand1 is always a variable, and Operand2 can be a literal constant, a variable, or an expression.

Prepared by: Tesfay Gidey 68


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

— Example: x = 12; // Assigns the value 12 to x

x = y; // Assigns the value of y to x

x = y + 2; // Assigns the result of y + 2 to x


2.8.1.1. Compound Assignment Operators
• (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=)

• Compound assignment operators combine the assignment operator with other operators like

arithmetic and bitwise operators.

• They provide a shorthand way of performing an operation and assigning the result back to the

variable.

• For example:

— value += increase; is equivalent to value = value + increase;

— a -= 5; is equivalent to a = a — 5;

— a /= b; is equivalent to a = a / b;

— price *= units + 1; is equivalent to price = price * (units + 1);

- Similar compound assignment operators exist for other arithmetic and bitwise operations.
2.8.2. Arithmetic Operators (+, -, *, /, %)
• Arithmetic operators are used to perform mathematical operations on operands.

• Except for the remainder or modulo operator (%), all other arithmetic operators can accept a

mix of integers and real operands.

• When both operands of the division operator (/) are integers, the division is performed as an

integer division, resulting in an integer outcome.

• Integer division does not round off to the next integer.

— Example: 9 / 2 gives 4 (not 4.5)

-9 / 2 gives -4 (not -4.5)

• To obtain a real division when both operands are integers, you can cast one of the operands to be

real.

Prepared by: Tesfay Gidey 69


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• Example: int cost = 100;

int volume = 80;

double unitPrice = cost / (double)volume;

- The modulus operator (%) gives the remainder of the division of two integer values.

— Example: 13 % 3 gives 1
2.8.3. Relational Operators (==, !=, >, <, >=, <=)
- Relational operators are used to compare the relationship between two expressions.

- The result of a relational operator is a Boolean value (true or false) based on the comparison result.

- Examples: (7 == 5) returns false (or 0)

(5 > 4) returns true (or 1)

- The operands of a relational operator must be evaluated to a number. Characters are valid operands

since they are represented by numeric values.

— Example: ‘A’ < ‘F’ returns true (or 1) because ‘A’ has a smaller ASCII value than ‘F’.
2.8.4. Logical Operators (!, &&, ||)
• Logical operators are used to combine and manipulate logical values (true or false).

• The logical negation operator (!) negates the logical value of its operand.

• The logical AND operator (&&) produces 0 if one or both of its operands evaluate to 0;

otherwise, it produces 1.

• The logical OR operator (||) produces 0 if both of its operands evaluate to 0; otherwise, it

produces 1.

• Non-zero values represent logical true, while zero represents logical false in C++.
2.8.5. Increment/Decrement Operators (++ and — )
- The increment (++) and decrement ( — ) operators are used to add or subtract 1 from a numeric

variable.

- The prefix form (++var) increments the value before using it in an expression.

- The postfix form (var++) increments the value after using it in an expression.

- Prefix and postfix operators cannot be used together on a single variable.

- The choice between prefix and postfix operators can make a difference in complex statements.
Prepared by: Tesfay Gidey 70
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

2.8.6. Conditional Operator (?:)


- The conditional operator (?:) takes three operands and provides a shorthand way of expressing

conditional statements.

- The first operand is a relational expression that is evaluated.

- If the result is non-zero (true), then the second operand is chosen as the final result; otherwise, the

third operand is chosen.

- Example: Z = (X < Y ? X : Y)

— If X is less than Y, the value of X will be assigned to Z; otherwise, the value of Y will be assigned to

Z.

#include <iostream>

int main() {
int m = 1, n = 2, min;
min = (m < n ? m : n);

std::cout << "min: " << min << std::endl;

int result = (7 == 5 ? 4 : 3);


std::cout << "result: " << result << std::endl;

return 0;
}

2.8.7. Comma Operator (,):


- The comma operator (,) allows multiple expressions to be evaluated sequentially in a single

statement.

- The comma operator evaluates each expression from left to right and returns the value of the last

expression.

- It is commonly used in for loops and function calls.


Example 1:

Prepared by: Tesfay Gidey 71


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

int a = 1, b = 2, c = 3;
int result = (a += 1, b += 2, c += 3); // result = 6

Example 2:

#include <iostream>

int main() {
int m, n, min;
int mCount = 0, nCount = 0;

// Prompt the user to enter values for m and n


std::cout << "Enter the value of m: ";
std::cin >> m;
std::cout << "Enter the value of n: ";
std::cin >> n;

// Perform the conditional operation and assign the result to min


min = (m < n ? (mCount++, m) : (nCount++, n));

// Print the values of min, mCount, and nCount


std::cout << "min: " << min << std::endl;
std::cout << "mCount: " << mCount << std::endl;
std::cout << "nCount: " << nCount << std::endl;

return 0;
}

• In this program, the main() function declares integer variables m, n, and min. It also

declares mCount and nCount and initializes them to 0.

• The user is prompted to enter values for m and n using std::cin.

• The line min = (m < n ? (mCount++, m) : (nCount++, n)); performs a conditional

operation using the ternary operator ? :. If m is less than n, mCount++ is evaluated

(increments mCount by 1) and the value of m is assigned to min. Otherwise, nCount++ is

evaluated (increments nCount by 1) and the value of n is assigned to min.

• Finally, the values of min, mCount, and nCount are printed to the console using std::cout.

Prepared by: Tesfay Gidey 72


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

• When you run this program, it will prompt you to enter values for m and n. After entering the

values, it will print the values of min, mCount, and nCount based on the conditional operation.

• Note: The input values for m and n will affect the outcome of the conditional operation, which in

turn affects the values of min, mCount, and nCount.


2.8.8. sizeof() Operator
• The sizeof() operator is used to determine the size of a data item or type in bytes.

• It takes a single operand, which can be a data type, a variable, or a constant, and returns the size

of that entity in bytes.

• The result of the sizeof() operator is implementation-dependent and may vary based on the

platform and compiler.

• Example:

• int a = sizeof(char); // The size of a char is typically 1 byte

• int b = sizeof(int); // The size of an int depends on the platform (usually 4 bytes)

• int c = sizeof(1.55); // The size of a double constant is typically 8 bytes


2.8.9. Explicit Type Casting Operators
• Type casting operators allow you to convert a value of one data type to another data type

explicitly.

• In C++, there are several type casting operators:

• static_cast: Performs conversions between compatible types during compile-time.

• dynamic_cast: Performs type conversions and checks if the conversion is valid in the case of

polymorphic types.

• reinterpret_cast: Performs low-level conversions between unrelated types by reinterpreting the

bit pattern.

• const_cast: Modifies the const or volatile qualifiers of a variable.

Example:

#include <iostream>

int main() {
Prepared by: Tesfay Gidey 73
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
int i;
float f = 3.14;
i = static_cast<int>(f);

std::cout << "i: " << i << std::endl;

return 0;
}

• In this program, the main() function declares an integer variable i and a float

variable f initialized with the value 3.14. The static_cast<int>(f) statement performs the

type casting, converting the float value f to an integer. The result is then assigned to i.

• Finally, the value of i is printed to the console using std::cout.

Type casting allows you to control the conversion between different data types and is useful in

situations where you need to explicitly convert values to perform specific operations or

assignments.
2.9 Operator Precedence.
• The order in which operators are evaluated in an expression is significant and is determined by

precedence rules.

• Operators in higher levels take precedence over operators in lower levels.

• Operator precedence determines the order in which operators are evaluated in an expression.

Precedence Operator Description


--------------------------------------------------
Highest
--------------------------------------------------
1 () Parentheses (grouping)
2 ++, -- Postfix increment and decrement
. Member access (dot)
-> Member access (arrow)
[] Array subscripting
() Function call
(type) Type casting
3 ++, -- Prefix increment and decrement
+, - Unary plus and minus
! Logical NOT
~ Bitwise NOT
* Dereference (indirection)
Prepared by: Tesfay Gidey 74
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
& Address-of
sizeof Size of type
new, new[] Dynamic memory allocation
delete, delete[] Dynamic memory deallocation
4 *, /, % Multiplication, division, modulus
5 +, - Addition, subtraction
6 <<, >> Bitwise shift left, shift right
7 <, <=, >, >= Relational less than, less than or
equal to, greater than, greater than or equal to
8 ==, != Relational equals, not equals
9 & Bitwise AND
10 ^ Bitwise XOR
11 | Bitwise OR
12 && Logical AND
13 || Logical OR
14 ?: Ternary conditional
15 =, +=, -=, *=, /=, %= Assignment operators
16 , Comma (separates expressions)
Lowest

• Operators with higher precedence are evaluated before operators with lower precedence. In case

of equal precedence, the associativity of the operators determines the evaluation order.
• For example, in the expression a + b * c, the multiplication * has higher precedence than

addition +, so b * c is evaluated first.

• It’s important to note that parentheses ( ) can be used to explicitly specify the evaluation order

and override the default precedence rules.

Precedence Table:

Level | Operator | Order


----------------------------------------
1 | () | Left to right
| [] | Left to right
| . | Left to right
| -> | Left to right
| () | Left to right
| (type) | Left to right
----------------------------------------
2 | ++, -- | Right to left
| +, - | Right to left
| ! | Right to left
| ~ | Right to left
| * | Right to left
Prepared by: Tesfay Gidey 75
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
| & | Right to left
| sizeof | Right to left
| new, new[] | Right to left
| delete, delete[] | Right to left
----------------------------------------
3 | *, /, % | Left to right
----------------------------------------
4 | +, - | Left to right
----------------------------------------
5 | <<, >> | Left to right
----------------------------------------
6 | <, <=, >, >= | Left to right
----------------------------------------
7 | ==, != | Left to right
----------------------------------------
8 | & | Left to right
----------------------------------------
9 | ^ | Left to right
----------------------------------------
10 | | | Left to right
----------------------------------------
11 | && | Left to right
----------------------------------------
12 | || | Left to right
----------------------------------------
13 | ?: | Right to left
----------------------------------------
14 | =, +=, -=, *=, /=, %= | Right to left
----------------------------------------
15 | , | Left to right

Example: Demonstrate the associativity and evaluation order of operators with the same

precedence.

#include <iostream>

int main() {
int a = 5;
int b = 7;
int c = 3;

int result1 = a + b - c;
int result2 = a - b + c;

std::cout << "Result 1: " << result1 << std::endl;

Prepared by: Tesfay Gidey 76


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
std::cout << "Result 2: " << result2 << std::endl;

return 0;
}

Example: Demonstrate the associativity and evaluation order of operators with right-to-

left associativity:

#include <iostream>

int main() {
int a = 5;
int b = 2;

int result1 = a--;


int result2 = --b;

std::cout << "Result 1: " << result1 << std::endl;


std::cout << "Result 2: " << result2 << std::endl;

return 0;
}

• We then evaluate two expressions:


1. a--: This expression uses the postfix decrement operator --, which has right-to-left

associativity. The -- operator decrements the value of a but returns the original value before the

decrement. So, a-- evaluates to 5, and then the value of a is decremented to 4. The final value,

5, is assigned to result1.

2. --b: This expression uses the prefix decrement operator --, which also has right-to-left

associativity. The -- operator decrements the value of b and returns the decremented value.

So, --b evaluates to 1, and the value of b is updated to 1 as well. The final value, 1, is assigned

to result2.

Prepared by: Tesfay Gidey 77


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Exercise:

#include <iostream>

int main() {
int a, b, c, d;

// Example 1
a = b + c * d;
std::cout << "Example 1 - Result: " << a << std::endl;

// Example 2
a = (b + c) * d;
std::cout << "Example 2 - Result: " << a << std::endl;

// Example 3
a = b += c;
std::cout << "Example 3 - Result: " << a << std::endl;

return 0;
}
Example 1 - Result: <result of b + c * d>
Example 2 - Result: <result of (b + c) * d>
Example 3 - Result: <result of b += c>

Prepared by: Tesfay Gidey 78


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

ADDIS ABAB SCIENCE AND


TECHNOLOGY UNIVERSITY

Worksheet 2
Course Title: Introduction to Programming / Fundamentals of Programming
Course No : Comp 4136

For each of the problems write a C++ code to perform the required task. Your
program should be based on the flow chart you drawn in the first worksheet.

1) Receive a number and determine whether it is odd or even.


2) Obtain two numbers from the keyboard, and determine and display
which (if either) is the larger of the two numbers.
3) Receive 3 numbers and display them in ascending order from smallest to
largest
4) Add the numbers from 1 to 100 and display the sum
5) Add the even numbers between 0 and any positive integer numbergiven
by the user.
6) Find the average of two numbers given by the user.
7) Find the average, maximum, minimum, and sum of three numbersgiven
by the user.
8) Find the area of a circle where the radius is provided by the user.
9) Swap the contents of two variables using a third variable.
10) Swap the content of two variables without using a third variable.
11) Read an integer value from the keyboard and display a message
indicating if this number is odd or even.
12) read 10 integers from the keyboard in the range 0 - 100, and count how
many of them are larger than 50, and display this result
13) Take an integer from the user and display the factorial of that number

Prepared by: Tesfay Gidey 1


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Chapter 3: Program Control Structures


Flow control is a fundamental concept in programming that allows programmers to control the order in which
instructions or statements are executed in a program. Here are some key points related to flow control:
• A running program spends all of its time executing instructions or statements in that program. The
program’s execution follows a specific flow, which determines the order in which statements are
executed.
• The order in which statements in a program are executed is called the flow of the program. By controlling
the flow, programmers can determine which instructions are executed and in what sequence.
• Flow control allows programmers to make decisions and control the execution path of a program. This
control can be achieved through branching statements, such as if-else statements or switch statements,
which enable different code paths to be taken based on certain conditions.
• The currently executing statement has control of the CPU, and when it completes, control is handed over
to another statement. This concept is often referred to as the flow of control.
• By default, the flow of control in a program is sequential, meaning statements are executed one after
another in the order they appear. However, branching statements and loops (repetition) allow for
deviations from the sequential flow.
• Branching statements, like if-else statements and switch statements, enable the program to take different
paths based on certain conditions. This allows for more flexible and dynamic execution based on specific
requirements or inputs.
• Loops, or repetition structures, allow a block of statements to be executed repeatedly until a certain
condition fails. This allows for efficient execution of repetitive tasks and simplifies the code by
eliminating the need to write the same statements multiple times.
Flow control is a powerful concept in programming, as it enables the programmer to have control over the
execution of the program, make decisions based on conditions, and repeat code as needed.
• The program control structure refers to the organization and flow of statements in a program.
• It determines how the program’s instructions are executed and how the program responds to different
conditions.
There are three main types of program control structures: sequential, selection, and iteration.
1. Sequential Control Structure:
• In the sequential control structure, statements are executed in the order they appear in the program, one
after another.
• This is the default control structure, and it represents the basic flow of control where each statement is
executed once and then the control moves to the next statement.

#include <iostream>

int main() {
// Sequential execution of statements
int a = 5;
int b = 10;
int sum = a + b;

std::cout << "The sum of a and b is: " << sum << std::endl;

return 0;
}

Prepared by: Tesfay Gidey 2


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
• In this example, the statements are executed sequentially. The variables a and b are defined, and their sum
is stored in the variable sum. Finally, the sum is printed to the console.
2. Selection Control Structure:
• The selection control structure allows the program to make decisions based on certain conditions. It
provides the ability to choose between different paths of execution.
• The most common selection structure is the if-else statement, which allows the program to execute
different blocks of code based on the evaluation of a condition.
• Other selection structures include switch statements and conditional expressions.
The most commonly used selection control structures in programming are:
1. if-else statement:
The if-else statement allows the program to decide between two possible blocks of code based on a condition.
If the condition evaluates to true, the code within the if block is executed. If the condition is false, the code
within the else block (if present) is executed.
Example:

int number = 10;


if (number > 0) {
std::cout << "Number is positive." << std::endl;
} else {
std::cout << "Number is non-positive." << std::endl;
}

2. switch statement:
• The switch statement provides a way to select one of many code blocks to be executed based on the value
of an expression or variable.
• It allows for multi-way branching.
• The switch statement is a selection control flow statement in C++ that allows for selecting between a set
of alternatives based on the value of an expression.
• The general form of the switch statement is:

switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
case value3:
// Code to be executed if expression matches value3
break;
// ...
default:
// Code to be executed if expression does not match any case
break;
}

Prepared by: Tesfay Gidey 3


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
The switch statement consists of the following components:
1. switch: The keyword that initiates the switch statement.
2. expression: An expression or variable whose value is being evaluated to determine the path of execution.
3. case: Each case represents a possible value that the expression can match. If the expression matches a
specific case value, the corresponding code block following that case is executed.
4. default: The optional default case is used when the expression does not match any of the defined cases. It
provides a default code block to be executed in such cases.
5. break: After executing the code block associated with a matching case, the break statement is used to exit
the switch statement. Without the break statement, execution would continue into the next case block,
leading to unintended behavior.
Remarks:
• The default and break components are optional. The default case is executed only when none of the cases
match the expression value.
• The break statement is used to exit the switch statement after executing the code block of the matching
case.
• It’s important to include the break statement after each case block to avoid fall-through behavior, where
execution continues into subsequent case blocks even if their conditions are not met.
• The switch statement provides a structured and concise way to handle multiple choices and execute
different code blocks based on the value of an expression.

Example:

int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
break;
}

Remarks:
• The expression within the switch statement is referred to as the switch tag. It is the value that is being
evaluated to determine the matching case.

Prepared by: Tesfay Gidey 4


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
• The constants preceding each case are called case labels. They represent the possible values that
the switch tag can match.
• The output of the expression used as the switch tag should always be a constant value, as the case labels
are constants.
• The evaluation of the switch tag is done once, and the resulting constant value is then compared to each
case label in the order they appear until a match is found.
• The comparison of the switch tag with the case labels is based on equality. Only if there is an exact match
between the switch tag and a case label, the corresponding case block be executed
• Each case block may contain zero or more statements, allowing for multiple statements to be executed
when a case is satisfied.
• Execution continues after a matching case is found until a break statement is encountered or until all
intervening statements are executed.
• This behavior is often referred to as “fall-through.” If a break statement is encountered, it exits the switch
statement, preventing the execution of subsequent case blocks.
It’s important to note that without a break statement, execution will continue into the next case block,
potentially leading to unintended behavior.
The break statement is crucial for controlling the flow of execution within the switch statement.
3. conditional operator (ternary operator):
The conditional operator provides a compact way to make decisions based on a condition. It has the form
`condition? expression1: expression2`. If the condition is true, the value of expression1 is returned; otherwise,
the value of expression2 is returned.

Example:

int number = 7;
std::string result = (number % 2 == 0) ? "Even" : "Odd";
std::cout << "The number is " << result << std::endl;

• These selection control structures allow programmers to control the flow of a program based on
conditions and make decisions accordingly.
• By utilizing these structures, programs can handle different scenarios and execute specific blocks of code
based on the evaluated conditions.
The “if” statement in C++ has different forms that allow for various conditional branching scenarios. Here are
the different forms of the “if” statement:
1. Simple “if” statement:
The simple “if” statement is the most basic form of conditional branching. It executes a block of code if a
specified condition is true.

Prepared by: Tesfay Gidey 5


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Syntax:

if (condition) {
// Code to be executed if the condition is true
}

Example:

int num = 5;
if (num > 0) {
std::cout << "The number is positive." << std::endl;
}

2. “If-else” statement:
The “if-else” statement provides a way to execute one block of code if a condition is true and another block of
code if the condition is false.

Syntax:

if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

Example:

int num = -2;


if (num > 0) {
std::cout << "The number is positive." << std::endl;
} else {
std::cout << "The number is non-positive." << std::endl;
}

2. “If-else if” statement:


The “if-else if” statement allows for multiple conditions to be checked in sequence. It executes different blocks
of code based on the evaluation of each condition.

Prepared by: Tesfay Gidey 6


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

Syntax:

if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}

Example:

int num = 0;
if (num > 0) {
std::cout << "The number is positive." << std::endl;
} else if (num < 0) {
std::cout << "The number is negative." << std::endl;
} else {
std::cout << "The number is zero." << std::endl;
}

4. Nesting If statements within another if statement

• Nesting “if” statements within another “if” statement is a common practice in programming.

• It allows for more complex decision-making and branching based on multiple conditions.

• This is achieved by placing one “if” statement inside the block of code executed when another “if”

statement’s condition is true.

Example:

#include <iostream>

int main() {
// Nesting if statements example
int num = 10;

if (num > 0) {
std::cout << "Number is positive." << std::endl;

if (num % 2 == 0) {
std::cout << "Number is even." << std::endl;
} else {
std::cout << "Number is odd." << std::endl;
}
Prepared by: Tesfay Gidey 7
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
} else {
std::cout << "Number is non-positive." << std::endl;
}

return 0;
}

3. Iteration Control Structure:


• The iteration control structure, also known as looping or repetition, allows a block of code to be
executed repeatedly until a specific condition is met.
• It provides a way to automate repetitive tasks and to iterate over a set of data or perform a specific action a
certain number of times.
• Common iteration structures include for loops, while loops, and do-while loops.
By combining these control structures, programmers can create complex and dynamic programs that can
respond to different conditions, make decisions, and repeat actions as needed.
The choice of control structures and their arrangement greatly influences the program’s behavior and
functionality, allowing for efficient and flexible program execution.
Repetition statements, also known as loops, allow a block of code to be executed repeatedly for a fixed
number of times or until a certain condition fails.
In C++, there are three main repetition statements:
1. The for statement or loop:
• The for loop is used when the number of iterations is known in advance.
• It consists of three parts: initialization, condition, and update.
• The syntax of the for loop is as follows:

for (initialization; condition; update) {


// Code to be executed in each iteration
}

• The initialization step is performed only once at the beginning.


• The condition is checked before each iteration, and if it evaluates to true, the code block is executed.
• After each iteration, the update step is performed. If the condition eventually becomes false, the loop
terminates.
2. The while statement or loop:
• The while loop is used when the number of iterations is not known in advance, but the loop should
continue as long as a certain condition is true.
• The syntax of the while loop is as follows:

Prepared by: Tesfay Gidey 8


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++

while (condition) {
// Code to be executed in each iteration
}

• The condition is checked before each iteration, and if it evaluates to true, the code block is executed. If the
condition becomes false, the loop terminates.
3. The do…while statement or loop:
• The do…while loop is similar to the while loop, but the condition is checked at the end of each iteration.
• This ensures that the code block is executed at least once, even if the condition is initially false.
• The syntax of the do…while loop is as follows:

do {
// Code to be executed in each iteration
} while (condition);

• The code block is executed first, and then the condition is checked. If the condition evaluates to true, the
loop continues.
• If the condition becomes false, the loop terminates.
4. Pitfalls in writing repetition statements
1. Infinite loop:
• An infinite loop is a loop that continues executing indefinitely without ever terminating.
• This can happen if the loop condition is always true or if the loop control variables are not properly
updated.
• It is important to ensure that the loop will eventually terminate.
• Examples of infinite loops:

Example 1:

int product = 0;
while (product < 50)
product *= 5;

Example 2:

int counter = 1;
while (counter != 10)
counter += 2;

Remarks:
Prepared by: Tesfay Gidey 9
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
• To avoid infinite loops, ensure that the loop condition eventually becomes false or include appropriate
control statements, such as break or return, within the loop to exit under certain conditions.
2. Off-By-One Bugs (OBOB):
• Off-By-One bugs occur when the loop executes one too many or one too few times due to incorrect loop
conditions or variable updates.
• These errors are quite common and can lead to unexpected behavior.

Example:

int count = 1;
while (count < 10) {
// Code executed in each iteration
count++;
}

• In this example, the loop condition count < 10 is expected to execute the loop body 10 times.
• However, since count is initialized to 1, the loop body is executed only 9 times. This is an Off-By-One
bug.
5. Types of Loops
1. Count-controlled loops:
• Count-controlled loops repeat a statement or block a specified number of times.
• They consist of an initialization of the loop control variable, an expression to test if the desired number of
repetitions has been completed, and an update of the loop control variable with each iteration.
2. Event-controlled loops:
• Event-controlled loops repeat a statement or block until a condition within the loop body changes, causing
the repetition to stop.
• There are three types of event-controlled loops:
1. Sentinel controlled: The loop continues processing data until a special value, which is not a possible
data value, is entered to indicate that processing should stop.
2. End-of-file controlled: The loop continues processing data as long as there is more data in the file.
3. Flag controlled: The loop continues processing data until the value of a flag changes within the loop
body.
3. The continue and break statements:
1. The continue statement
• The continue statement terminates the current iteration of a loop and jumps to the next iteration.
• It is an error to use the continue statement outside of a loop.
• In a while or do…while loop, the next iteration starts from the loop condition.
• In a for loop, the next iteration starts from the loop’s fifth expression.

#include <iostream>

int main() {
for (int n = 10; n > 0; n--) {
Prepared by: Tesfay Gidey 10
Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
if (n == 5)
continue;
std::cout << n << ",";//The number 5 will be skipped due to the continue
statement.
}

return 0;
}

- When the continue statement appears inside nested loops, it applies to the loop immediately enclosing it, not
to the outer loops.
Example:

#include <iostream>

int main() {
bool more = true;
int i, n, num;

while (more) {
std::cout << "Enter the value of 'n': ";
std::cin >> n;

for (i = 0; i < n; i++) {


std::cout << "Enter a number: ";
std::cin >> num;

if (num < 0)
continue;

// Rest of the code for processing the number


std::cout << "Entered number: " << num << std::endl;
}

std::cout << "Do you want to continue? (1 - Yes, 0 - No): ";


std::cin >> more;
}

return 0;
}

• In this implementation, the program prompts the user to enter the value of n, which determines the number
of iterations for the inner loop. Within the inner loop, the user is prompted to enter a number.
• If the number is less than 0, the continue statement skips the rest of the code inside the loop and moves to
the next iteration. If the number is greater than or equal to 0, the program performs the desired processing
for the number (in this case, simply printing it).
• After completing the inner loop, the program asks the user if they want to continue. If the user enters 1,
the outer loop continues, and the process repeats. If the user enters 0, the program exits.

Prepared by: Tesfay Gidey 11


Addis Ababa Science and Technology University, Department of Software Engineering
Introduction to Programming in C ++
2. The break statement:
- The break statement can be used inside a loop (while, do…while, or for) or a switch statement.
- It causes an immediate jump out of the loop or switch statements, terminating them.
- Like the continue statement, the break statement only applies to the immediate loop or switch statement
enclosing it.
- It is an error to use the break statement outside of a loop or switch statement.

#include <iostream>

int main() {
int n;

for (n = 10; n > 0; n--) {


std::cout << n << ",";

if (n == 3) {
std::cout << "count down aborted!!";
break;
}
}

return 0;
}

• The loop counts down from 10 to 3, printing the value of n followed by a comma. When n becomes 3, it
prints "count down aborted!!" and exits the loop using break.

Prepared by: Tesfay Gidey 12


Addis Ababa Science and Technology University, Department of Software Engineering

You might also like