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

C++-Unit_1_2 Notes

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

C++-Unit_1_2 Notes

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

PROBLEM SOLVING USING OOP WITH C++

CHAPTER 1: PROBLEM SOLVING, ALGORITHM & FLOWCHART

1.1 PROGRAM DEVELOPMENT LIFE CYCLE (PDLC)


1.2 ALGORITHM
1.2.1 ADVANTAGES OF ALGORITHM
1.2.2 DISADVANTAGES OF ALGORITHM
1.3 FLOWCHART
1.3.1 ADVANTAGES OF FLOWCHART
1.3.2 DISADVANTAGES OF FLOWCHART

Advanatges and Disadvantages


Characteristics of POP and OOP
Characteristics of POP and OOP
BASIC CONCEPTS OF OOPS: Refer Notes
Class
Object
Data Abstarction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing

Sudheendra Mouli H C, Asst Professor Dept, Of Computer Application, GSSS-SSGFC


PROBLEM SOLVING USING OOP WITH C++

CHAPTER 1: PROBLEM SOLVING, ALGORITHM & FLOWCHART

PROBLEM-SOLVING
• Problem-solving is the process of using computational-methods and logical-
reasoning to find solutions to complex issues or tasks.
• This process is fundamental to developing software.

1.1 PROGRAM DEVELOPMENT LIFE CYCLE (PDLC)


• PDLC is a structured approach to developing software.
• It consists of six stages:
1) Problem Definition
2) Problem Analysis
3) Algorithm Development
4) Coding & Documentation
5) Testing & Debugging
6) Maintenance

1) Problem Definition
• This stage involves defining the problem that the software aims to solve.
• Key-Points
- Clearly identify and state the problem.
- Gather requirements from stakeholders to understand what they expect.
- Define the scope of the software-project, including its goals and objectives.
- Document the problem and requirements for later reference.
2) Problem Analysis
• In this stage, the problem defined earlier is analyzed to understand its nature, scope, and specific
requirements.
• Key-Points
- Break down the problem into smaller parts or modules.
- Analyze user needs to ensure the solution meets requirements.
- Consider time, budget, and technical limits.
- Assess if the problem can feasibly be solved with available resources.

Sudheendra Mouli H C, Asst Professor Dept, Of Computer Application, GSSS-SSGFC


PROBLEM SOLVING USING OOP WITH C++
3) Algorithm Development
• Here, algorithms are designed to solve each part of the problem identified in the
analysis stage.
• Key-Points
- Design algorithms to meet requirements.
- Use flowcharts, pseudocode, or structured English to show algorithms visually or in text.
- Ensure algorithms are clear, efficient, and logical.
- Keep scalability and maintainability in mind.
4) Coding & Documentation
• Coding involves implementing designed algorithms in a programming language.
Documentation involves describing the program's functionality, usage, and internals.
• Key-Points
- Write code following coding standards and best practices.
- Use appropriate data structures and programming constructs.
- Include comments and documentation in the code to explain its purpose, logic, and usage.
- Create user manuals, technical documentation, and comments for future
reference and maintenance.
5) Testing & Debugging
• Testing verifies that the software meets requirements and functions correctly. Debugging
identifies and fixes errors found during testing.
• Key-Points
- Develop test cases based on requirements and expected outcomes.
- Execute test cases to find errors, bugs, or inconsistencies.
- Fix issues to ensure the software works as intended.
- Conduct different types of testing like unit, integration, system, and acceptance testing.
6) Maintenance
• Maintenance includes making changes and updates to the software after
deployment.
• Key-Points
- Address bug fixes and enhancements based on feedback and changing needs.
- Optimize performance for new hardware or software.
- Update documentation to reflect changes.
- Plan for long-term maintenance with version control and bug tracking.

Sudheendra Mouli H C, Asst Professor Dept, Of Computer Application, GSSS-SSGFC


PROBLEM SOLVING USING OOP WITH C++
1.2 ALGORITHM
• An algorithm is a step by step procedure to solve a problem
• In other words, an algorithm is a sequence of instructions that act on some input
data to produce some output in a finite number of steps
• Algorithm is independent of any programming language
• Algorithm is written in the natural languages like English
• Five properties of algorithm are:
1) Input: An algorithm may have many inputs or no inputs at all
2) Output: An algorithm must produce at least 1 output as result
3) Finite: An algorithm should have finite number of steps and it should end after a finite time
4) Definite: Each step must be clear, well-defined and precise. There should be no any ambiguity
5) Effective: Each step must be simple and should take a finite amount of time
• Example 1: Write an algorithm to find sum of 2 numbers Step 1: Start
Step 2: Read Number1, Number2
Step 3: Compute Sum= Number1+Number2 Step 4: Write
Sum
Step 5: Stop
1.2.1 ADVANTAGES OF ALGORITHM
• Clear Steps: Algorithms provide simple, clear steps to solve problems.
• Effective Problem Solving: They break down problems into smaller, manageable parts.
• Reusability: You can reuse an algorithm for similar problems in the future.
1.2.2 DISADVANTAGES OF ALGORITHM
• Time-Consuming to Create: Creating an algorithm can take a lot of time.
• Requires Skill: Writing a good algorithm needs strong problem-solving skills.
• Limited Use: Algorithms are usually designed for specific problems and may not work for others
without changes.

Sudheendra Mouli H C, Asst Professor Dept, Of Computer Application, GSSS-SSGFC


PROBLEM SOLVING USING OOP WITH C++
1.3 FLOWCHART
• Flowchart is a pictorial representation of an algorithm
• In other words, flowchart shows the sequence of instructions in a program
• Flowcharts are compared with the blue print of a building
• Flowcharts are used in analyzing or designing a program
• Each step in the algorithm is represented by a different symbols
• Actual instructions are written within the symbols
• Symbols are connected by arrows
• Basic flowchart symbols are represented in below table

Symbols used in flowchart

• Example: Draw a flowchart to find sum of 2 numbers.

Sudheendra Mouli H C, Asst Professor Dept, Of Computer Application, GSSS-SSGFC


PROBLEM SOLVING USING OOP WITH C++
1.3.1 ADVANTAGES OF FLOWCHART
• Easy to Understand: Flowcharts clearly show the steps of a process. This makes it easier to
understand how things work.
• Improves Communication: They help team members and clients communicate better by providing
a simple visual guide to discuss a process.
• Helps in Problem Solving: Flowcharts make it easier to find and fix problems by showing the entire
process visually.
1.3.2 DISADVANTAGES OF FLOWCHART
• Complicated for Large Systems: Flowcharts can become confusing and hard to follow when used
for big or complex systems.
• Takes Time to Create: Making detailed flowcharts can take a lot of time, especially for processes that
change often.
• Not Very Flexible: Flowcharts might not work well for processes that are not straightforward,
as they usually show steps in a fixed order.

ALGORITHM VS. FLOWCHART

Sudheendra Mouli H C, Asst Professor Dept, Of Computer Application, GSSS-SSGFC


PROBLEM SOLVING AND PROGRAMMING USING
C++
BENEFITS OF OOPS:

 Object orientation contributes the solution of many problems associated with the development and
quality of softwareproducts.

 The new technology promises greater productivity better quality of software and lesser
maintainacecost.

The advantages are:

 It is possible to have multiple instances of an object without any interference.

 It is possible to map objects in the problem domain.

 It is easy to partition the work in a project based on objects.

 Object oriented system can be easily upgraded from small to large system.

 Software complexity can be easily managed.

 The principle of data hiding helps the programmer to build secure program that cannot be
accessed by other part of the program.

 Though inheritance we can eliminate redundancy and extend the use of exisiting class.

APPLICATIONS OF OOPS:
 Real Time System
 Stimulation and Modeling
 Object Oriented Data Base
 AI and Expert Systems
 Neural Network and Parallel Processing
 CIM/CAD/CAM system
 Hypertext, Hypermedia and expert text

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ CHAPTER 2: INTRODUCTION TO C++

2.1 FEATURES OF C++


2.2 GENERAL STRUCTURE OF C++ PROGRAM
2.3 STEPS IN C++ PROGRAM EXECUTION
2.4 CHARACTER SET
2.5 TOKENS
2.5.1 KEYWORDS
2.5.2 IDENTIFIER
2.5.3 CONSTANTS
2.6 BASIC DATA-TYPES
2.6.1 PRIMARY DATA-TYPES
2.6.2 QUALIFIERS
2.7 VARIABLE
2.7.1 RULES FOR DEFINING A VARIABLE
2.7.2 DECLARATION OF VARIABLE
2.7.3 INITIALIZATION OF VARIABLE
2.8 DATA INPUT/OUTPUT-FUNCTIONS
2.8.1 INPUT-FUNCTIONS
2.8.2 OUTPUT-FUNCTIONS

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
CHAPTER 2: INTRODUCTION TO C++

2.1 FEATURES OF C++


1) Object-Oriented Programming (OOP)
• C++ supports OOP concepts like classes, objects and inheritance.
• Classes are used to group data and functions into objects for modularity and reusability.
2) Strongly Typed Language
• C++ is statically typed, so variables must be declared with their data-types before use.
• Strong-typing catches errors during compilation. This can lead to more efficient code execution.
3) Standard Template Library (STL)
• STL provides template-classes and functions for common data-structures (e.g., vectors, lists) and
algorithms (sorting, searching).
• It promotes code reuse and productivity with pre-implemented, efficient solutions.
4) Memory-management
• C++ supports explicit memory-management through features like dynamic
memory-allocation (new/delete) and pointers.
• Developers can optimize memory-usage.
5) Performance
• C++ is known for efficiency and is suitable for systems-programming and games.
• It offers low-level control over hardware. This optimizes code for speed and memory.
6) Operator Overloading
• C++ allows overloading-operators (e.g., `+`, `-`, `*`) to define custom behaviors for user-defined types.
• This enhances code-readability and maintainability for operations on these types.
7) Multiple-inheritance
• C++ supports multiple-inheritance. This allows classes to inherit from more than one parent-class.
• This supports complex object-oriented designs.
8) Templates
• Templates in C++ enable generic-programming where types and functions can work with specified
parameters later.
• They reduce code duplication and enhance flexibility by allowing reusable-code for any data-type.
9) Exception Handling
• C++ uses `try`, `catch`, and `throw` for exception handling and managing errors.
• This separates error-handling logic from normal program flow, enhancing reliability.
10) Standardization
• C++ is standardized by ISO. This ensures consistency and portability across platforms and
compilers.
• New standards (e.g., C++11, C++14) introduce features, improve the language, and clarify its use for
developers.

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
2.2 GENERAL STRUCTURE OF C++ PROGRAM
#include <iostream> // Preprocessor-directive
using namespace std; // Namespace declaration
int main() // Main function
{
declaration section

statement-1 // Executable section starts


statement-2
statement-3 // Executable section ends
}
Preprocessor-directives
• The preprocessor accepts the source-program and prepares the source-program for compilation.
• The preprocessor-statements start with symbol #.
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to include the specified file- contents in the
beginning of the program.
• For ex:
#include< iostream >
Namespace Declaration
• Namespaces are used to organize code into logical-groups and avoid naming- conflicts.
main()
• Every C++ program should have a function-called as main().
• This the first function to be executed always.
• The statements enclosed within left and right brace is called body of the function.
• The main() function is divided into 2 parts:
i) Declaration section
• The variables that are used within the function main() should be declared in the declaration-
section only.
• The variables declared inside a function are called local-variables. Ex:
int p, t, r;
ii) Executable section
• This contains the instructions given to the computer to perform a specific task.
• The task may be to
→ display a message
→ read data or
→ add 2 numbers etc
• Comments are portions of the code ignored by the compiler. The comments
allow the user to make simple notes in the source-code.
// this is an example for single line comment
/* this is an example
for multiple line comment */

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++

• Program to display a message on the screen

#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++" << endl;
return 0;
}

Output:
Welcome to C++

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
2.3 STEPS IN C++ PROGRAM EXECUTION

1) Preprocessing
• Purpose: Before compilation, the preprocessor scans the source-code for
preprocessor-directives (`#include`, `#define`, etc.).
• Actions:
- Header inclusion: `#include` directives pull in contents of header-files.
- Macro substitution: `#define` macros are replaced with their defined-values.
2) Compilation
• Purpose: The preprocessed source-code is translated into machine-readable instructions.
• Actions:
- Syntax analysis: Checks syntax for correctness, identifies tokens (keywords, identifiers, literals).
- Semantic analysis: Validates semantics (type checking, function-calls, etc.).
- Code generation: Translates validated-code into assembly- or machine-code.

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3) Assembly (Optional step)
• Purpose: Translates the output of the compiler into object-code specific to the platform (if
compiling to assembly-code).
• Actions: Generates assembly-language-code or intermediate object-files (`.obj`).
4) Linking
• Purpose: Combines object-files and libraries to generate an executable-file.
• Actions:
- Symbol resolution: Resolves external-references to functions or variables used across different files.
- Static library inclusion: Links statically linked libraries (`.lib`, `.a`).
- Dynamic linking (optional): Resolves references to dynamically linked
libraries (`.dll`, `.so`).
5) Loading
• Purpose: The operating-system loads the executable-file into memory for
execution.
• Actions: Allocates memory-space for the program and initializes necessary data- structures.
6) Initialization:
• Purpose: Prepares the environment before `main()` execution.
• Actions: Initializes global-variables with default-values, sets up environment- variables, etc.
7) Execution of `main()` function
• Purpose: The entry-point where program execution begins.
• Actions: Executes statements inside `main()`, including variable-assignments, control flow
statements (`if`, `for`, `while`), and I/O-operations (`cout`, `cin`).

Note:
HOW TO LEARN C++ LANGUAGE?
• English is a universal language used to communicate with others.
• In the same way, C++ is a language used to communicate with computer. In other words, C++ is used
to instruct computer to perform particular task.
• The task can be
→ simple task like adding 2 numbers or
→ complex task like building a railway reservation system
• Before you play the game, you should learn rules of the game. So that you can play better and win easily.
In the same way, to write C++ programs, you should learn rules of C++ language.
STEPS TO LEARN C++ LANGUAGE
Step 1: Before speaking any language, you should first learn alphabets. In the same way, to learn C++
language, you should first learn alphabets in C++.
Step 2: Then, you should learn how to group alphabets in particular sequence to form a meaningful word.
In the same way, in C++ language, you should learn tokens (i.e. words).
Step 3: Then, you should learn how to group the words in particular sequence to form a meaningful
sentence. In the same way, in C++ language, you should learn instruction (i.e. sentence).
Step 4: Then, you should learn how to group the sentences in particular sequence to form a meaningful
paragraph. In the same way, in C++ language, you should learn program (i.e. paragraph).

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++CHARACTER SET
2.4
• Character-set refers to the set of alphabets, letters and some special-characters that are valid in C++
language.
• For example, the characters in C++ are:
→ Letters A-X, a-z, both upper and lower
→ Digits 0-9
→ Symbols such as + - * / %
→ White spaces

2.5 TOKENS
• A token is a smallest element of a C++ program.
• One or more characters are grouped in sequence to form meaningful words. These meaningful words are
called tokens.
• The tokens are broadly classified as follows
→ Keywords ex: if, for, while
→ Identifiers ex: sum, length
→ Constants ex: 10, 10.5, 'a', "sri"
→ Operators ex: + - * /
→ Special symbols ex: [], (), {}

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ KEYWORDS
2.5.1
• Keywords are tokens which are used for their intended-purpose only.
• Each keyword has fixed meaning and that cannot be changed by user. Hence, they
are also called reserved-words.
Rules for using keyboards
• Keywords cannot be used as a variable or function.
• All keywords should be written in lower letters.
• Some keywords are as listed below table

2.5.2 IDENTIFIER
• As the name indicates, identifier is used to identify various entities of program such as variables,
constants, functions etc.
• In other words, an identifier is a word consisting of sequence of
→ Letters
Digits or
→ "_"(underscore)
• For ex:
area, length, breadth

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ CONSTANTS
2.5.3
• A constant is an identifier whose value remains fixed throughout the execution of the program.
• The constants cannot be modified in the program.
• For example:
1, 3.14512 , “z‟, “gcwmaddur"
• Five different types of constants are:
1) Integer-constant
• An integer is a whole-number without any fraction-part.
• There are 3 types of integer-constants as listed in below table:

2) Floating-point-constant
• The floating-point-constant is a real-number.
• The floating-point-constants can be represented using 2 forms as listed in below table:

3) Character-constant
• A symbol enclosed within a pair of single-quotes(') is called a character-constant.
• Each character is associated with a unique-value called an ASCII (American Standard Code for
Information Interchange) code.
• For ex:
'9', 'a', '\n'
4) String-constant
• A sequence of characters enclosed within a pair of double-quotes(“) is called a
string-constant.
• The string always ends with NULL (denoted by \0) character.
• For ex:
"9" "a" "gcwmaddur" "\n"
5) Escape Sequence Characters
• An escape sequence character begins with a backslash and is followed by one character.
• A backslash (\) along with some characters give rise to special print effects by changing
(escaping) the meaning of some characters.

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
• The complete set of escape sequences are as listed in below table:

COMPARISON OF KEYWORDS, IDENTIFIERS, AND CONSTANTS

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++BASIC DATA-TYPES
2.6
• The data-type defines the type of data stored in a memory-location.
• C++ supports 3 classes of data-types:
1) Primary data-type e.g. int, flaot
2) Derived data-types e.g. array
3) User defined data-types e.g. structure, class
2.6.1 PRIMARY DATA-TYPES
1) int
• An int is a keyword which is used to define integers.
• Using int keyword, the programmer can inform the compiler that the data associated with this
keyword should be treated as integer.
• C++ supports 3 different sizes of integer:
→ short int
→ int
→ long int
2) float
• A float is a keyword which is used to define floating-point-numbers.
3) double
• A double is a keyword used to define long floating-point-numbers.
4) char
• A char is a keyword which is used to define single character.
5) bool
• A bool is a keyword which is used to define Boolean values (true or false).
6) void
• void is an empty data-type. Since no value is associated with this data-type, it does not occupy any
space in the memory.
• This is normally used in functions to indicate that the function does not return any
value.

2.6.2 QUALIFIERS
• Qualifiers alter the meaning of primary data-types to yield a new data-type.
1) Size Qualifiers
• Size-qualifiers alter the size of primary data-type.
• The keywords long and short are two size-qualifiers. For
example:
long int i; //The size of int is 4 bytes but, when long keyword is
//used, that variable will be of 8 bytes
short int i; //The size of int is 4 bytes but, when short keyword is
//used, that variable will be of 2 byte

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
2) Sign Qualifiers
• Whether a variable can hold positive-value, negative-value or both values is specified by sign-
qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
unsigned int a; //unsigned variable can hold zero & positive-values only signed int b;
//signed variable can hold zero , positive and negative-values
3) Constant Qualifiers
• Constant qualifiers can be declared with keyword ‘const’.
• An object declared by const cannot be modified.
const int p=20; //the value of p cannot be changed in the program.

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++VARIABLE
2.7
• A variable is an identifier whose value can be changed during execution of the program.
In other words, a variable is a name given to a memory-location where the data can be stored.
• Using the variable-name, the data can be
→ stored in a memory-location and
→ accessed or manipulated
2.7.1 RULES FOR DEFINING A VARIABLE
1) The first character in the variable should be a letter or an underscore(‘_’)
2) The first character can be followed by letters or digits or underscore
3) No extra symbols are allowed (other than letters, digits and underscore)
4) Length of a variable can be up to a maximum of 31 characters
5) Keywords should not be used as variable-names
• Valid variables:
z, principle_amount, gcw_maddur Invalid
variables:
3fact //violates rule 1
sum= sum-of-digits dollar$ //violates rule 3 for
int if //violates rule 5
2.7.2 DECLARATION OF VARIABLE
• The declaration tells the complier
→ what is the name of the variable used
→ what type of date is held by the variable
• Syntax:
data_type v1,v2,v3;
where v1,v2,v3 are variable-names data_type can
be int, float or char
• For ex:
int a, b, c; float x,
y, z;
2.7.3 INITIALIZATION OF VARIABLE
• The variables are not initialized when they are declared. Hence, variables normally contain garbage-
values and hence they have to be initialized with valid-data.
• Syntax is shown below:
data_type var_name=data;
where data_type can be int, float or char var_name
is a name of the variable
= is assignment operator
‘data’ is the value to be stored in variable
• For ex:
int a=10;
float pi=3.1416; char
c='z';

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
2.8 DATA INPUT/OUTPUT-FUNCTIONS
• C++ has several library-functions for input- and output-operations.
• For example:
`cin`, `cout`, `cerr`, `clog`.
• To use these functions in a C++ program, the preprocessor-statement
`#include<iostream>` must be included.
2.8.1 INPUT-FUNCTIONS
• Input-functions are used to read data from the keyboard and store it in a memory- location.
• For example:
`cin`: Reads input from the standard-input (keyboard).
• Syntax:
`int num;
cin >> num;` //reads the entered value into the variable `num`.
2.8.2 OUTPUT-FUNCTIONS
• Output-functions are used to receive data from memory-locations and display it on the monitor.
• For example:
`cout`: Writes output to the standard-output (screen).
• Syntax:
`cout << "Hello!";` // This Displays "Hello!" followed by a newline by default.
• Program which asks user for their name and age, then prints a greeting message.

#include <iostream>
using namespace std;

int main() {
// Variables to store user input
string name;
int age;

// Prompt user for input


cout << "Enter your name: ";
cin >> name;

cout << "Enter your age: ";


cin >> age;

// Output greeting message


cout << "Hello, " << name << "! You are " << age << " years old." << endl;

return 0;
}
Output:
Enter your name: Rama
Enter your age: 30
Hello, Rama! You are 30 years old.

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++

INPUT FUNCTIONS VS OUTPUT FUNCTIONS

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application ,GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
CHAPTER 3: OPERATORS & EXPRESSIONS

3.1 OPERATOR
3.1.1 ARITHMETIC OPERATORS
3.1.2 RELATIONAL OPERATORS
3.1.3 LOGICAL OPERATORS
3.1.4 ASSIGNMENT OPERATOR
3.1.5 SHORTHAND OPERATORS
3.1.6 CONDITIONAL OPERATOR
3.1.7 BITWISE OPERATORS
3.1.8 COMMA OPERATOR
3.1.9 sizeof OPERATOR
3.1.10 INCREMENT/DECREMENT OPERATORS
3.1.10.1 INCREMENT OPERATOR
3.1.10.2 DECREMENT OPERATOR
3.1.11 SCOPE RESOLUTION OPERATOR
3.2 EXPRESSION
3.2.1 ARITHMETIC EXPRESSIONS
3.2.2 RELATIONAL-EXPRESSIONS
3.2.3 LOGICAL-EXPRESSIONS
3.3 PRECEDENCE AND ASSOCIATIVITY
3.3.1 PRECEDENCE OF OPERATORS
3.3.2 ASSOCIATIVITY OF OPERATORS
3.3.2.1 LEFT-ASSOCIATIVE OPERATORS
3.3.2.2 RIGHT-ASSOCIATIVE OPERATORS
3.4 TYPE CONVERSION
3.4.1 TYPE CONVERSION (IMPLICIT CONVERSION)
3.4.2 TYPE CASTING (EXPLICIT CONVERSION)

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
CHAPTER 3: OPERATORS & EXPRESSIONS

3.1 OPERATOR
• An operator specifies what operation need to be performed on the data.
• For ex:
+ indicates add operation
* indicates multiplication operation
Operand
• An operand can be a constant or a variable.
Expression
• An expression is combination of operands and operator that reduces to a single- value.
• For ex:
Consider the following expression a+b here a and
b are operands
+ is an operator

CLASSIFICATION OF OPERATORS

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ ARITHMETIC OPERATORS
3.1.1
• These operators are used to perform arithmetic operations.
• There are 5 arithmetic operators:

• Program to demonstrate the working of arithmetic operators.

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
#include
C++ <iostream>
using namespace std;
int main() {
int a = 9, b = 4, c;

c = a + b;
cout << "a+b=" << c << endl;

c = a - b;
cout << "a-b=" << c << endl;

c = a * b;
cout << "a*b=" << c << endl;

c = a / b;
cout << "a/b=" << c << endl;

c = a % b;
cout << "Remainder when a divided by b=" << c << endl;

return 0;
}

Output:
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ RELATIONAL OPERATORS
3.1.2
• Relational operators are used to find the relationship between two operands.
• The output of relational-expression is either true (1) or false (0).
• For example
a>b // If a is greater than b,
// then a>b returns 1
// else a>b returns 0.
• The 2 operands may be constants, variables or expressions.
• There are 6 relational operators:

• For ex:
Condition Return values
2>1 1 (or true)
2>3 0 (or false)
3+2<6 1 (or true)
• Program to illustrate the use of relational operators.

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
#include
C++ <iostream>

int main() {
cout << "4>5 : " << (4 > 5) << endl;
cout << "4>=5 : " << (4 >= 5) << endl;
cout << "4<5 : " << (4 < 5) << endl;
cout << "4<=5 : " << (4 <= 5) << endl;
cout << "4==5 : " << (4 == 5) << endl;
cout << "4!=5 : " << (4 != 5) << endl;

return 0;
}
Output:
4>5 : 0
4>=5 : 0
4<5 : 1
4<=5 :1
4==5 : 0
4!=5 : 1

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ LOGICAL OPERATORS
3.1.3
• These operators are used to perform logical operations.
• The output of logical-expression is either true (1) or false (0).
• There are 3 logical operators:
Operator Meaning Example
&& Logical AND If c=5 and d=2 then ((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then ((c==5) || (d>5)) returns true.
! Logical NOT If c=5 then !(c==5) returns false.
• All non-zero values (i.e. 1, -1, 2, -2) will be treated as true. While zero
value (i.e. 0) will be treated as false.

• Program to illustrate the use of logical operators


#include <iostream>
using namespace std;

int main() {

cout << "7 && 0 : " << (7 && 0) << endl;


cout << "7 || 0 : " << (7 || 0) << endl; cout
<< "!0 : " << (!0) << endl;

return 0;
}
Output:
7 && 0 : 1
7 || 0 : 1
!0 : 1

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ ASSIGNMENT OPERATOR
3.1.4
• The most common assignment operator is =.
• This operator assigns the value in right side to the left side.
• Syntax:
variable=expression;
• For ex:
c=5; //5 is assigned to c
b=c; //value of c is assigned to b 5=c;
// Error! 5 is a constant.
• Program to demonstrate the working of assignment operator.
#include <iostream>
using namespace std;

int main() {
int a = 9, b = 4, c;

c = a + b;
cout << "a+b=" << c << endl;

return 0;
}
Output:
a+b=13

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.1.5 SHORTHAND OPERATORS
• Shorthand operators combine an arithmetic operation with assignment.
• Syntax:
`op=`
where `op` is an arithmetic operator.
• For ex,
a=a+10: can be written as a+=10;
• In the same way, we have:
Operator Example Same as
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
• Program to illustrate the usage of the shorthand operators.
#include <iostream>
using namespace std;

int main() {
int num = 10;
cout << "Initial value of num: " << num << endl;

// Shorthand operators
num += 5; // Equivalent to num =
num + 5; cout << "After num += 5: " << num << endl;

return 0;
}
Output:
Initial value of num: 10
After num += 5: 15

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ CONDITIONAL OPERATOR
3.1.6
• The conditional operator is also called ternary operator as it takes three operands.
• Conditional operators are used for decision making in C++.
• Syntax:
(exp1)? exp2: exp3;
where exp1 is an expression evaluated to true or false; If exp1 is
evaluated to true, exp2 is executed;
If exp1 is evaluated to false, exp3 is executed.
• Program to find largest of 2 numbers using conditional operator.
#include <iostream>
using namespace std;

int main() {
int a, b, max;
cout << "Enter 2 distinct numbers: " << endl;
cin >> a >> b;

max = (a > b) ? a : b;
cout << "Largest number = " << max << endl;

return 0;
}
Output:
enter 2 distinct numbers
34
largest number = 4

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ BITWISE OPERATORS
3.1.7
• These operators are used to perform logical operation (and, or, not) on individual bits of a binary-
number.
• There are 6 bitwise operators:
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
• For ex,
Ex for ~ (bitwise complement) a = 13 Ex for & (bitwise AND)
0000 1101 a = 13 0000 1101
~a= 11110010 b=6 0000 0110
a&b 0000 0100
Ex for || (bitwise OR) Ex for ^ (bitwise xor)
a = 13 0000 1101 a = 13 0000 1101
b=6 0000 0110 b=6 0000 0110
a|b 0000 1111 a^b 0000 1011
• The operator that is used to shift the data by a specified number of bit positions towards left or
right is called shift operator.
The syntax is shown below for << The syntax is shown below for >>
b=a << num; b=a >> num;
where ‘a’ is value to be shifted
‘num’ is number of bits to be shifted
Ex for <<(left shift): Ex for >>(right shift): a
a = 13 0000 1101 = 13 0000
b=a<<1 0001 1010 1101
b=a<<1 0000 0110

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
• Program to illustrate the usage of the Bitwise Operators #include
<iostream>
using namespace std;

int main() {
// Variables for demonstration
unsigned int num1 = 13; // Binary: 0000 1101
unsigned int num2 = 6; // Binary: 0000 0110
unsigned int result;

// Bitwise AND
result = num1 & num2;
cout << "Bitwise AND (num1 & num2): " << result << endl;

// Bitwise OR
result = num1 | num2;
cout << "Bitwise OR (num1 | num2): " << result << endl;

// Bitwise XOR
result = num1 ^ num2;
cout << "Bitwise XOR (num1 ^ num2): " << result << endl;

// Bitwise NOT
result = ~num1;
cout << "Bitwise NOT (~num1): " << result << endl;

// Left shift
result = num1 << 1;
cout << "Left shift (num1 << 1): " << result << endl;

// Right shift
result = num1 >> 1;
cout << "Right shift (num1 >> 1): " << result << endl;

return 0;
}
Output:
Bitwise AND (num1 & num2): 4 Bitwise OR
(num1 | num2): 15 Bitwise XOR (num1 ^
num2): 11 Bitwise NOT (~num1):
4294967282 Left shift (num1 << 1): 26
Right shift (num1 >> 1): 6

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.1.8 COMMA OPERATOR
• Comma operator allows multiple-expressions to be evaluated within a single- statement.
• This operator
 evaluates each expression from left to right and
 returns the result of the rightmost expression.
• Syntax:
`expression1, expression2, ..., expressionN`
• This operator is often used in `for` loops, function-calls, and variable-declarations.
• Program to illustrate the usage of the comma operator.
#include <iostream>
using namespace std;

int main() {
int a = 1, b = 2, c = 3;

// Using comma operator in a single-statement


int result = (a += 5, b += 10, c += 15);

// Output results
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "Result = " << result << endl;
return 0;
}
Output:
a=6
b = 12
c = 18
Result = 18

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.1.9 sizeof OPERATOR
• This operator is used to determine the size, in bytes, of a data-type.
• Syntax:
`sizeof(type)`
• This operator is commonly used to determine storage-requirements.
• Program to illustrate the usage of the `sizeof` operator. #include
<iostream>
using namespace std;

int main() {
int intSize = sizeof(int);
double doubleSize = sizeof(double); char
charSize = sizeof(char);
bool boolSize = sizeof(bool);

cout << "Size of int: " << intSize << " bytes" << endl;
cout << "Size of double: " << doubleSize << " bytes" << endl; cout << "Size
of char: " << charSize << " byte" << endl;
cout << "Size of bool: " << boolSize << " byte" << endl; return 0;
}
Output:
Size of int: 4 bytes Size of
double: 8 bytes Size of
char: 1 byte Size of bool: 1
byte

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ INCREMENT/DECREMENT OPERATORS
3.1.10
3.1.10.1 INCREMENT OPERATOR
• ++ is an increment operator.
• As the name indicates, increment means increase, i.e. this operator is used to
increase the value of a variable by 1.
• For example:
If b=5
then b++ or ++b; // b becomes 6
• The increment operator is classified into 2 categories:
1) Post increment Ex: b++
2) Pre increment Ex: ++b
• As the name indicates, post-increment means first use the value of variable and then increase the
value of variable by 1.
• As the name indicates, pre-increment means first increase the value of variable by 1 and then use the
updated value of variable.
• For ex:
If x is 10,
then z= x++; sets z to 10 but z =
++x; sets z to 11
• Program to illustrate the use of increment operators.
#include <iostream>
using namespace std;

int main() {
int x = 10, y = 10, z;

z = x++;
cout << "z = " << z << " x = " << x << endl;

z = ++y;
cout << "z = " << z << " y = " << y << endl;

return 0;
}
Output:
z=10 x=11
z=11 y=11

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.1.10.2 DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is used to decrease the value of
a variable by 1.
• For example:
If b=5
then b-- or --b; // b becomes 4
• Similar to increment operator, the decrement operator is classified into 2
categories:
1) Post decrement Ex: b--
2) Pre decrement Ex: --b
• For ex:
If x is 10,
then z= x--; sets z to 10, but z = --
x; sets z to 9.
• Program to illustrate the use of decrement operators.
#include <iostream>
using namespace std;

int main() {
int x = 10, y = 10, z;

z = x--;
cout << "z = " << z << " x = " << x << endl;

z = --y;
cout << "z = " << z << " y = " << y << endl;

return 0;
}
Output:
z=10 x=9
z=9 y=9

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
INCREMENT OPERATOR VS. DECREMENT OPERATOR

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.1.11 SCOPE RESOLUTION OPERATOR
• This operator is used to access global-variables from within local scopes such as functions.
• Syntax: `
::variable_name`
• This operator is used to differentiate between local and global-variables with the same name.
• This operator helps in accessing global-variables within any scope without
ambiguity.
• Program to illustrate the use of Scope Resolution operator.
#include <iostream>
using namespace std;
int globalVar = 100; // Global-variable

int main() {
int localVar = 50; // Local variable

cout << "Global-variable: " << globalVar << endl;


cout << "Local variable: " << localVar << endl;

cout << "Accessing globalVar: " << ::globalVar << endl;

return 0;
}
Output:
Global-variable: 100
Local variable: 50
Accessing globalVar: 100

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++EXPRESSION
3.2
• An expression is combination of operands and operator that reduces to a single- value.
• For examples: Simple expressions: `x + y`, `5 * z`
Complex expressions: `a + b * (c - d)`
• Expressions are used to perform computations, assign values, or compare values.

3.2.1 ARITHMETIC EXPRESSIONS


• Arithmetic expressions performs basic arithmetic operations on numeric data-types (`int`, `float`).
• Program to illustrate the use of Arithmetic Expressions.
#include <iostream>
using namespace std;

int main() {
int a = 9, b = 4, c;

c = a + b;
cout << "a+b=" << c << endl;
c = a - b;
cout << "a-b=" << c << endl;
return 0;
}
Output:
a+b=13
a-b=5

3.2.2 RELATIONAL-EXPRESSIONS
• Relational-expressions compare two values and return a Boolean result (`true` or
`false`).
• They are used in decision-making statements like `if`, `while`, and `for` loops:
• Program to illustrate the use of Relational-expressions.
#include <iostream>
using namespace std;

int main() {
cout << "4>5 : " << (4 > 5) << endl;
cout << "4>=5 : " << (4 >= 5) << endl;
return 0;
}
Output:
4>5 : 0
4>=5 : 0
4<5 : 1

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.2.3 LOGICAL-EXPRESSIONS
• Logical-expressions combine multiple conditions using logical operators (`&&`,
`||`, `! `).
• They evaluate to `true` or `false` based on the truth values of their operands.
• Program to illustrate the use of Logical-expressions.
#include <iostream>
using namespace std;

int main() {
cout << "7 && 0 : " << (7 && 0) << endl;
cout << "7 || 0 : " << (7 || 0) << endl;
return 0;
}
Output:
7 && 0 : 1
7 || 0 : 1

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.3 PRECEDENCE AND ASSOCIATIVITY
3.3.1 PRECEDENCE OF OPERATORS
• The order in which different operators are used to evaluate an expression is called
precedence of operators.
• Operators with higher-precedence are evaluated before operators with lower- precedence.
Example: Arithmetic operator (`*`) has higher-precedence than addition (`+`).
• Parentheses ` () ` can be used to explicitly control the order of evaluation in expressions.
Example:
(a + b) * c ensures that addition is performed before multiplication, overriding default precedence

Precedence Table

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++

• Program to illustrate the use of Precedence.


#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5, c = 2;
int result = a + b * c; // * has higher-precedence than +
cout << "Result of a + b * c: " << result << endl;
return 0;

}
Output:
Result of a + b * c: 20

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.3.2 ASSOCIATIVITY OF OPERATORS
• Associativity determines the order in which operators of the same precedence are grouped and
evaluated.
• Two types of associativity:
1) Left-associative (`left-to-right`)
2) Right-associative (`right-to-left`)

3.3.2.1 LEFT-ASSOCIATIVE OPERATORS


• Operators are evaluated from left to right if they have the same precedence level.
• Example: Addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), etc.
• Program to illustrate the use of Left-Associative Operators
#include <iostream>
using namespace std;

int main() {

int result = 10 - 5 + 3; // Left-associative operators: subtraction and addition cout

<< "Result: " << result << endl;


return 0;
}

Output:
Result: 8

3.3.2.2 RIGHT-ASSOCIATIVE OPERATORS


• Operators are evaluated from right to left if they have the same precedence level.
• Example: Assignment (`=`), conditional operator (`?:`), etc.
• Program to illustrate the use of Right-Associative Operators

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
#include
C++ <iostream>
using namespace std;

int main() {
int a = 5, b = 10, c = 15;

a = b = c; // Right-associative operator: assignment

cout << "a: " << a << ", b: " << b << ", c: " << c << endl;

return 0;
}

Output:
a: 15, b: 15, c: 15

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
LEFT-ASSOCIATIVE OPERATORS VS. RIGHT-ASSOCIATIVE OPERATORS

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++TYPE CONVERSION
3.4
• Type conversion is used to convert data of one type to data of another type.
• Type conversion is of 2 types:
1) Type Conversion (Implicit Conversion)
2) Type Casting (Explicit Conversion)

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++ TYPE CONVERSION (IMPLICIT CONVERSION)
3.4.1
• If a compiler converts one type of data into another type of data automatically, it is known as implicit
conversions.
• There is no data loss in implicit conversion.
• The conversion always takes place from lower rank to higher rank.
• If one operand type is same as other operand type, no conversion takes place and type of result remains
same as the operands i.e. int+int=int
float+float=float
• Conversion rules are as follows:
→ If either operand is long double, convert the other to long double.
→ Otherwise, if either operand is double, convert the other to double.
→ Otherwise, if either operand is float, convert the other to float.
→ Otherwise, convert char and short to int.
→ Then, if either operand is long, convert the other to long.
• Program to illustrate implicit conversion.
#include <iostream>
using namespace std;

int main()
{ int a =
5;
double b = 10.5;

double result = a + b; // Implicit conversion of 'a' to double before addition

cout << "Result: " << result << endl;


return 0;
}
Output:
Result: 15.5

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++
3.4.2 TYPE CASTING (EXPLICIT CONVERSION)
• When the data of one type is converted explicitly to another type with the help of some pre-defined
functions, it is called as explicit conversion.
• There may be data loss in this process because the conversion is forceful.
• Syntax:
data_type1 v1;
data_type2 v2 = static_cast<data_type2>(v1);
where v1 can be expression or variable
• Program to illustrate explicit conversion.
#include <iostream>
int main() {
float b = 11.000000;
int c = 22;
float d = b / static_cast<float>(c);

cout << "b = " << b << endl;


cout << "c = " << c << endl;
cout << "d = " << d << endl;

return 0;
}
Output:
b = 11
c = 22
d = 0.5

IMPLICIT CONVERSION VS. EXPLICIT CONVERSION

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


PROBLEM SOLVING AND PROGRAMMING USING
C++

Sudheendra Mouli H C, Asst Professor, Dept Of Computer Application, GSSS-SSFGC


****

CHAPTER 4: CONTROL STRUCTURES

4.1 BASIC CONCEPT OF DECISION-STATEMENTS


4.1.1 THE if STATEMENT
4.1.2 THE if else STATEMENT
4.1.3 THE nested if STATEMENT
4.1.4 THE else if LADDER STATEMENT
4.1.5 THE switch-statement
4.2 BASIC CONCEPT OF LOOP
4.2.1 THE while LOOP
4.2.2 THE for LOOP
4.2.3 THE do while STATEMENT
4.2.4 NESTED LOOPS
4.3 break AND continue STATEMENTS
4.3.1 THE break STATEMENT
4.3.2 THE continue STATEMENT

****
****

CHAPTER 4: CONTROL STRUCTURES

INTRODUCTION TO CONTROL STRUCTURES


• A program is nothing but the execution of sequence of one or more instructions.
• Quite often, it is desirable to change the order of execution of statements based on
certain conditions
• This involves a kind of decision making to see whether a particular condition has occurred or not
and direct the computer to execute certain statements accordingly.
• Based on application, it is necessary / essential
i) To alter the flow of a program
ii) Test the logical conditions
iii) Control the flow of execution as per the selection.
• These conditions can be placed in the program using decision-making statements.

C++ SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS


1) Decision making statements
i) if statement
ii) if else statement
iii) nested if statement
iv) else if ladder
v) switch-statement
2) Loop control statements
i) while loop
ii) for loop
iii) do-while loop
3) Unconditional control statements
i) break statement
ii) continue statement

****
***

4.1 BASIC CONCEPT OF DECISION-STATEMENTS


• Decision making is critical to computer programming.
• There will be many situations when you will be given 2 or more options and you will have to select an
option based on the given conditions.
• For ex, we want to print a remark about a student based on secured marks and following is the
situation:
1. Assume given marks are x for a student
2. If given marks are more than 95 then
3. Student is brilliant
4. If given marks are less than 30 then
5. Student is poor
6. If given marks are less than 95 and more than 30 then
7. Student is average
• Now, question is how to write programming code to handle such situation. C++ language provides
conditional i.e., decision making statements which work based on the following flow diagram:

• There are 5 types of decision-statements:


i) if statement
ii) if else statement
iii) nested if statement
iv) else if ladder
v) switch-statement

****
***

4.1.1 THE if STATEMENT


• This is basically a “one-way” decision-statement.
• This is used when we have only one alternative.
• Syntax:
if(expression)
{
statement1;
}
• Firstly, the expression is evaluated to true or false.
If the expression is evaluated to true, then statement1 is executed.
If the expression is evaluated to false, then statement1 is skipped.
• The flow diagram is shown below:

• Program to illustrate the use of if statement


#include <iostream>
using namespace std;

int main()
{ int n;
cout << "Enter any non zero integer: " << endl;
cin >> n;

if (n > 0)
cout << "Number is a positive number" << endl;
if (n < 0)
cout << "Number is a negative number" << endl;

return 0;
}
Output:
Enter any non zero integer:
7
Number is positive number

****
***

4.1.2 THE if else STATEMENT


• This is basically a “two-way” decision-statement.
• This is used when we must choose between two alternatives.
• Syntax:
if(expression)
{
statement1;
}
else
{
statement2;
}
• Firstly, the expression is evaluated to true or false.
If the expression is evaluated to true, then statement1 is executed.
If the expression is evaluated to false, then statement2 is executed.
• The flow diagram is shown below:

• Program to illustrate the use of if else statement.


#include <iostream>
using namespace std;

int main()
{ int n;
cout << "Enter any non-zero integer: " << endl;
cin >> n;

if (n > 0)
cout << "Number is a positive number" << endl;
else
cout << "Number is a negative number" << endl;

return 0;
}
Output:
Enter any non-zero integer:
7
Number is positive number

****
4.1.3 THE nested if STATEMENT
• An if-else statement within another if-else statement is called nested if statement.
• This is used when an action has to be performed based on many decisions. Hence, it is called as multi-
way decision-statement.
• Syntax:
if(expr1)
{
if(expr2)
statement1

else
} statement2
else
{
if(expr3)
statement3
else
statement4
}
• Here, firstly expr1 is evaluated to true or false.
If the expr1 is evaluated to true, then expr2 is evaluated to true or false.
If the expr2 is evaluated to true, then statement1 is executed. If the expr2 is
evaluated to false, then statement2 is executed.
If the expr1 is evaluated to false, then expr3 is evaluated to true or false.
If the expr3 is evaluated to true, then statement3 is executed. If the expr3 is
evaluated to false, then statement4 is executed.
• The flow diagram is shown below:
• Program to select and print the largest of the 3 numbers using nested “if-else”
statements.
#include <iostream>
using namespace std;

int main()
{ int a, b, c;
cout << "Enter Three Values: " << endl;
cin >> a >> b >> c;

cout << "Largest Value is: ";


if (a > b) {
if (a > c)
cout << a << endl;
else
cout << c << endl;
} else {
if (b > c)
cout << b << endl;
else
cout << c << endl;
}

return 0;
}

Output:
Enter Three Values:
786
Largest Value is: 8
4.1.4 THE else if LADDER STATEMENT
• This is basically a “multi-way” decision-statement.
• This is used when we must choose among many alternatives.
• Syntax:
if(expression1)
statement1; else
if(expression2)
statement2;
else if(expression3)
statement3 else
if(expression4)
statement4
else
default statement5
• The expressions are evaluated in order (i.e. top to bottom).
• If an expression is evaluated to true, then
→ statement associated with the expression is executed &
→ control comes out of the entire else if ladder
• For ex, if exprression1 is evaluated to true, then statement1 is executed.
If all the expressions are evaluated to false, the last statement4 (default case) is executed.
• Program to illustrate the use of else if ladder statement.
#include <iostream>
using namespace std;

int main() {
char grade; // local variable definition
cout << "Enter grade A to D: " << endl;
cin >> grade;

switch (grade) {
case 'A':
cout << "Excellent!" << endl;
break;
case 'B':
cout << "Well done" << endl;
break;
case 'C':
cout << "You passed" << endl;
break;
#include <iostream>
using namespace std;

int main()
{ int n;
cout << "Enter any integer: ";
cin >> n;

if (n > 0)
cout << "Number is Positive" << endl;
else if (n < 0)
cout << "Number is Negative" << endl;
else if (n == 0)
cout << "Number is Zero" << endl;
else
cout << "Invalid input" << endl;

return 0;
}

Output:
Enter any integer: 7
Number is Positive
4.1.5 THE switch-statement
• This is basically a “multi-way” decision-statement.
• This is used when we must choose among many alternatives.
• The syntax & flow diagram is shown below:

• Here, choice can be either any integer value or a character.


• Based on this integer value, the control is transferred to a particular case-value where necessary
statements are executed.
• During executing, if break statement is encountered, then the control comes out of
the switch-block.
• If the value of the choice does not match with any of the case values (i.e. value1, value2, value3)
then control goes to default label.
• All case-values must be different.
• Program to illustrate the use of switch-statement.
#include <iostream>
using namespace std;

int main() {
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
cout << "Welcome to C++ language" << endl;
return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
4.2 BASIC CONCEPT OF LOOP
• Let's consider a situation when you want to write a message “Welcome to C++ language” five times.
Here is a simple C++ program to do the same:

case 'D':
cout << "Better try again" << endl;
break;
default:
cout << "Invalid grade" << endl;
return 0;
}
cout << "Your grade is " << grade << endl;
return 0;
}
Output:
enter grade A to D:
B
Well done
Your grade is B

• When the program is executed, it produces the above result.


• It was simple, but again let's consider another situation when you want to write the same message
thousand times, what you will do in such situation?
• Are we going to write cout statement thousand times? No, not at all.
• C++ language provides a concept called loop, which helps in executing one or more statements up to
desired number of times.
• Loops are used to execute one or more statements repeatedly.
• The flow diagram is shown below:

• There are 3 types of loops in C++ programming:


1) while loop
2) for loop
3) do while loop
4.2.1 THE while LOOP
• A while loop-statement can be used to execute a set of statements repeatedly as long as a given
condition is true.
• Syntax:
while(expression)
{
statement1;
statement2;
}
• Firstly, the expression is evaluated to true or false.
• If the expression is evaluated to false, the control comes out of the loop without executing the body
of the loop.
• If the expression is evaluated to true, the body of the loop (i.e. statement1) is
executed.
• After executing the body of the loop, control goes back to the beginning of the while statement and
expression is again evaluated to true or false. This cycle continues until expression becomes false.
• The flow diagram is shown below:

#include <iostream>
using namespace std;

int main() {
int i = 1;
while (i <= 5) {
cout << "Welcome to C++ language" << endl;
i = i + 1;
}
return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
• Program to display a message 5 times using while statement.
4.2.2 THE for LOOP
• A for loop-statement can be used to execute s set of statements repeatedly as long as a given condition
is true.
• Syntax:
for(expr1;expr2;expr3)
{
statement1;
}
• Here, expr1 contains initialization statement
expr2 contains limit test expression expr3 contains
updating expression
• Firstly, expr1 is evaluated. It is executed only once.
• Then, expr2 is evaluated to true or false.
If expr2 is evaluated to false, the control comes out of the loop without executing the
body of the loop.
If expr2 is evaluated to true, the body of the loop (i.e. statement1) is executed.
• After executing the body of the loop, expr3 is evaluated.
• Then expr2 is again evaluated to true or false. This cycle continues until expression
becomes false.
• The flow diagram is shown below:
Program to display a message 5 times using for statement.

#include <iostream> using


namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
cout << "Welcome to C++ language" << endl;
}
return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
4.2.3 THE do while STATEMENT
• When we do not know exactly how many times a set of statements have to be repeated, do-while
statement can be used.
• Syntax:
do
{
statement1;
}while(expression);
• Firstly, the body of the loop is executed. i.e. the body of the loop is executed at
least once.
• Then, the expression is evaluated to true or false.
• If the expression is evaluated to true, the body of the loop (i.e. statement1) is executed
• After executing the body of the loop, the expression is again evaluated to true or false. This cycle
continues until expression becomes false.
• The flow diagram is shown below:

#include <iostream>
using namespace std;

int main() {
int i = 1;
do {
cout << "Welcome to C++ language" << endl;
i = i + 1;
} while (i <= 5);

return 0;
}
Output:
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
Welcome to C++ language
• Program to display a message 5 times using do while statement
WHILE LOOP VS. DO-WHILE LOOP
4.2.4 NESTED LOOPS
• Nested loops refer to placing one loop inside another loop.
• Syntax:
for (initialization; condition; update) {
// Outer loop code
for (initialization; condition; update) {
// Inner loop code
}
}

while (outer_condition) {
// Outer loop code
while (inner_condition) {
// Inner loop code
}
}

do {
// Outer loop code
do {
// Inner loop code
} while (inner_condition);
} while (outer_condition);

• Program to print a 3x3 matrix using nested for loops

#include <iostream>

int main() {
for (int i = 1; i <= 3; ++i) { for
(int j = 1; j <= 3; ++j) {
cout << "(" << i << "," << j << ") ";
}
cout << endl;
}
return 0;
}

Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
4.3 break AND continue STATEMENTS
4.3.1 THE break STATEMENT
• The break statement is jump-statement which can be used in switch-statement and loops.
• The break statement works as shown below:
1) If break is executed in a switch-block, the control comes out of the switch-block and the statement
following the switch-block will be executed.
2) If break is executed in a loop, the control comes out of the loop and the statement following the loop
will be executed.
• Syntax:

• Program to illustrate usage of break statement.

#include <iostream>

int main() {
for (int i = 1; i <= 10; ++i)
{ if (i == 5) {
cout << "Breaking the loop at i = 5" << endl;
break;
}
cout << i << " ";
}
return 0;
}

Output:
1 2 3 4 Breaking the loop at i = 5
PROBLEM SOLVING AND PROGRAMMING USING
C++
4.3.2 THE continue STATEMENT
• During execution of a loop, it may be necessary to skip a part of the loop based on some condition. In
such cases, we use continue statement.
• The continue statement is used only in the loop to terminate the current iteration.
• Syntax:

• Program to read and add only positive numbers using continue statement. #include
<iostream>
using namespace std; int
main() {
int i = 1, num, sum = 0; for (i =
0; i < 5; i++) {
cout << "Enter an integer: "; cin >>
num;
if (num < 0) {
cout << "You have entered a negative number" << endl; continue; //
skip the remaining part of loop
}
sum = sum + num;
}
cout << "The sum of the positive integers entered = " << sum << endl; return 0;
}
Output:
Enter an integer: 10 Enter
an integer:-15
You have entered a negative number Enter an
integer: 15
Enter an integer: -100
You have entered a negative number Enter an
integer: 30
The sum of the positive integers entered = 55

Sudheendra Mouli H C, Asst Professor Dept, Of Computer Application, GSSS-SSGFC

You might also like