PPS-UNIT- II
PPS-UNIT- II
UNIT-II
Introduction to Decision Control Structures and Functions
Statement: Is the smallest executable unit of a C program. Every statement is terminated with a
semicolon. It is an instruction given to the computer to perform a particular task like reading
input, displaying output or evaluating an expression etc.
Most statements in a typical C program are simple statements of this form. Other examples of
simple statements are the jump statements return, break, continue, and goto.
A return statement specifies the return value for a function ( if there exists one) and
when executed it causes the function to exit immediately
A break and continue statements jump immediately to the end of a loop (or switch) or
the next iteration of loop.
A goto statement jumps to another location in the same function; and exists for the rare
occasions when it is needed.
Decision Control statements: These constructs enable us to specify the flow of program
control; i.e., the order in which the instructions in a program must be executed. They make it
possible to make decisions, to perform tasks repeatedly or jump from one section of code to
another. The control statements in C are classified into the following categories:
1. Selection statements (if, if…else, if…else…if, switch.. case)
All the conditional constructs uses Boolean expression which are formed by using
relational (<, >, <=, >=), equality (==, !=) and logical operators (&&, ||, !).
Logical operators are used to combine two or more relational expressions
Selective statements: Used for selective execution of a program segment. The ‘C ‘ selective
statements are:
Simple if statements
if-else statements
Nested if statements (if-else-if ladder)
switch-case statement (Selection of One of Many Alternatives)
Example 1: Write a program that reads two numbers A, B and prints the bigger of the two.
Solution: Use if statement to perform the test: A>B.
//Program to that reads two integers and determines the largest
int main()
{
int A, B;
printf(“\nEnter two integer values for A & B: “);
scanf(“%d %d”, &A, &B);
if( A>B)
Example 2: Write a program that reads the grade of a student and prints the messages
“Congratulations, You passed the exam”
…………
if (grade>=0)
{
printf(“Congratulations…..\n”);
printf(“Passed……\n”);
}
If…else construct: Used when there are two alternatives. An if…else statement can be
followed an optional else statement, which executes when the Boolean expression is false.
if (Boolean expression)
{
Statement sequence 1
}
else
{
Statement sequence 2
}
The equivalent flowchart for the if-else construct is shown in Figure 2.2. If the Boolean
expression evaluates to true, then the if code will be executed, otherwise, the else code will be
executed.
Example 2: …………
if (grade>=0)
{
printf(“Passed……\n”);
printf(“Congratulations…..\n”);
}
else
{
printf(“Sorry, you failed……\n”);
printf(“Try again……\n”):
}
Nested if…else if: When there are several alternatives, then nested if…else may be used.
Example: //program to print whether a given number is positive, negative or equal to zero
#include <stdio.h>
int main()
{
int x;
printf(“\n ENTER THE NUMBER: ”);
scanf(“%d”, &x);
if(x > 0)
printf(“x is positive \n”);
else if(x == 0)
printf(“x is zero \n”);
else
printf(“x is negative \n”);
return 0;
}
Figure 2.3: Program to find the largest among three given numbers using if…else statement.
NOTE: Multiple if…else statements cause confusion and leads to dangling else problem. An
alternative construct for multiple if…else construct is switch…case.
If it matches, then the statements followed the constant will be executed. The break
statement at end of each case statement will transfer the control to the statement next
to the switch…case block. If a break statement is not encountered then the control
continues across other statements (error prone if not used carefully as it runs the
remaining cases). Omitting a break statement results in error prone by executing the
remaining cases. This phenomenon is called fall-through.
If none of the case constants matches, then the statements in the default section will
be executed. Default case is optional and it doesn’t require break.
There can be only one default statement in a statement. It can be placed anywhere in
the switch statement.
while construct: It is the fundamental conditional repetitive structure in C and used to repeat
or iterate a statement or sequence of statements until some condition becomes true. It is a pre-
test loop where the condition is tested before executing the loop body. The general form of this
construct is given below:
while <condition>
{
statement;
}
where
while: Reserved word of C
<condition> :is a Boolean expression
Statement: can be a simpler or compound statement.
do-while loop: This is another conditional repetitive control structure provided by C. The
syntax of do-while is:
do
{
Statement;
} while <condition>
It performs a post-test in the sense that the condition is not tested until the body of the loop is
executed at least once. An equivalent flowchart for a do-while loop is given in Figure 2.7: It
repeats the loop as long as the condition remains true. As soon as the condition becomes false,
the control leaves the loop and goes to the next immediate statement after the while
reserved word.
The code snippet to find the factorial of a given number using do-while construct is:
i=2; fact=1;
do
{
fact=fact*i; //repeatedly multiplies the number by varying i
i=i+1;
} while(i<=n)
printf("\nFactorial of %d = %ld", n, fact); //print the result
for loop: It is a count controlled loop in the sense that the program knows in advance how
many times the loop is to be executed. The general form of this construct is given below:
The code snippet to find the factorial of a given number using for construct is:
fact=1;
for(i=2; i<=n; ++i)
{
fact=fact*i; //repeatedly multiplies the number by varying i
i=i+1;
}
printf("\nFactorial of %d = %ld", n, fact); //print the result
if .. goto construct: This is another looping construct. The general form of this construct is:
Label: N
Statement 1
Statement 2
……
…….
Statement N
if <condition> then goto N
Nested looping: A nested loop is one inside the body of another loop. The inner and outer loops need
not be the same construct. Example:
while <condition>
{
do
{
Statements;
}
for( ..;..;)
{
Statements;
}
}
Function: A function is a self –contained block of program statements that performs a particular task.
They can be called
from several times from different portions of a program. They may be classified as library functions and
programmer-defined (user defined) functions. scanf(), printf(), sqrt() etc. are examples of library
functions. When a function is called upon, with or without input data, it returns information to the main
program of calling function from where it was called.
Advantages of functions
1. Functions make programs significantly easier to understand and maintain by breaking up a
program into manageable chunks.
2. Main program can consist of a series of function calls rather than countless lines of code. It can
be executed as many times as necessary from different points in the main program.
3. Well written functions may be reused in multiple programs. C standard library is an example of
reuse of functions. This enables code sharing.
4. Functions can be used to protect data. This is related to with the concept of local data, which is
available only within the function being executed.
5. Different programmers working on one project can divide the workload by writing different
functions.
6. Debugging error correction is easy.
Usage of functions
Functions are used by calling them from other functions.
When a function is used, it is referred to as the ‘called function’ and the calling function is called
caller.
The called functions use data that is passed to them from the calling function.
Information from the calling function to called function is passed as parameters.
Functions manipulate the received data to produce a useful result.
In the function declaration there are three basic parts namely function_name, return_type and
datatype_list.
function_name: Gives the name is an identifier used to identify the function code.
return_type: Specifies the type of data given back to the calling construct by the function after
its specific task.
data_type_list: this list specifies the data type of each of the variables, the values of which are
expected to be transmitted by the calling construct to the function.
Function definition: The collection of program statements in C that describes the specific task done
by the function is called a function definition. It consists of the function header and a function body,
which is a block of code enclosed in braces. The definition creates the actual function in memory. The
general form of the function definition is as follows:
The first line is called header and the code between the braces is called the function body. It is similar to
the function declaration but does not require the semicolon at the end.
Formal parameters: the list of variables in the function header is also referred to as the formal
parameters.
Actual arguments/parameters: The arguments in the calling function.
Function call or invocation: When a function is invoked by the calling function, the control is passed to
the function. Then it executes the statements in the function. After performing the task by using the
information passed from the calling function, the control will be returned back to the calling function.
Syntax:
variable_name=function_name(var1, var2, ….);
or
function_name();
variable_name=function_name();
Parameter passing mechanisms: In C, there are two ways in which parameters can be passed
to a function. They are:
1. Call by value and
2. Call by address or reference.
Call-by value:
In call-by value, a copy of the actual parameters is passed to the corresponding formal
parameters in the called function.
The function can make use of this copy to produce the result.
If any modification done to the formal parameters will not be effected in corresponding actual
arguments in the calling function.
OUTPUT:
Call-by-address:
o In this method, the addresses of the actual arguments are passed to the function. Using
these addresses function can directly access the actual arguments.
o When an array is passed to a function, the address of the array is passed and no the
copy of the complete array.
o During its execution the function has the ability to modify the contents of the array that
is specified as the function argument.
o The array is not passed by value to the function
//Program to demonstrate call-by-address parameter passing mechanism
#include<stdio.h>
void swap(int *a, int *b) //function definition
{
int temp=*a;
*a=*b;
*b=temp;
printf("\nValues of a and b in function 'swap' function: %d %d",*a,*b);
}
int main()
{
int a=10, b=20;
printf("\nValues of a and b before function call: %d %d",a,b);
swap(&a,&b); //function call
printf("\nValues of a and b after function call: %d %d",a,b);
return 0;
}
Output:
RECURSION
Recursion in programming is a technique for defining a problem in terms of one or more smaller
versions of the same problem.
A function that calls itself directly or indirectly to solve a smaller version of its task until a final
call which does not require a self-call is a recursive function.
The necessary for implementing recursion:
Decomposition into smaller problems of same type.
Recursive calls must diminish problem size.
Necessity of base case.
Base case must be reached.
Base condition: An instance of a problem the solution of which require no further recursive calls is
known as a base case. It is a special case whose solution is known. Every recursive algorithm must
require at least one base case in order to be valid.
General form of a recursive algorithm is:
if(this is a base case ) then
solve directly
else
redefine the problem using recursion
Example1:
Example 2:
Example 3:
Output:
Example 4:
Scope and extent: The region of the program over which the declaration of an identifier is visible is
called the scope of the identifier. It relates the accessibility, the period of existence and the boundary of
usage of variables declared in a statement block or a function. These features define whether a variable
is local or global.
Lifetime: Is the period during execution of a program in which a variable of function exists.
Local variables: Variables declared within a block or the function body are called local variables. They
have local scope and are created at the point of their declaration within the function body and are
usable inside the function. These variables exist inside the specific function that creates them and are
not known to other functions and to the main program. The existence of the local variables ends when
the function completes its specific task and returns to the calling point. They are recreated each time a
function is executed or called.
Global variables: Variables declared outside of all the functions of a program and accessible by any of
these functions are called global variables.
Scope Rules
The region of the program over which the declaration of an identifier is accessible is called the
scope of the identifier.
The scope relates to the accessibility, the period of existence, and the boundary of usage of
variables declared in a program.
Scopes can be of four types.
Block
File
Function
Function prototype
Block scope: The identifier can only be used in the block in which it is declared. Outside of the block
these variables are unknown and non-existent.