[go: up one dir, main page]

0% found this document useful (0 votes)
18 views35 pages

Chapter 1 4 Updated

Uploaded by

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

Chapter 1 4 Updated

Uploaded by

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

CHAPTER 1

TIMELINE: PROGRAMMING LANGUAGES

1843: Ada Lovelace's Pioneering Machine Algorithm

In 1843, Ada Lovelace, a mathematician and writer, developed the first-ever algorithm
designed specifically for a machine. Working in collaboration with Charles Babbage, who
invented the Difference Engine—a mechanical general-purpose computer—Lovelace envisioned
and described an algorithm that could be executed by the machine. This groundbreaking work is
widely regarded as the foundational step in the creation of programming languages, as it introduced
the concept of using a machine to perform a sequence of operations based on coded instructions.
Ada Lovelace's contributions laid the groundwork for modern computing and earned her the title
of the world's first computer programmer.

1944-1945: Development of Plankalkül by Konrad Zuse

Between 1944 and 1945, German engineer Konrad Zuse developed Plankalkül (Plan
Calculus), which is considered the first "real" programming language. Plankalkül introduced
several key concepts that are fundamental to modern programming, including the creation of
procedures—blocks of code that can be stored and reused to perform routine operations. This
innovation allowed for more efficient and systematic programming, enabling complex tasks to be
broken down into simpler, reusable components. Zuse's pioneering work with Plankalkül marked
a significant advancement in the history of computer science, laying the groundwork for the
development of future programming languages.

1949: Assembly Language and the EDSAC

In 1949, Assembly language was employed in the Electronic Delay Storage Automatic
Calculator (EDSAC), one of the earliest computers. Assembly language is a low-level
programming language that serves as a bridge between human-readable code and machine code,
the specific instructions necessary to operate a computer. By simplifying the complex binary
instructions of machine code into more understandable commands, Assembly language made
programming more accessible to engineers and played a crucial role in the early development of
computer systems.

1949: Shortcode—The First High-Level Language

Also in 1949, Shortcode (or Short-order code) became the first high-level programming
language (HLL) to be proposed. Initially suggested by John McCauley, it was William Schmitt
who implemented Shortcode for the BINAC computer that same year, and later for the UNIVAC
in 1950. Unlike low-level languages like Assembly, Shortcode allowed programmers to write
instructions in a more abstract form, closer to human language, which could then be translated into
machine code. This marked a significant leap towards more user-friendly programming.
1952: Autocode—The First Compiled Language

By 1952, Autocode emerged as a general term for a family of programming languages.


Alick Glennie developed the first version of Autocode for the Mark 1 computer at the University
of Manchester. Autocode was groundbreaking as the first-ever compiled language, meaning it
could be translated directly into machine code using a program called a compiler. This innovation
greatly streamlined the programming process. Autocode was subsequently used on other early
computing machines like the Ferranti Pegasus and Sirius, solidifying its place in computing
history.

1957: The Creation of FORTRAN

In 1957, John Backus and his team at IBM developed FORTRAN, short for FORmula
TRANslation. As the first high-level programming language designed for scientific, mathematical,
and statistical computations, FORTRAN revolutionized the way complex calculations were
performed. It enabled scientists and engineers to write programs using a more accessible syntax
that could be efficiently translated into machine code, significantly speeding up the computational
process.

FORTRAN's impact was profound, and it quickly became the language of choice for
scientific computing. Remarkably, despite the emergence of many new programming languages,
FORTRAN remains in use today, especially in some of the world’s most advanced
supercomputers. Its longevity is a testament to its robustness and efficiency in handling intensive
computational tasks.

1958: The Birth of ALGOL (Algorithmic Language)

In 1958, a joint committee of American and European computer scientists developed


ALGOL (Algorithmic Language). ALGOL was a groundbreaking language that introduced many
of the concepts and structures still used in programming today. It served as a foundation for the
development of several of the most influential programming languages, including Pascal, C, C++,
and Java. ALGOL's emphasis on structured programming and its clear syntax made it a crucial
milestone in the evolution of computer languages, shaping the way software was developed for
decades.

1958: The Invention of LISP (List Processor)

Also in 1958, John McCarthy at the Massachusetts Institute of Technology (MIT) invented
LISP (List Processor), originally designed for artificial intelligence research. LISP introduced
several key concepts, such as tree data structures and automatic storage management, which have
influenced many subsequent languages. Despite being one of the oldest programming languages
still in use, LISP remains relevant, often utilized in specialized areas where its unique capabilities
excel. Today, companies like Acceleration, Boeing, and Genworks continue to incorporate LISP
into their technology stacks, and it can be used as an alternative to modern languages like Ruby or
Python.
1959: The Development of COBOL (Common Business Oriented Language)

In 1959, Common Business Oriented Language (COBOL) was developed with a focus on
business, finance, and administrative systems. The creation of COBOL was led by Dr. Grace
Murray Hopper, a pioneering computer scientist. One of the key features of COBOL was its
portability—it was designed to run on all brands and types of computers, making it incredibly
versatile.

COBOL became the backbone of many critical systems, including credit card processors,
ATMs, telephone and cellular networks, hospital signal systems, and traffic control systems. Its
straightforward, English-like syntax made it accessible for businesses to adopt widely.
Remarkably, COBOL is still in use today, particularly in the banking sector and for gamification
systems, where its reliability and efficiency continue to be valued.

1964: The Creation of BASIC (Beginner’s All-Purpose Symbolic Instruction Code)

In 1964, a group of students at Dartmouth College developed BASIC (Beginner’s All-


Purpose Symbolic Instruction Code) as a programming language intended for beginners. The
language was designed to be simple and accessible, particularly for students who did not have a
strong background in mathematics or computers. BASIC’s straightforward syntax allowed users
to write programs without the complexity typically associated with other languages.

BASIC was further developed by Bill Gates and Paul Allen, the founders of Microsoft.
They transformed it into one of the company’s first marketable products, setting the stage for
Microsoft’s future success. BASIC's impact was significant, as it became a widely used language
that introduced many people to the world of programming.

1970: The Development of PASCAL

In 1970, Niklaus Wirth developed the programming language PASCAL, named after the
French mathematician Blaise Pascal. PASCAL was designed as an educational tool to teach
computer programming, with an emphasis on structured programming and data structuring. Its
simplicity and clarity made it easy to learn, making it an ideal choice for teaching programming
concepts.

PASCAL gained popularity in the early days of Apple, where it was favored for its ease of
use and powerful features. It played a significant role in shaping the development of early software
and influenced many subsequent programming languages.

1972: The Introduction of Smalltalk

In 1972, Smalltalk was developed at the Xerox Palo Alto Research Center (PARC) by Alan
Kay, Adele Goldberg, and Dan Ingalls. Smalltalk was groundbreaking because it allowed
programmers to modify code on the fly, which was a novel feature at the time. The language
introduced several concepts that have become fundamental in modern programming languages,
including object-oriented programming (OOP) principles and dynamic typing. Many of these
concepts are now visible in languages like Python, Java, and Ruby. Today, companies such as
Leafly, Logitech, and CrowdStrike incorporate Smalltalk into their technology stacks due to its
innovative features and enduring relevance.

1972: The Creation of C

In 1972, Dennis Ritchie developed the C programming language at Bell Telephone


Laboratories. C was designed for use with the Unix operating system and was named after its
predecessor, the B language. C's design has had a profound influence on the development of many
subsequent programming languages. It introduced key concepts that have been adopted and refined
in languages such as C#, Java, JavaScript, Perl, PHP, and Python. C remains widely used in
industry, with major companies like Google, Facebook, and Apple relying on it for various
applications and systems.

1972: The Development of SQL (SEQUEL)

In 1972, IBM researchers Raymond Boyce and Donald Chamberlain developed SEQUEL
(Structured English Query Language), which later became known as SQL (Structured Query
Language). SEQUEL was designed to facilitate the management and manipulation of data stored
in relational databases. It allowed users to view, update, and manage database information with
ease.

The language was renamed SQL, and it has since become the standard for querying and
managing relational databases. SQL's influence is pervasive in the tech industry, with numerous
companies relying on it for their database operations. Prominent organizations such as Microsoft
and Accenture utilize SQL in their tech stacks to handle complex data interactions and ensure
efficient database management.

1980/1981: The Creation of Ada

In 1980/1981, the Ada programming language was developed by a team led by Jean Ichbiah
at CUU Honeywell Bull, under contract with the United States Department of Defense. Ada was
named in honor of Ada Lovelace, a pioneering mathematician and the first computer programmer.
Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level
language. It was designed to address the need for a reliable, maintainable language suitable for
complex systems.

Ada was influenced by existing programming languages like Pascal but incorporated
additional features to improve its robustness and versatility. It is extensively used in critical
systems, including air-traffic management systems in countries such as Australia, Belgium, and
Germany, as well as in various transport and space projects.

1983: The Evolution of C++

In 1983, Bjarne Stroustrup developed C++ at Bell Labs as an extension of the C


programming language. C++ introduced several enhancements to C, including classes, virtual
functions, and templates, which enabled object-oriented programming and more flexible software
design. Since its inception, C++ has consistently ranked among the top programming languages
and was inducted into the Hall of Fame in 2003.

C++ is known for its performance and efficiency, making it a popular choice for high-
performance applications. It is used in a wide range of software, including Microsoft Office, Adobe
Photoshop, game engines, and other complex systems that require high computational power.

1983: The Introduction of Objective-C

In 1983, Brad Cox and Tom Love developed Objective-C, a programming language that
combines elements of C with Smalltalk’s object-oriented features. Objective-C was designed to
add object-oriented capabilities to the C programming language, making it possible to create more
complex and modular software.

Objective-C became the primary programming language for developing software for
Apple's macOS and iOS operating systems. Its integration with Apple's development environment,
Xcode, and its use in frameworks such as Cocoa and Cocoa Touch made it a cornerstone of Apple’s
software ecosystem. Although Objective-C has been largely succeeded by Swift, it remains an
important part of Apple's software development history.

1987: The Creation of Perl

In 1987, Larry Wall developed Perl, a general-purpose, high-level programming language.


Initially designed as a scripting language for text processing and report generation, Perl quickly
gained popularity due to its flexibility and powerful features. It provided robust support for string
manipulation, regular expressions, and file handling, which made it particularly effective for tasks
related to text editing.

Over time, Perl evolved beyond its original scope and became widely used for a variety of
applications. It found a niche in CGI (Common Gateway Interface) scripting for web development,
database management, system administration, network programming, and even graphic
programming. Perl's versatility and strong community support have established it as a valuable
tool for many developers and organizations.

1990: The Development of Haskell

In 1990, Haskell was introduced as a general-purpose programming language named after


the American logician and mathematician Haskell Brooks Curry. Haskell is distinguished by its
purely functional programming paradigm, which means it focuses on mathematical functions and
immutable data. This approach emphasizes the use of functions to perform computations and
manage data, rather than changing state or using imperative commands.

Haskell is particularly valued in industries that require complex calculations, data


processing, and numerical analysis. Despite its powerful capabilities, Haskell is not as commonly
seen in mainstream applications compared to other languages. However, it has been used in various
niche applications, including games like Nikki and the Robots, demonstrating its versatility and
unique strengths.

1991: The Introduction of Python

In 1991, Guido van Rossum developed Python, a general-purpose, high-level programming


language named after the British comedy troupe Monty Python. Python was designed to be
accessible and enjoyable to use, with a focus on readability and simplicity. Its syntax is clean and
straightforward, supporting multiple programming paradigms, including procedural, object-
oriented, and functional programming.

Python’s versatility and ease of use have contributed to its widespread popularity. It is used
by many prominent companies and organizations, including Google, Yahoo, and Spotify, for a
range of applications from web development to data analysis and artificial intelligence. The
language’s extensive libraries and community support continue to make it one of the most popular
programming languages globally.

1991: The Introduction of Visual Basic

In 1991, Microsoft introduced Visual Basic, a programming language designed to simplify


the process of creating graphical user interfaces (GUIs). Visual Basic allowed programmers to use
a drag-and-drop interface to select and modify pre-built code components, making it accessible for
developers who wanted to build applications with a user-friendly interface without extensive
coding.

While Visual Basic is less commonly used today compared to modern programming
languages, it has had a significant impact on software development. Elements of Visual Basic
continue to be incorporated into various Microsoft applications, such as Word, Excel, and Access,
highlighting its enduring influence and utility in building robust software solutions.

1993: The Creation of Ruby

In 1993, Yukihiro Matsumoto developed Ruby, an interpreted high-level programming


language. Ruby was designed with a focus on simplicity and productivity, influenced by languages
such as Perl, Ada, Lisp, and Smalltalk. It was intended to be a teaching language that combined
the best aspects of these languages while emphasizing a natural and intuitive syntax.

Ruby is widely known for its use in web development, particularly with the Ruby on Rails
framework, which revolutionized web application development by simplifying and accelerating
the process. Companies such as Twitter, Hulu, and Groupon are prominent users of Ruby,
demonstrating its effectiveness and popularity in building scalable and dynamic web applications.

1995: The Development of Java

In 1995, James Gosling and his team at Sun Microsystems introduced Java, a general-
purpose, high-level programming language originally created for an interactive TV project. Java
was designed with the principle of "Write Once, Run Anywhere" (WORA) in mind, meaning that
code written in Java could run on any device or platform that had a Java Virtual Machine (JVM),
regardless of the underlying hardware or operating system.

Java's cross-platform functionality and robustness have contributed to its enduring


popularity. It consistently ranks among the world's most widely used programming languages. Its
versatility allows it to be found in a wide range of applications, from desktop computers and
smartphones to embedded systems like parking meters and industrial equipment. Java's extensive
ecosystem, including a rich set of libraries and frameworks, continues to make it a crucial language
for building scalable and reliable software solutions.

1995: The Introduction of PHP

In 1995, Rasmus Lerdorf developed PHP, initially standing for "Personal Home Page" but
now known as "Hypertext Preprocessor." PHP is a server-side scripting language designed for
creating and managing dynamic web pages and web applications. It integrates seamlessly with
databases and is widely used for server-side development.

PHP's versatility and ease of integration with various web technologies have made it a
popular choice for many high-profile websites and applications. Notable examples include
Facebook, Wikipedia, Digg, WordPress, and Joomla. Its widespread adoption highlights its
significance in the world of web development.

1995: The Creation of JavaScript

In 1995, Brendan Eich developed JavaScript, a programming language primarily used for
creating dynamic and interactive elements on web pages. JavaScript enables functionalities such
as form validation, animations, and real-time updates without needing to refresh the web page. It
is also utilized in PDF documents, web browsers, and desktop widgets.

JavaScript's impact is profound, as it is an integral part of almost every major website and
web application. Prominent examples include Gmail, Adobe Photoshop (for scripting), and
Mozilla Firefox (for extensions and customization). Its ubiquity and essential role in modern web
development make it one of the most important languages in the tech industry.

2000: The Introduction of C#

In 2000, Microsoft introduced C#, a programming language designed to combine the power
of C++ with the simplicity and ease of use of Visual Basic. C# was developed to address the need
for a language that could facilitate both high-performance computing and developer productivity.
It shares many similarities with Java, including its object-oriented features and syntax.

C# is widely used across Microsoft products and services, and it plays a key role in the
development of desktop applications and enterprise software within the Microsoft ecosystem. Its
integration with the .NET framework has made it a preferred language for building robust and
scalable applications.
2003: The Creation of Scala

In 2003, Martin Odersky developed Scala, a programming language that merges functional
programming with object-oriented programming. Scala is designed to provide the expressiveness
and flexibility of functional programming while retaining the organization and structure of object-
oriented design.

Scala’s compatibility with Java makes it particularly useful for Android development and
for integrating with existing Java codebases. Its advanced features and interoperability have made
it popular among major technology companies. Notable examples of companies using Scala
include LinkedIn, Twitter, Foursquare, and Netflix, reflecting its effectiveness in handling
complex and scalable software solutions.

2003: The Introduction of Groovy

In 2003, James Strachan and Bob McWhirter developed Groovy, a language derived from
Java that aims to enhance developer productivity. Groovy builds upon Java, offering a more
concise and expressive syntax while maintaining compatibility with Java code. This makes it easier
for developers familiar with Java to learn and use Groovy effectively.

Groovy's design focuses on simplifying code and reducing boilerplate, which can
significantly speed up development and improve readability. It is commonly used in areas such as
scripting, domain-specific languages (DSLs), and testing. Notable companies utilizing Groovy in
their tech stacks include Starbucks, TransferWise, and Craftbase, reflecting its practical benefits
and widespread adoption in various industries.

2009: The Introduction of Go

In 2009, Google introduced Go, also known as Golang, to address the challenges associated
with large-scale software systems. Go was designed with a focus on simplicity, efficiency, and
ease of use, featuring a modern structure that helps manage complexity in programming. Its
concurrent programming model and strong performance have made it a popular choice for building
scalable and high-performance applications.

Go has gained widespread adoption among major tech companies, including Google, Uber,
Twitch, and Dropbox. Its efficient design and robust features have established it as a key tool in
the development of large-scale systems and distributed software.

2014: The Creation of Swift

In 2014, Apple developed Swift as a modern replacement for C, C++, and Objective-C.
Swift was created with the goal of simplifying the development process and minimizing errors,
offering a more intuitive and safer programming experience compared to its predecessors. Its
modern syntax and features are designed to improve code readability and reduce common
programming pitfalls.
Swift’s versatility allows it to be used across various domains, including desktop
applications, mobile apps, and cloud services. Its impact is evident in applications such as
Duolingo, which launched a new app written in Swift, showcasing the language's capability to
handle modern app development challenges effectively.
CHAPTER II
ALGORITHM and FLOWCHARTS

Definition and Characteristics of an Algorithm

An algorithm, derived from the name of the mathematician Al-Khwarizmi, refers to a


procedure or technique for solving problems. In computer science and software engineering,
algorithms are used for planning and solving problems. An algorithm is defined as a sequence of
steps that accomplishes a specific task or solves a particular problem. It is characterized by:

• Input: An algorithm may or may not require input data.


• Output: Each algorithm is expected to produce at least one result.
• Definiteness: Each step or instruction in the algorithm must be clear and unambiguous.
• Finiteness: The algorithm must terminate after a finite number of steps when executed.

Control Structures in Algorithms and Flowcharts


Algorithms and flowcharts use the following three primary control structures:

• Sequence: In a sequence structure, statements are executed one after the other in a linear
order, from top to bottom.
• Branching (Selection): This control structure involves making decisions based on
conditions. A decision is evaluated as either TRUE or FALSE. If the condition is TRUE,
one branch of the code is executed; if FALSE, the alternative branch is taken. This is
typically represented using 'IF-THEN' constructs.
• Loop (Repetition): Loops allow for the repeated execution of statements based on a loop
condition. Common loop constructs include WHILE and FOR loops, which execute a block
of code multiple times as long as a specified condition is met.

Advantages of Algorithms

• Clarity: Algorithms provide a step-by-step representation of a solution, making it easier


to understand and follow.
• Definiteness: They use a definite procedure, ensuring that each step is clear and precise.
• Independence from Programming Language: Algorithms are language-agnostic,
meaning they can be understood and used without requiring knowledge of a specific
programming language.
• Debugging: The logical sequence of steps in an algorithm makes it easier to debug and
identify issues.
How to Write Algorithms

• Define the Input: Determine the data or inputs that the algorithm will process.
• Define the Variables: Use variables to represent the inputs and intermediate values. For
clarity, use meaningful names for the variables
• Outline the Operations: Specify the steps or operations that the algorithm will perform
using the input variables
• Output the Results: Define how the results of the algorithm’s operations will be output.

Example of an Algorithm to Calculate the Area of a Rectangle

• Input: HEIGHT, WIDTH


• Variables: HEIGHT, WIDTH, AREA
• Operations:
o Calculate AREA = HEIGHT * WIDTH
• Output: Print AREA

Example Execution

If HEIGHT = 2 and WIDTH = 3:

o Compute AREA = 2 * 3
o Output: AREA = 6

Introduction to Flowcharts

The concept of flowcharts was first designed by John Von Neumann in 1945. Unlike
algorithms, which use a sequence of steps described in text, flowcharts use various symbols to
visually represent the sequence and logic of operations in a system. Flowcharts provide a clear,
graphical representation of the process, making it easier to understand and communicate how a
problem is solved or how a system functions.

Advantages of Flowcharts

• Effective Communication: Flowcharts are an excellent tool for conveying the logic and
structure of a program or process. They provide a visual representation that can be easily
understood by both technical and non-technical stakeholders.
• Problem Analysis: They facilitate easy and efficient analysis of problems by breaking
down complex processes into simpler, visual steps.
• Blueprint for Development: During the program development cycle, flowcharts act as a
blueprint, simplifying the design and development process by outlining the sequence of
operations and decision points.
• Maintenance: Flowcharts aid in the maintenance of programs or systems by providing a
clear, visual map of how processes are structured. This helps in identifying and addressing
issues or making updates more efficiently.
• Code Conversion: They make it easier to translate the visual representation of processes
into programming code. The logical flow depicted in a flowchart can be directly mapped
to programming constructs.

Standard Symbols Used in Flowcharts

Flowcharts use a set of standard symbols to represent different types of actions or steps in
a process. Here are some commonly used symbols:

• Start/End (Terminator): This symbol indicates the beginning or end of a flowchart. It is


typically represented by an oval or rounded rectangle.

• Process: Represented by a rectangle, this symbol is used to denote a process or an


operation that needs to be performed.

• Decision: A diamond shape represents a decision point where the process can branch
based on a condition (e.g., YES or NO).

• Input/Output: Represented by a parallelogram, this symbol is used to show data input or


output operations.

• Flow Line (Arrow): Arrows indicate the direction of flow from one step to the next.

• Connector: A small circle or labeled connector symbol is used to show a jump or


connection to another part of the flowchart, typically used to connect different parts of a
flowchart that are on different pages.

• Document: Represented by a rectangle with a wavy bottom edge, this symbol indicates a
document or report.

• Manual Operation: A trapezoid symbol is used to represent operations that are performed
manually rather than by the computer.
Example Flowchart

Here’s a simple example of a flowchart for a basic process:

Start: Begin the process (Oval symbol).


Input Data: Collect data (Parallelogram symbol).
Process Data: Perform a calculation or operation (Rectangle symbol).
Decision: Check if the result meets a condition (Diamond symbol).
YES: Proceed to next step.
NO: Go back or end process.
Output Result: Display or output the result (Parallelogram symbol).
End: Finish the process (Oval symbol).

Problem: Calculate the Sum of Two Numbers

1. Problem: Calculate the Sum of Two Numbers


Algorithm:1. Problem: Calculate the Sum of Two Numbers

Algorithm:

Input: Two numbers, A and B.


Process: Compute the sum S = A + B.
Output: Display the sum S.
Flowchart:

• Start: An oval indicating the beginning of the process.


• Input A, B: A parallelogram representing the input of two numbers, A and B.
• Process: S = A + B: A rectangle symbolizing the computation or process step
where the sum S is calculated.
• Output S: A parallelogram indicating the output of the sum S.
• End: An oval representing the end of the process.

Explanation: This simple algorithm adds two numbers and outputs the result. The flowchart
visually represents this process with clear steps for input, calculation, and output.

2. Problem: Find the Maximum of Three Numbers

Algorithm:

Input: Three numbers, A, B, and C.


Process:
Compare A with B.
Compare the larger value with C.
Assign the largest value to MAX.
Output: Display the maximum value MAX.
Flowchart:

• Start: An oval symbol representing the beginning of the process.


• Input A, B, C: A parallelogram where the three numbers A, B, and C are input.
• Decision: A > B?: A diamond symbol representing the decision point where A
is compared with B.

• True: If A is greater than B, then:


o Compare A with C: Another decision point where A is compared
with C.
§ If A is greater than C, A is the maximum (output MAX).
§ If C is greater, C is the maximum (output MAX).
• False: If B is greater than or equal to A, then:
o Compare B with C: Another decision point where B is compared
with C.
§ If B is greater than C, B is the maximum (output MAX).
§ If C is greater, C is the maximum (output MAX).

• Output MAX: A parallelogram where the maximum value (MAX) is output.


• End: An oval symbol representing the end of the process.
Explanation: The algorithm determines the maximum of three numbers by comparing them
pairwise and selecting the largest. The flowchart uses decision symbols to represent the
comparison operations.

3. Problem: Check if a Number is Even or Odd


Algorithm:

Input: Number N.
Process:
Compute the remainder of N divided by 2.
If the remainder is 0, N is even; otherwise, N is odd.
Output: Display whether N is even or odd.

Flowchart:

• Start: An oval symbol representing the beginning of the process.


• Input N: A parallelogram where the number NNN is input.
• Process: Compute N%2N \% 2N%2: A rectangle representing the operation
where the remainder of NNN divided by 2 is computed.
• Decision: Remainder = 0?: A diamond symbol representing a decision point.

• True: If the remainder is 0, then NNN is even, and the flow goes to the
next step:
o Output "Even": A parallelogram where the output "Even" is
displayed.
• False: If the remainder is not 0, then NNN is odd, and the flow goes to the
next step:
o Output "Odd": A parallelogram where the output "Odd" is
displayed.

• End: An oval symbol representing the end of the process.


Explanation: The algorithm checks the parity of a number by computing the remainder of division
by 2. The flowchart includes a decision symbol to determine the outcome.

4. Problem: Find the Factorial of a Number

Algorithm:

Input: Number N.
Process:
Initialize FACT = 1.
Multiply FACT by every number from 1 to N.
Output: Display the factorial FACT.
Flowchart:

• Start: An oval symbol representing the beginning of the process.


• Input N: A parallelogram where the number NNN is input.
• Initialize FACT = 1: A rectangle symbol representing the initialization
of the variable FACT to 1.
• Process: For i from 1 to N: This step involves a loop (which might be
represented in a more detailed flowchart using a combination of a process
symbol and a decision symbol).

• Multiply FACT by i: A rectangle symbol representing the


operation where FACT is multiplied by the current value of iii in
each iteration of the loop.

• Output FACT: A parallelogram where the factorial value (FACT) is


output after completing the loop.
• End: An oval symbol representing the end of the process.

Explanation: The algorithm calculates the factorial of a number by multiplying a series of integers.
The flowchart shows a loop structure to handle the iterative multiplication.

5. Problem: Find the Average of a List of Numbers


Algorithm:

Input: List of numbers.


Process:
Compute the sum of the numbers.
Divide the sum by the count of numbers.
Output: Display the average.
Flowchart:

• Start: An oval symbol indicating the beginning of the process.


• Input List of Numbers: A parallelogram where the list of numbers is
input.
• Process: Compute Sum and Count: A rectangle symbol representing
the operation where the sum of the numbers is calculated, and the count of
the numbers is determined.
• Process: Compute Average = Sum / Count: A rectangle symbol
representing the calculation of the average by dividing the sum by the count.
• Output Average: A parallelogram where the calculated average is
output.
• End: An oval symbol representing the end of the process.

Explanation: The algorithm calculates the average of a list of numbers by summing them and
dividing by their count. The flowchart includes summation and division steps.

6. Problem: Determine if a Number is Prime


Algorithm:

Input: Number N.
Process:
Check divisibility of N by numbers from 2 to √N.
If N is divisible by any of these numbers, it is not prime.
Output: Display whether N is prime or not.
Flowchart:

• Start: An oval symbol representing the beginning of the process.


• Input N: A parallelogram where the number NNN is input.
• Process: For iii from 2 to N\sqrt{N}N: A rectangle representing a loop
that iterates iii from 2 up to the square root of NNN.
• Decision: N%i==0N \% i == 0N%i==0?: A diamond symbol
representing the decision point where NNN is checked to see if it is divisible
by iii.

• True: If N%i==0N \% i == 0N%i==0, it means NNN is divisible by


iii, so:
o Output "Not Prime": A parallelogram where "Not Prime"
is output, indicating that NNN is not a prime number.
o The process then leads to the End.
• False: If N%iN \% iN%i is not 0, continue to the next iteration of
the loop until iii reaches N\sqrt{N}N.

• Output "Prime": After all iterations, if no divisor is found, output


"Prime," indicating that NNN is a prime number.
• End: An oval symbol representing the end of the process.
Explanation: The algorithm checks if a number is divisible by any number up to its square root to
determine if it is prime. The flowchart shows a loop with a decision symbol for divisibility checks.

7. Problem: Compute the Fibonacci Sequence up to N Terms


Algorithm:

Input: Number N.
Process:
Initialize first two terms: F1 = 0, F2 = 1.
Compute the next terms by summing the previous two terms until N terms
are reached.
Output: Display the sequence.
Flowchart:

• Start: An oval symbol representing the beginning of the process.


• Input N: A parallelogram where the number NNN (the number of terms
in the Fibonacci sequence to generate) is input.
• Initialize F1 = 0, F2 = 1: A rectangle symbol where the first two terms
of the Fibonacci sequence are initialized. F1F1F1 is set to 0, and F2F2F2 is
set to 1.
• Process: For iii from 3 to NNN: A rectangle symbol representing a loop
that iterates from 3 up to NNN.

• Compute Next = F1 + F2: Inside the loop, a rectangle symbol


where the next term in the Fibonacci sequence is calculated by
summing the previous two terms, F1F1F1 and F2F2F2.
• Update F1 = F2, F2 = Next: Another rectangle symbol where the
values of F1F1F1 and F2F2F2 are updated. F1F1F1 takes the value
of F2F2F2, and F2F2F2 takes the value of the newly calculated
term, NextNextNext.

• Output Sequence: A parallelogram where the sequence of Fibonacci


numbers up to NNN terms is output.
• End: An oval symbol representing the end of the process.
Explanation: The algorithm generates Fibonacci numbers by summing the previous two terms.
The flowchart illustrates this with initialization, a loop for computation, and output steps.

8. Problem: Sort a List of Numbers (Bubble Sort)


Algorithm:

Input: List of numbers.


Process:
Compare adjacent numbers.
Swap if out of order.
Repeat until the list is sorted.
Output: Display the sorted list.
Flowchart:

• Start: An oval symbol representing the beginning of the process.


• Input List of Numbers: A parallelogram where the list of numbers to be
sorted is input.
• Process: For iii from 0 to N−1N-1N−1: A rectangle symbol representing
the outer loop that iterates iii from 0 to N−1N-1N−1, where NNN is the
number of elements in the list.
• For jjj from 0 to N−i−1N-i-1N−i−1: Another rectangle symbol
representing the inner loop that iterates jjj from 0 to N−i−1N-i-1N−i−1. This
loop allows comparison of adjacent elements in the list.
• Decision: List[j] > List[j+1]?: A diamond symbol representing the
decision point where each pair of adjacent elements is compared.

• True: If List[j] is greater than List[j+1], the flow proceeds to:


o Swap List[j] and List[j+1]: A rectangle symbol where the
two elements are swapped to put them in the correct order.
• False: If List[j] is not greater than List[j+1], no action is taken, and
the loop continues.

• Output Sorted List: After completing the outer loop, a parallelogram


where the sorted list is output.
• End: An oval symbol representing the end of the process.

Explanation: The algorithm sorts a list using the bubble sort method, which repeatedly compares
and swaps adjacent elements. The flowchart includes nested loops for sorting and a decision
symbol for comparisons.

9. Problem: Search for an Element in a List (Linear Search)


Algorithm:

Input: List of numbers, Target.


Process:
Traverse the list.
Compare each element with Target.
If found, return the position.
Output: Display the position of the Target or "Not Found".
Flowchart:

• Start: Represented by a rounded rectangle.


• Input List, Target: Represented by a parallelogram.
• Process: For i from 0 to N-1: Represented by a rectangle (process box).
This indicates the start of a loop.
• Decision: List[i] == Target?: Represented by a diamond shape (decision
box).
o True: Output Position i, represented by a parallelogram
(input/output box).
o False: Continue, which means you go back to the loop process to
increment i.
• Output "Not Found": If the loop ends without finding the target,
represented by a parallelogram.
• End: Represented by a rounded rectangle.

Explanation: The algorithm performs a linear search through a list to find a target value. The
flowchart shows a loop with a decision point to check each element.

10. Problem: Calculate the Greatest Common Divisor (GCD) Using Euclidean Algorithm
Algorithm:

Input: Two numbers, A and B.


Process:
Replace A with B and B with A % B.
Repeat until B becomes 0.
The GCD is the value of A.
Output: Display the GCD.
Flowchart:

• Start: Represented by a rounded rectangle.


• Input A, B: Represented by a parallelogram.
• Process: While B ≠ 0: Represented by a rectangle with a loop indicator or note that this is
a repeating process.

• Compute R = A % B: Represented by a rectangle (process box).

• Set A = B: Represented by a rectangle (process box).

• Set B = R: Represented by a rectangle (process box).

• Output A: Represented by a parallelogram.

• End: Represented by a rounded rectangle.

Explanation: The algorithm calculates the GCD using the Euclidean method, which involves
repeated modulus operations. The flowchart includes a loop and process symbols to handle the
iterative computation.
1. Mathematical Operators

Mathematical operators are symbols used to perform arithmetic calculations on operands


(numbers or variables).

• Addition (+): Adds two operands.


• Subtraction (-): Subtracts the second operand from the first.
• Multiplication (*): Multiplies two operands.
• Division (/): Divides the first operand by the second.
• Modulus (%): Returns the remainder of the division of the first operand by the second.

Examples:

1. Addition: A + B
o If A = 5 and B = 3, then A + B = 8.
2. Multiplication: A * B
o If A = 4 and B = 7, then A * B = 28.
3. Modulus: A % B
o If A = 10 and B = 3, then A % B = 1 (remainder when 10 is divided by 3).

2. Relational Operators

Relational operators are used to compare two values or expressions. The result is typically a
Boolean value (True or False).

• Equal to (==): Checks if two operands are equal.


• Not equal to (!=): Checks if two operands are not equal.
• Greater than (>): Checks if the first operand is greater than the second.
• Less than (<): Checks if the first operand is less than the second.
• Greater than or equal to (>=): Checks if the first operand is greater than or equal to the
second.
• Less than or equal to (<=): Checks if the first operand is less than or equal to the
second.

Examples:

1. Equal to: A == B
o If A = 5 and B = 5, then A == B is True.
2. Greater than: A > B
o If A = 7 and B = 3, then A > B is True.
3. Less than: A < B
o If A = 2 and B = 5, then A < B is True.
o
3. Logical Operators

Logical operators are used to combine multiple Boolean expressions or conditions.

• AND (&&): Returns True if both operands are true.


• OR (||): Returns True if at least one of the operands is true.
• NOT (!): Reverses the logical state of its operand. If a condition is True, it becomes
False, and vice versa.

Examples:

1. AND: (A > B) && (C < D)


o If A = 5, B = 3, C = 2, and D = 4, then (A > B) && (C < D) is True.
2. OR: (A == B) || (C > D)
o If A = 5, B = 6, C = 3, and D = 2, then (A == B) || (C > D) is True.
3. NOT: !(A > B)
o If A = 5 and B = 3, then !(A > B) is False.

4. Selection Control Statements

Selection control statements allow a program to choose different paths of execution based on
conditions.

• If Statement: Executes a block of code if a specified condition is true.


• If-Else Statement: Executes one block of code if a condition is true and another block if
it is false.
• Switch Statement: Allows a variable to be tested for equality against a list of values.

5. Loop Control Structures

Loop control structures allow a set of instructions to be executed repeatedly based on a


condition.

• For Loop: Repeats a block of code a specified number of times.


• While Loop: Repeats a block of code as long as a specified condition is true.
• Do-While Loop: Similar to the while loop, but the block of code is executed at least once
before the condition is tested.

Notes:

• Mathematical Operators perform basic arithmetic operations.


• Relational Operators compare values and return Boolean results.
• Logical Operators combine Boolean expressions.
• Selection Control Statements allow decision-making in the code based on conditions.
• Loop Control Structures enable repeated execution of code based on conditions.
CHAPTER III

INTRODUCTION TO C++

C++ is a powerful programming language that emerged in 1979, created by Bjarne


Stroustrup as an extension of the C language. Initially known as "C with Classes," it aimed to
combine the efficiency of C with the benefits of object-oriented programming. Key features
included classes, inheritance, inline functions, and strong type checking.

In 1983, the language was renamed C++, symbolizing its evolution beyond C. New
features such as virtual functions, function overloading, references, and the const keyword
were introduced, further enhancing its capabilities.

C++ was first commercially implemented in 1985 and continued to evolve with notable
releases like Turbo C++ in 1990. The language was officially standardized in 1998 as C++98,
which introduced the Standard Template Library (STL). Subsequent updates, including
C++03, C++11, C++14, C++17, and C++20, introduced modern features like lambda
expressions, auto keyword, concurrency support, and concepts.

C++ remains a widely used language, known for its performance, flexibility, and ability
to handle complex systems. Its ongoing evolution ensures its relevance in modern software
development.

1. Preprocessor Directives

• #include <iostream>:
o This line is a preprocessor directive. Lines starting with a # are instructions for
the preprocessor, which runs before the actual compilation of the code.
o The directive #include <iostream> tells the preprocessor to include the
contents of the iostream file, which is part of the C++ Standard Library.
o The iostream library provides functionalities for input and output operations (like
reading from the keyboard or writing to the screen).

2. Namespace Declaration

• using namespace std;:


o In C++, namespaces are used to organize code and prevent name conflicts.
o The std namespace contains all the entities of the Standard C++ Library, such as
cout, cin, and many other functions and objects.
o The statement using namespace std; allows the programmer to use these
entities without having to prefix them with std::.

3. Main Function Declaration

• int main():
o Every C++ program must have a main function because it is the entry point
where execution begins.
o The int before main() indicates that the function returns an integer value. By
convention, returning 0 indicates successful execution.
o The parentheses () after main indicate that this is a function declaration. In this
case, the main function doesn’t take any parameters.
• Function Body:
o The body of the main function is enclosed in curly braces {}.
o All the code inside these braces will be executed when the program runs.

4. Output Statement

• cout << "Hello World!";:


o This line outputs the text "Hello World!" to the screen.
o cout is an object representing the standard output stream in C++. It is used to
display output on the screen.
o The << operator is used to send the string "Hello World!" to the output stream.
o The line ends with a semicolon ;, which is required to terminate statements in
C++.

5. Return Statement

• return 0;:
o The return statement ends the execution of the main function.
o Returning 0 generally indicates that the program executed successfully without
errors.

6. Input Statement

• cin >> sample;:


o cin is an object representing the standard input stream in C++, typically
associated with the keyboard.
o The >> operator is used to extract input from the standard input stream and store it
in the variable sample.

7. Comments

• Single-line comments:
o Written with //, anything after these two slashes on the same line is ignored by
the compiler.
• Multi-line comments:
o Written with /* to start and */ to end, everything between these markers is
ignored by the compiler.
• Comments are not executed and serve as notes for programmers to explain and document
the code.
Variables and Data Types in C++
1. Variables

• Definition:
o A variable is a named storage location in memory that holds a value, which can
be modified during program execution. It acts as a container to store data that
your program can manipulate.
• Characteristics:
o Symbol/Name: Each variable has a unique name (also known as an identifier)
that distinguishes it from other variables.
o Value: The data or information stored in the variable.
o Changeable: The value stored in a variable can change as the program runs,
allowing dynamic data handling.
o Temporary Storage: Variables store data temporarily while the program is
running. Once the program ends, the data in variables is lost unless it has been
saved elsewhere.

• Variable Types:
o Variables can represent different types of data, such as:
§ Numeric values (e.g., integers, floating-point numbers)
§ Characters (e.g., 'A', 'b')
§ Strings (e.g., "Hello World")
§ Memory addresses (used in pointers)
• Role in Programs:
o Variables are central to programming because they store and manipulate the data
that programs operate on.
o A program's purpose often revolves around the modification and use of variables
to achieve desired outcomes.

2. Components of a Variable

• Name (Identifier): The unique name given to a variable to identify it in the program.
• Data Type: Specifies the type of data the variable will store (e.g., int for integers, float
for floating-point numbers).
• Size: The amount of memory allocated to store the variable, which depends on the data
type.
• Value: The actual data stored in the variable.

3. Types of Variables

• Local Variables:
o Defined within a specific scope, such as inside a function or block of code.
o Scope: Only accessible within the block or function where they are declared.
o Lifetime: Exist only during the execution of that specific part of the program.

Global Variables:
• Declared outside of all functions and blocks, typically at the top of the program.
• Scope: Accessible from any part of the program after its declaration.
• Lifetime: Exist for the duration of the program's execution.

4. Rules for Naming Variables

• When naming variables (identifiers) in C++, certain rules must be followed:


o Allowed Characters: Only alphabets (A-Z, a-z), numbers (0-9), and the
underscore _ are allowed.
o Starting Character: The name must begin with an alphabet or an underscore (_).
It cannot start with a number.
o Reserved Words: Variable names cannot be reserved keywords in C++ (e.g.,
int, float, return).
o Case Sensitivity: Variable names are case-sensitive (var and Var are considered
different identifiers).
• Examples of valid and invalid variable names:
o Valid: age, total_amount, _index, count1
o Invalid: 1stNumber (starts with a number), float (reserved keyword), total-
amount (contains an invalid character -)

1. Constants

• Definition:
o A constant is a value that, unlike a variable, cannot be changed during the
execution of a program. Once a constant is defined, its value remains fixed.
• Characteristics:
o Immutability: Constants are immutable, meaning their values are set once and
cannot be altered.
o Usage: Due to their fixed nature, constants are often used to represent values that
are universally consistent, such as mathematical constants (e.g., π) or fixed
configuration values.
• Examples:
o Numbers: 3.142, 25, -10
o Characters: 'A', '$'
o Strings: "Hello, World!", "C++ Programming"
• Practical Example:
o To calculate the area of a circle:
§ Variables: area, r (radius)
§ Constant: π (pi) = 3.142

2. Data Types

• Definition:
o A data type defines the type of data a variable or constant can hold. It specifies
the size and layout of the variable's memory, the range of values it can store, and
the set of operations that can be applied to it.
• Importance:
o Data types are fundamental to programming because they help manage and
organize the information stored in a program.
o They ensure that operations are performed correctly according to the nature of the
data.
• Different Data Types in C++:
o Integer:
§ Represents whole numbers (positive, negative, or zero) without a
fractional part.
§ Examples: 0, 1, -125, 144457
§ Sizes:
§ short int: Typically 2 bytes (e.g., -32,768 to 32,767)
§ int: Typically 4 bytes (e.g., -2,147,483,648 to 2,147,483,647)
§ long int: Typically 4 bytes or more, depending on the system.
§

Floating-point:

• Represents numbers with a decimal point (fractional numbers).


• Examples: 3.0, -111.5
• Floating-point types include:
o float: Typically 4 bytes, less precise, but faster.
o double: Typically 8 bytes, more precise, used for most floating-point
calculations.
o long double: Typically 10 bytes or more, for very precise calculations.

Character:

• Represents a single character, such as a letter, number, or symbol.


• Stored in a single byte.
• Examples: 'a', 'A', '@', '$', '2'

String:

• Represents a sequence of characters (text).


• In C++, a string is an array of characters terminated by a null character \0.
• Examples: "Kuala Lumpur", "Computer", "John White"

Boolean:

• Represents a logical value: true or false.


• Typically used for conditions and flags.
3. Declaration of Variables

• Purpose:
o Declaring a variable serves two main purposes:
1. Type Association: It assigns a data type and a name (identifier) to the
variable, allowing the compiler to interpret the variable's operations
correctly.
2. Memory Allocation: It instructs the compiler to allocate the appropriate
amount of memory and associate an address with the variable.

Here’s a more organized and detailed explanation of Constants and Data Types in C++:

Constants and Data Types in C++


1. Constants

• Definition:
o A constant is a value that, unlike a variable, cannot be changed during the
execution of a program. Once a constant is defined, its value remains fixed.
• Characteristics:
o Immutability: Constants are immutable, meaning their values are set once and
cannot be altered.
o Usage: Due to their fixed nature, constants are often used to represent values that
are universally consistent, such as mathematical constants (e.g., π) or fixed
configuration values.
• Examples:
o Numbers: 3.142, 25, -10
o Characters: 'A', '$'
o Strings: "Hello, World!", "C++ Programming"
• Practical Example:
o To calculate the area of a circle:
§ Variables: area, r (radius)
§ Constant: π (pi) = 3.142

cpp
Copy code
const float PI = 3.142; // Constant declaration
float area, r;
area = PI * r * r;
2. Data Types

• Definition:
o A data type defines the type of data a variable or constant can hold. It specifies
the size and layout of the variable's memory, the range of values it can store, and
the set of operations that can be applied to it.
• Importance:
o Data types are fundamental to programming because they help manage and
organize the information stored in a program.
o They ensure that operations are performed correctly according to the nature of the
data.
• Different Data Types in C++:
o Integer:
§ Represents whole numbers (positive, negative, or zero) without a
fractional part.
§ Examples: 0, 1, -125, 144457
§ Sizes:
§ short int: Typically 2 bytes (e.g., -32,768 to 32,767)
§ int: Typically 4 bytes (e.g., -2,147,483,648 to 2,147,483,647)
§ long int: Typically 4 bytes or more, depending on the system.
§ Examples:

int age = 25;


short int smallNumber = 32000;
long int largeNumber = 1000000;

o Floating-point:
§ Represents numbers with a decimal point (fractional numbers).
§ Examples: 3.0, -111.5
§ Floating-point types include:
§ float: Typically 4 bytes, less precise, but faster.
§ double: Typically 8 bytes, more precise, used for most floating-
point calculations.
§ long double: Typically 10 bytes or more, for very precise
calculations.
§ Examples:

float temperature = 36.6f;


double pi = 3.141592653589793;

o Character:
§ Represents a single character, such as a letter, number, or symbol.
§ Stored in a single byte.
§ Examples: 'a', 'A', '@', '$', '2'
§ Example:

char grade = 'A';


char symbol = '$';

o String:
§ Represents a sequence of characters (text).
§ In C++, a string is an array of characters terminated by a null character \0.
§ Examples: "Kuala Lumpur", "Computer", "John White"
§ Example:

std::string cityName = "Kuala Lumpur";


std::string name = "John White";
o Boolean:
§ Represents a logical value: true or false.
§ Typically used for conditions and flags.
§ Examples:

bool isRaining = true;


bool isFinished = false;
3. Declaration of Variables

• Purpose:
o Declaring a variable serves two main purposes:
1. Type Association: It assigns a data type and a name (identifier) to the
variable, allowing the compiler to interpret the variable's operations
correctly.
2. Memory Allocation: It instructs the compiler to allocate the appropriate
amount of memory and associate an address with the variable.

4. Constant Declaration

• Purpose:
o Constants are often used to define values that do not change throughout the
program, such as mathematical constants or fixed configuration values
CHAPTER IV

ARITHNETIC OPERATORS

Arithmetic operators, also known as mathematical operators, are used in programming to


perform basic mathematical operations on numerical data types. Here’s a breakdown of the most
common arithmetic operators:

1. Addition Program

Situation:
You are developing a simple calculator program for an elementary school. The program needs to
add two numbers entered by the user. The program should display the sum of these two numbers.

Programming Task:
Write a program that prompts the user to enter two integers. The program should then compute
and display the sum of these two numbers.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;

int sum = a + b;
cout << "Sum of " << a << " and " << b << " is " << sum << endl;

return 0;
}

Explanation:

• The program prompts the user to enter two integers.


• It then calculates the sum using the + operator and displays the result.

2. Subtraction Program

Situation:
A store manager needs a program to calculate the difference between the total sales and the
expenses to determine the profit. The sales and expenses are both input by the user.
Programming Task:
Write a program that takes the total sales and expenses as inputs from the user. The program
should then calculate and display the profit by subtracting the expenses from the sales.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;

int difference = a - b;
cout << "Difference between " << a << " and " << b << " is " << difference << endl;

return 0;
}

Explanation:

• The program prompts the user to enter two integers.


• It then calculates the difference using the - operator and displays the result.

3. Multiplication Program

Situation:
A factory worker needs a program to calculate the total production output. Each machine in the
factory produces a certain number of items per hour, and the factory operates for a certain
number of hours each day.

Programming Task:
Write a program that asks the user to input the number of items produced by one machine per
hour and the number of hours the factory operates each day. The program should then calculate
and display the total number of items produced by the machine in one day.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;

int product = a * b;
cout << "Product of " << a << " and " << b << " is " << product << endl;

return 0;
}
Explanation:

• The program prompts the user to enter two integers.


• It calculates the product using the * operator and displays the result.

4. Division Program

Situation:
A teacher is preparing a program to help students understand division. The program should take
two numbers as input: the total number of candies and the number of students. It should then
calculate how many candies each student will get.

Programming Task:
Write a program that takes the total number of candies and the number of students as inputs. The
program should then calculate and display how many candies each student will get. If the
number of students is zero, the program should display an error message.

#include <iostream>
using namespace std;

int main() {
float a, b;
cout << "Enter two numbers: ";
cin >> a >> b;

if (b != 0) {
float quotient = a / b;
cout << "Quotient of " << a << " divided by " << b << " is " <<
quotient << endl;
} else {
cout << "Error: Division by zero is not allowed." << endl;
}

return 0;
}

Explanation:

• The program prompts the user to enter two floating-point numbers.


• It checks if the divisor is not zero before performing the division using the / operator.
• The result is displayed, or an error message is shown if the divisor is zero.
5. Modulus Program

Situation:
A packaging company needs to distribute items into boxes. They want to know how many items
will be left after evenly distributing the items into a given number of boxes.

Programming Task:
Write a program that takes the total number of items and the number of boxes as inputs. The
program should calculate and display the number of items that will be left over after distributing
them evenly among the boxes. If the number of boxes is zero, the program should display an
error message.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;

if (b != 0) {
int remainder = a % b;
cout << "Remainder of " << a << " divided by " << b << " is " <<
remainder << endl;
} else {
cout << "Error: Division by zero is not allowed." << endl;
}

return 0;
}

Explanation:

• The program prompts the user to enter two integers.


• It checks if the divisor is not zero before performing the modulus operation using the %
operator.
• The remainder is displayed, or an error message is shown if the divisor is zero.

6. Exponentiation Program

Situation:
An engineer is designing a program to calculate the power consumption of a device. The device's
power consumption can be modeled as P=V2/RP = V^2 / RP=V2/R, where VVV is the voltage
and RRR is the resistance.

Programming Task:
Write a program that takes the voltage and resistance as inputs from the user. The program
should then calculate and display the power consumption using the formula P=V2/RP = V^2 /
RP=V2/R. Use the pow() function to calculate the square of the voltage.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double base, exponent;
cout << "Enter the base and exponent: ";
cin >> base >> exponent;

double result = pow(base, exponent);


cout << base << " raised to the power of " << exponent << " is " <<
result << endl;

return 0;
}

Explanation:

• The program prompts the user to enter a base and an exponent.


• It uses the pow() function from the <cmath> library to calculate the exponentiation.
• The result is then displayed.

You might also like