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

CPP Unit-2 Notes

Uploaded by

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

CPP Unit-2 Notes

Uploaded by

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

UNIT - 02

CONTROL STATEMENTS

Control statements are statements that alter the sequence of flow of instructions.
Any single input statement, assignment and output statement is simple statement.
A group of statements that are separated by semicolon and enclosed within curled braces {and} is called a
block or compound statement.

Types of control statements


C++ supports two basic control statements.
 Selection statements
 Iteration statements

Selection statements:
 This statement allows us to select a statement or set of statements for execution based on some
condition.
 The different selection statements are:
a. if Statement
b. if-else Statement
c. Nested if Statement
d. if-else-if Ladder
e. switch Statement
f. Conditional Operator
g. Jump Statements:
i. break
ii. continue
iii. goto
iv. return

a) if in C

The if statement is the simplest decision-making statement.


It is used to decide whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.

Syntax:

if(condition)
{
// Statements to execute if
// condition is true
}
Example
if (i > 15)
{
printf("10 is greater than 15");
}
Flowchart of if Statement

b) if-else in C
This statement is also called as two-way branching.
It is used when there are alternative statements need to be executed based on the condition.
It executes some set of statements when the given condition is TRUE and if the condition is FALSE then
other set of statements to be executed.

Syntax:
if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}

EXAMPLE:

if (time < 18)


{
cout << "Good day.";
}
else
{
cout << "Good evening.";
}

Flowchart:

c) Nested if Statement
When a number of if blocks are present one after another with the same scope (the same scope
means under one { } block), then that condition is termed as a Nested if condition.

If the first condition is True, we go into the next if condition and the subsequent condition is
checked until we get a false condition, and the checking stops.

Syntax:

Example

Flowchart:
d) if-else-if Ladder

This structure is also called as else-if ladder. This structure will be used to verify a range of values.

This statement allows a choice to be made between different possible alternatives. A choice must be made
between more than two possibilities.

Syntax:

Example
Flowchart

e) switch Statement

The switch statement in C++ is a flow control statement that is used to execute the different blocks of
statements based on the value of the given expression.
We can create different cases for different values of the switch expression.
We can specify any number of cases in the switch statement but the case value can only be
of type int or char.
Syntax

Example:
Flowchart

C++ Ternary or Conditional Operator


In C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional statements. It
can be used as an inline conditional statement in place of if-else to execute some conditional code.
Syntax of Ternary Operator ( ? )
expression ? statement_1 :
statement_2;

As the name suggests, the ternary operator works on three operands where
 expression: Condition to be evaluated.
 statement_1: Statement that will be executed if the expression evaluates to true.
 statement_2: Code to be executed if the expression evaluates to false.

Example
int A = 39, B = 10, C = 23;
// Evaluate largest of three using ternary operator
int maxNum = (A > B) ? ((A > C) ? A : C) : ((B > C) ? B : C);
Jumping statements
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to
terminate or continue the loop inside a program or to stop the execution of a function.
Types of Jump Statements in C++
In C++, there is four jump statements
1. break
2. continue
3. goto
4. return

1. break
 The break statement has two uses. You can use it to terminate a case in the switch statement.
 And you can also use it to force immediate termination of a loop like, while, do-while and for,
by passing the normal loop conditional test.
 When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement.

Syntax:
break;

Example

Flowchart
2. Continue

 The C++ continue statement is used to execute other parts of the loop while skipping some parts
declared inside the condition, rather than terminating the loop, it continues to execute the next
iteration of the same loop.
 It is used with a decision-making statement which must be present inside the loop.
 This statement can be used inside for loop or while or do-while loop.

Syntax
Continue;

Example

Flowchart
3. Goto
 The C++ goto statement is used to jump directly to that part of the program to which it is being
called.
 Every goto statement is associated with the label which takes them to part of the program for which
they are called.
 The label statements can be written anywhere in the program it is not necessary to use them before
or after the goto statement.
Syntax
goto label_name;
.
.
.
label_name:

Example

Flowchart

4. Return
 The return statement takes control out of the function itself.
 It is stronger than a break. It is used to terminate the entire function after the execution of the
function or after some condition.
 Every function has a return statement with some returning value except the void() function.
Although void() function can also have the return statement to end the execution of the
function.

Syntax

return expression;

Example

Flowchart

Loop control statements


Loops
 Loops can execute a block of code as long as a specified condition is reached.
 Loops are handy because they save time, reduce errors, and they make code more readable.
 In Programming, sometimes there is a need to perform some operation more than once or (say) n
number of times. Loops come into use when we need to repeatedly execute a block of statements.
 This condition may be predefined or post-defined.

There are mainly two types of loops:

1. Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop
body. For Loop and While Loop is entry-controlled loops.

2. Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the
loop body. Therefore, the loop body will execute at least once, irrespective of whether the test
condition is true or false. the do-while loop is exit controlled loop.

1. For Loop
 This statement is called as the fixed execution looping statement.
 It is normally used when we know in advance exactly how many times a set of statements should be
repeatedly executed again and again.
 It provides initialization, loop-end-condition and increment/decrement process statements in a
single line.
 When one is aware of fixed number of iterations, then this looping structure is best suited.
Syntax

for (statement 1; statement 2; statement 3)


{
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

Example
for (int i = 0; i < 5; i++)
{
cout << i << "\n";
}

Flowchart
2. While loop
 This looping structure is also called as pre-tested looping structure.
 The while loop loops through a block of code as long as a specified condition is true.

Syntax
while (condition)
{
// code block to be executed
}

Example
int i = 0;
while (i < 5)
{
cout << i << "\n";
i++;
}

Flow Diagram of while loop


3. Do-while loop
 This looping structure is also called as post-tested looping structure.
 Unlike while loop that test the loop condition at the beginning, the do-while loop checks the
condition after the execution of the statement.
 This means that a do-while loop always executes at least once. Its functionality is exactly
the same as the while loop, except that the condition in the do while loop is evaluated after
the execution of statement, instead of before.
Syntax
do
{
// code block to be executed
}
while (condition);

Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Flowchart of do-while loop
Modular Programming
 Modular programming is the process of subdividing a computer program into separate sub-
programs.
 A module is a separate software component. It can often be used in a variety of applications and
functions with other components of the system.
 If the programs are complex and lengthy, they can be modularized into subprograms. The
subprograms are called as functions.
 The subprograms can be developed independently, compiled and tested. They can be reused in other
programs also.

Functions
 A function is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a function.
 Functions are used to perform certain actions, and they are important for reusing code: Define the
code once, and use it many times.

Types of functions
There are two types of functions:
a) Library functions
b) User-defined functions

a) Library functions: A standard library is a collection of pre-defined functions and other


programming elements which are accessed through header files.
b) User-defined functions: User-defined function is a function defined by the user to solve his/her
problem. Such a function can be called (or invoked) from anywhere and any number of times in the
program.

User-defined functions:
Function definition or structure of user-defined function
Return-type-specifier: It is the datatype of the value return by the function to anther function when it is
called. The return-type-specifier can be char, int, float or void. data type void is used when the function
return no value to the calling function.
Function-name: is the name of the function. It is an identifier to identify the particular function in a
program. The rules to form an identifier are already discussed in the introductory section.
Argument-list with declaration is the list of arguments or parameters or variables with their declaration.
Each argument should be declared separately. Each declaration should be separated by comma. The list
should be enclosed within parenthesis. The complete line is called the function header. Note that there is no
semicolon at the end.
Local-variable declaration is the declaration of the variables that are used within the function. Since these
variables are local to the function, these variables are called as local variables.
Executable-statements are the statements that perform the necessary operations to solve the
problem. If the function is returning a value, a return statement should be included. Otherwise,
return statement is not necessary.

Local declaration and executable statements are together called as body of the function. The body of the
function should be enclosed within the curled braces.

Important Definitions
 Calling function is a function that transfers control from it to another function by specifying the
name of that function and passing arguments.
 Called function is a function that receives the call and arguments from another calling function.
 Function call is the statement that is used to call or make another function execute.
 When a function call is made, the control jumps from calling function to the called function.

The Syntax of function call is:

variable = function-name(argument-list);

OR

variable=function-name();

main() function
 In C++, the main() function returns a value of type int to the operating system. If the program runs
successfully, 0 is returned.
 Otherwise, a non-zero value is returned to the operating system, indicating that the program
contains errors.
 If the main() function is not returning a value, the datatype void can be used as return-type-
specifier.
The Syntax of main() function is:

Types of arguments
A variable in a function header is called an argument. The arguments are used to pass information from the
calling function to the called function.
a) Actual arguments:
The function call statement contains name of the function and list of arguments to be passed.
These arguments or parameters are called as actual arguments.
The arguments can be constants, variables or expressions.
Example: In the function call g =gcd(a, b);
a and b are the actual arguments. Actual arguments have values stored in them before the function call
hence the name actual.
b) Formal arguments
The function header contains return-type-specifier, function name and list of arguments with their
declaration.
These arguments are called as formal arguments or dummy arguments.
Formal arguments get their values from the actual arguments.
Example: In the function header int gcd(int x, int y) x and y are the formal arguments.
 The actual arguments and formal arguments should same in number and order.
 The names of actual arguments and formal arguments can be same or different.
 Formal arguments should always be names of variables.
c) Local variables
The variables declared inside function or block is said belong to that block.
These variables are called as Local variables.
Values of local variables are accessible only in that block.
The function’s formal arguments are also considered as local variables.
d) Global variables
The variables declared outside the function are called as global variables.
These variables are referred by the same datatype and same name throughout the program in both the
calling function and called function.
Whenever if some variables are to be treated as same value in both main() and in other functions, it is
advisable to use global variables.

TYPES OF FUNCTIONS
There are different types of functions.
1. Functions with no arguments and no return values
2. Functions with arguments and with no return values
3. Functions with no arguments and with return values
4. Functions with arguments and with return values
5. Recursive functions

1. Functions with no arguments and with no return values


In this method, the function simply performs an independent task. The function does not receive or send
any arguments.
The Syntax is:

Example:
void natural( )
{
for(int i=1; i <= 10; i++)
cout<<setw(4)<<i;
}
2. Functions with arguments and with no return values
In this method, the function receives some arguments and does not return any value.
Syntax:

Example:

3. Functions with no arguments and with return values


In this method, the function receives no arguments but return a value.

Syntax:

Example:

4. Functions with arguments and with return values


In this method, the function receives some arguments and returns a value.
Syntax:
Example:

5. Recursive functions
Recursive function is a function that calls itself. The process of calling a function by itself is called as
recursion.
Syntax:

Recursive functions must have one or more terminating conditions to terminate recursion. Otherwise,
recursion will become infinite.
Example program of recursion

#include <iostream>
using namespace std;

int fib(int x)
{
if((x==1)||(x==0)) {
return(x);
}
else {
return(fib(x-1) + fib(x-2));
}
}

int main() {
int x , i = 0;
cout << “Enter the number of terms of series : “;
cin >> x;
cout << “\nFibonnaci Series : “;
while(i < x) {
cout << ” ” << fib(i);
i++;
}
return 0;
}

You might also like