C++ Chap 1 3
C++ Chap 1 3
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.
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.
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.
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.
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:
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.
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 .
• 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.
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.
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.
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.
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.
Learning computer programming offers a range of benefits and is becoming increasingly important in
• 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.
• 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.
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.
• Learning programming helps you better understand and navigate the digital world,
including concepts like cybersecurity, data privacy, and the ethical implications
of technology.
• 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.
Programming languages can be classified into several categories based on their design and
purpose. Some common categories of programming languages include:
• 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.
• 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)
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.
N.B:
Please note that the fifth generation has no widely adopted languages, so specific characteristics are not
applicable.
• 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.
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.
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.
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.
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.
• The CPU is the core component of a computer system and performs all the major
computational tasks.
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.
• 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.
• 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.
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).
1. Imperative Programming:
• 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:
5. Declarative Programming:
6. Event-Driven Programming:
7. Concurrent Programming:
N.B:
#1. C:
int main() {
int x = 10;
if (x > 0) {
printf("Positive number\n");
} else {
printf("Non-positive number\n");
}
return 0;
}
#2. 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:
program HelloWorld;
var
x: Integer;
begin
writeln('Enter a number: ');
readln(x);
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:
#2. 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++:
#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#:
using System;
class HelloWorld
{
private int x;
public HelloWorld(int x)
{
this.x = x;
}
1. Requirements Engineering:
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:
4. Software Testing:
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.
• 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:
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.
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:
Disadvantages:
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:
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. 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:
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:
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.
7. Extensibility:
8. Security:
9. Testability:
10. Maintainability:
By considering these characteristics during the program design phase, you can create a
well-structured and high-quality software solution in any programming language.
2. Output: An algorithm produces desired results, which are the expected outcomes or
solutions to the problem.
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.
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.
• 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.
• 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.
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.
Worksheet 1
Course Title: Introduction to Programming / Fundamentals of Programming
Course No : Comp 4136
Chapter Two
2. Variables, Data Types, and Operators
examining the following code, we can gain a better understanding of these essential parts and their
#include <iostream>
int main() {
// Print a message to the console
std::cout << "This is a General Structure of a Simple C++ Program!" << std::endl;
2. int main() { ... }: The main function is the entry point of every C++ program. It acts
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++
• The << operator is used to insert the message into the output stream. std::endl is used to
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
8. The ‘include’ instruction is a preprocessor instruction that directs the compiler to include a copy
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();
}
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
3. Output Statement:
Within the main function, the code uses the cout object to display the message "Hello World!" to the
console:
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
(printing to the console) and input (reading from the console), respectively.
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
#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.
• It is associated with the standard input stream, typically the console, and is used to read input
#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
• The user is prompted to enter a number using std::cout, and the entered number is displayed
• It’s important to note that cout and cin are part of the standard library and do not require
• cout and cin used for output and input operations respectively.
• The iostream library provides many more features and functionalities for formatted
• 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.
be treated as a comment.
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.
*/
code. This is useful when you want to exclude certain lines of code from being executed without
deleting them.
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).
• In this example, the function add is declared with a return type of int and two
• 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
• The returned value, which is the sum of 5 and 3, is stored in the variable result.
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:
• In this example, the greet function takes a name parameter of type std::string and prints a
• Functions provide code reusability and allow you to break down complex tasks
• 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:
• 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
• 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
• 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
• 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
• Program commands are executed sequentially (line by line), following the order in which they
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
• Functions are composed of two main parts: the header and the body. The header consists of the
• A parameter serves as a declaration that specifies the type and name of the value that
• On the other hand, the actual value provided by the calling function when it invokes or calls the
• Arguments are the concrete values that are passed to the function and assigned to the
corresponding parameters.
integer value. But, a function that just prints a message has nothing to return and would be
• 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:
2. The statement cout << "\n In main function"; prints the message "In main function" on the
console.
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
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
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
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,
• Variables are used to represent and work with different types of data, such as numbers,
• They provide a way to store temporary or permanent data that can be used in calculations,
• Each variable has a unique identifier, known as its name, which is used to refer to and
• The name must follow certain rules and conventions defined by the programming
underscores.
• Variables can be declared with a specific type, specifying the kind of data they can hold,
• 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 ++
• The value stored in a variable can be accessed and utilized in various parts of the
- 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
- Value: a value that can be changed by assigning a new value to the variable.
• 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:
• The range and size of these types depend on the specific implementation and the platform.
2. Floating-Point Types:
• Floating-point types represent numbers with a fractional part.
• 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.
• Characters are represented using the ASCII or Unicode character encoding system.
• 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`.
- 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
N.B
Understanding the fundamental variable types in C++ is crucial for effectively storing and
By utilizing these variable types appropriately, programmers can write robust and efficient
types.
1. Signed Types:
• Signed types can represent both positive and negative numbers, including zero.
• The most significant bit (MSB) is reserved as the sign bit, and the remaining bits store
• 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:
• 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
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
- Mixing signed and unsigned types in expressions can lead to unexpected results due to
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).
• The range for a signed 8-bit integer (char) is from -128 to 127. The largest positive number that
• The range for an unsigned 8-bit integer (unsigned char) is from 0 to 255. The largest number
• 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
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.
Declaration refers to the act of introducing a variable to the program by specifying its name
It informs the compiler or interpreter that a variable with a specific name and type will be used
in the program.
Example:
int num;
• 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
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.
• The size of the memory allocated depends on the data type of the variable.
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
• 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:
• For example, in C++, words like `int`, `if`, `for`, and `while` are reserved keywords and
can create meaningful and unique variable names, ensuring clarity and avoiding conflicts in
your code.
Identifiers
• A valid identifier is a sequence of one or more letters, digits, or underscores. The length of an
• Spaces and special characters (such as punctuation marks) cannot be part of an identifier.
• Keywords (also known as reserved words) should not be used as names for identifiers.
• 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
• 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
• Global variables have a longer lifetime and persist throughout the execution of the
program.
Local variables have a limited lifetime and are created when their scope is entered and
#include <iostream>
void myFunction()
{
int localVariable = 20; // Local variable within the function
int main()
{
int localVariable = 30; // Local variable within the main function
myFunction();
return 0;
}
In this example, we have both local and global variables. Here’s how the scope works:
• localVariable is declared within the main function, making it a local variable specific to
• localVariable is also declared within the myFunction function, making it a different local
• When the program runs, the main function is executed first. It prints the value of its local
• 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.
Inside main:
localVariable: 30
globalVariable: 10
Inside myFunction:
localVariable: 20
globalVariable: 10
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
• 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
• Reusability:
Once defined, user-defined data types can be used in multiple parts of a program, promoting code
• Abstraction:
User-defined data types allow programmers to abstract complex data structures, hiding
variables of different types under a single name. They provide a convenient way to represent
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,
• 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
• 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-
They enable developers to create custom data structures tailored to their specific needs,
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;
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;
}
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;
return 0;
}
• 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.
• We create an instance of the BankAccount class called account and perform operations like
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
• This feature is beneficial when there is a need to repeatedly use a complex or lengthy type
• 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>
int main() {
USHORT width = 9;
USHORT height = 5;
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
• 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.
to unsigned short int, making the code easier to understand and reducing the potential for
• 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
• 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
• For example, if you subtract 8 from -32768, it wraps around to -32776. And if you subtract 1
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
For example:
65535 + 1 = 0
0–1 = 65535
0–8 = 65528
65528 + 1 = 65529
• In this example, the maximum value that an unsigned integer can hold is 65535. When you add 1
• Similarly, when you subtract 1 from 0, it wraps around to the maximum value (65535).
• For example, if you subtract 8 from 0, it wraps around to 65528. And if you add 1 to 65528, it
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.
For example:
- “\n” is used to move the cursor to the beginning of the next line.
• It performs a simple text substitution, where the defined constant is replaced with its
• 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;
• 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.
• Constants defined with `const` have a specific type, and the compiler enforces type checking
• For example, `const unsigned short int studentPerClass = 15;` defines a constant named
• Using `const` allows for stronger type checking and can provide better compile-time error
detection.
#include <iostream>
int main() {
unsigned short int totalStudents = studentPerClass * 5;
std::cout << "Total students in 5 classes: " << totalStudents <<
std::endl;
return 0;
}
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
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 traditional way of defining integer constants was using `#define` directives, but an alternate
• 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,
• By default, if you don’t assign explicit values, the first constant will have a value of 0, and the
• 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
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.
#include <iostream>
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
• 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 ++
• 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
• 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
Memory can be conceptualized as a large array of bytes, where each byte has a unique
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 ...
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
• 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;`.
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.
• 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.
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
— Conditional operator: Also known as the ternary operator (`?:`), it provides a shorthand
— 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,
- It causes the operand on the left side of the assignment statement to have its value changed to the
- Operand1 is always a variable, and Operand2 can be a literal constant, a variable, or an expression.
• Compound assignment operators combine the assignment operator with other operators like
• They provide a shorthand way of performing an operation and assigning the result back to the
variable.
• For example:
— a -= 5; is equivalent to a = a — 5;
— a /= b; is equivalent to a = a / b;
- 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
• When both operands of the division operator (/) are integers, the division is performed as an
• To obtain a real division when both operands are integers, you can cast one of the operands to be
real.
- 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.
- The operands of a relational operator must be evaluated to a number. Characters are valid operands
— 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.
- 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 ++
conditional statements.
- If the result is non-zero (true), then the second operand is chosen as the final result; otherwise, the
- 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);
return 0;
}
statement.
- The comma operator evaluates each expression from left to right and returns the value of the last
expression.
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;
return 0;
}
• In this program, the main() function declares integer variables m, n, and min. It also
• Finally, the values of min, mCount, and nCount are printed to the console using std::cout.
• 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
• It takes a single operand, which can be a data type, a variable, or a constant, and returns the size
• The result of the sizeof() operator is implementation-dependent and may vary based on the
• Example:
• int b = sizeof(int); // The size of an int depends on the platform (usually 4 bytes)
explicitly.
• dynamic_cast: Performs type conversions and checks if the conversion is valid in the case of
polymorphic types.
bit pattern.
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);
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.
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.
• Operator precedence determines the order in which operators are evaluated in an expression.
• 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
• It’s important to note that parentheses ( ) can be used to explicitly specify the evaluation order
Precedence Table:
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;
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;
return 0;
}
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.
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>
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.
#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;
}
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;
}
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.
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.
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:
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;
}
• 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”
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;
}
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;
if (num < 0)
continue;
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.
#include <iostream>
int main() {
int 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.