0% found this document useful (0 votes)
20 views20 pages

PPS-UNIT- II

The document provides an overview of decision control structures and functions in C programming, detailing the classification of statements into simple and compound types. It explains various control structures such as selection statements (if, if-else, switch-case) and looping constructs (while, do-while, for), along with their syntax and examples. Additionally, it addresses concepts like the conditional operator and nested loops, emphasizing their usage in decision-making and iteration within C programs.
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)
20 views20 pages

PPS-UNIT- II

The document provides an overview of decision control structures and functions in C programming, detailing the classification of statements into simple and compound types. It explains various control structures such as selection statements (if, if-else, switch-case) and looping constructs (while, do-while, for), along with their syntax and examples. Additionally, it addresses concepts like the conditional operator and nested loops, emphasizing their usage in decision-making and iteration within C programs.
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/ 20

PPS Course material – BE1/4 CSE-3

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.

C statements can be classified as:

 Simple statements: Is a single statement.


 Compound statements

Simple statements: The simplest kind of statements in C is an expression (followed by a


semicolon, the terminator for all simple statements). Its value is computed and discarded.
Examples:
X=2;
X=x+2;
printf (“\nWelcome to CBIT…”);
root=-b*sqrt(b*b-4*a*c);

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.

Compound statements: A compound statement is a group of statements separated from each


other by a semicolon. This group of statements, also called a block of code, is enclosed between
a pair of curly braces i.e., ‘{‘, ‘}’. One compound statement can be embedded in another
compound statement. The compound statements come in two varieties.

 Selective / Decision control /Conditional statements


 Looping/iterative/repetition statements

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)

Department of Computer Science and Engineering, CBIT, 2018-19 Page 1


PPS Course material – BE1/4 CSE-3

2. Iteration/looping/repetitive (for, while, do…while)

Figure 1: Types of C Control Structures

 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)

if construct: It is a simple selection statement, used when a statement(s) needs to be


executed conditionally. It consists of a Boolean expression followed by one or more statements.

Syntax: if (Boolean expression)


{
Statement sequence
}
Where if : is a reserved word
expression : is a Boolean expression written within a set of parenthesis
Statement sequence: either a simplest statement or a block.

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)

Department of Computer Science and Engineering, CBIT, 2018-19 Page 2


PPS Course material – BE1/4 CSE-3

printf(“\n %d is Bigger….”, A);


if( B>A)
printf(“\n %d is Bigger….”, B);
return 0;
}

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”);
}

The equivalent flowchart for an if construct is shown in Figure 2.1.

Figure 2.1: Flow chart for if statement.

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
}

Where if and else : are reserved words


expression : is a Boolean expression written within a set of parenthesis
Statement sequence1, 2: are either simplest statement or a block.

Department of Computer Science and Engineering, CBIT, 2018-19 Page 3


PPS Course material – BE1/4 CSE-3

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.

Figure 2.2: Flow chart for if…else statement.

Example: Program to print the largest of two numbers:

//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)

printf(“\n %d is Bigger….”, A);


else
printf(“\n %d is Bigger….”, B);
return 0;
}

Example 2: …………
if (grade>=0)
{
printf(“Passed……\n”);
printf(“Congratulations…..\n”);
}
else
{
printf(“Sorry, you failed……\n”);
printf(“Try again……\n”):
}

Department of Computer Science and Engineering, CBIT, 2018-19 Page 4


PPS Course material – BE1/4 CSE-3

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.

Solutions to dangling else problem: use null else or brackets.

Department of Computer Science and Engineering, CBIT, 2018-19 Page 5


PPS Course material – BE1/4 CSE-3

Figure 2.4: Solutions to dangling else problem

Conditional operator: It is an alternative to if…else construct. The syntax of conditional


operator is
expr1 ? expr2 : expr3
//program to print the largest among the given two integers using conditional operator
#include <stdio.h>
int main()
{
int a,b;
printf(“\n ENTER THE TWO NUMBERS:”);
scanf(“%d %d”, &a, &b);
printf(“\nLargest among %d and %d is: %d”, a, b, a>b?a:b);
return 0;
}
//largest among three numbers using conditional operator
int main()
{
int a,b,c,max;
printf("\nEnter any three integers: ");
scanf("%d %d %d",&a,&b,&c);
max=a>b ? a : b;
max=max>c ? max : c;
printf("Largest among %d %d and %d is : %d",a,b,c,max);
return 0;
}

Switch…case: It is an alternative for multiple if…else construct. If the selection of one of


several different courses of action is required in a program, then the switch-case statement
of C can be used. The syntax of switch… case is given in Figure 2.5.

 switch, case, break and default are reserved words


 The expression must be evaluated to an integer or a constant value
 The values of various case constants must be unique
 Expression is first checked with the first case constant. If does not match checks with
the next and so on.

Department of Computer Science and Engineering, CBIT, 2018-19 Page 6


PPS Course material – BE1/4 CSE-3

 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.

Figure 2.5: Syntax and flow chart for switch…case construct

Switch Vs nested if:


1. Switch can only test for equality where s if conditional expression can be of a
test expression involving any type of relational expression and or logical
operator.
2. A switch statement is usually more efficient than nested ifs
3. The switch statement can always be replaced with a series of else-if statements

Department of Computer Science and Engineering, CBIT, 2018-19 Page 7


PPS Course material – BE1/4 CSE-3

Repetition/iterative /Looping constructs: Allows a set of statements to be executed a


number of times, each time change the values of one or more variables so that every new
execution is different from the previous one. The looping statements are classified into two
categories: non-deterministic (the number of times the loop is to be executed in not known in
advance) and deterministic (no. of iterations is known) loops. C supports the looping
statements of while, do-while and for. While and do-while are non-deterministic
(unbounded); for is deterministic (bounded) statements.

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.

The sequence of operation in a while loop is as follows:


1. Test the condition
2. If the condition is true then execute the statement and repeat step 1.
3. If the condition is false, leave the loop and proceed with the rest of the program.
An alternative flowchart for a while loop is given in Figure 2.6:

Figure 2.6: Control flow in a while loop

//Program to find the factorial of a given number using while structure


#include<stdio.h>
int main()
{
int i, n; //declaration of variables

Department of Computer Science and Engineering, CBIT, 2018-19 Page 8


PPS Course material – BE1/4 CSE-3

long fact; //long integer to hold largest value


printf("\nEnter a positive number: ");
scanf("%d",&n); // Read the input for ‘n’
i=2; fact=1;
while(i<=n)
{
fact=fact*i; //repeatedly multiplies the number by varying i
i=i+1;
}
printf("\nFactorial of %d = %ld", n, fact); //print the result
return 0;
}

do-while loop: This is another conditional repetitive control structure provided by C. The
syntax of do-while is:
do
{
Statement;
} while <condition>

Where while: a reserved word


Statement : can be a simple or compound statement
<condition>: is a Boolean expression
The sequence of operations in a do-while loop is as follows:
1. Execute the statement
2. Test the condition
3. If the condition is true then repeat step 1 to 2
4. If the condition is false, leave the loop and go on with the rest of the program

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

Department of Computer Science and Engineering, CBIT, 2018-19 Page 9


PPS Course material – BE1/4 CSE-3

Figure 2.7: Control flow in a do-while loop

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:

for (initialization; expression; increment)


{
Statement;
}
Where
for: is a reserved word
Initialization: is usually an assignment expression wherein a loop control
variable is initialized
Expression: is a conditional expression required to determine whether the loop should
continue or be terminated
Increment: it modifies the value of the loop control variable by a certain amount.
The loop is executed with the loop control variable at initial value, final value and the value in
between. An equivalent flowchart of the ‘for’ loop is given in Figure 2.8:

Figure 2.8: Control flow in a for loop

Department of Computer Science and Engineering, CBIT, 2018-19 Page 10


PPS Course material – BE1/4 CSE-3

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;
}
}

Rules for the formation of nested loops:


1. An outer for loop and an inner for loop cannot have the same control variable
2. The inner loop must be completely nested inside the body of the outer loop
Example: Program to print the following output
1
12
123
1234
12345
int main()
{
int I,j;
for(i=1;i<=5;++i)
{
for(j=1;j<=I;++j)
printf(“%d”, j);
printf(“\n”);
}
return 0;
}

Department of Computer Science and Engineering, CBIT, 2018-19 Page 11


PPS Course material – BE1/4 CSE-3

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.

Function prototype declaration


 All the header files contain declarations for a range of functions, as well as definitions for
various constants.
 User defined functions should be normally be declared prior to its use to allow the compiler to
perform type checking on the arguments used in its call statement of calling construct.
 The general form of a function declaration statement is as follows:
return_type function_name( data_type_list);

 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.

Examples of function prototypes/declarations:

Department of Computer Science and Engineering, CBIT, 2018-19 Page 12


PPS Course material – BE1/4 CSE-3

int add(int a, int b);


float sqrt(float x);
void readinput( void);
void dosomething(int x);

 All functions must be declared before they are used.


 When a function takes no parameters, the inclusion of the word ‘void’ inside the parenthesis is
optional, since it is the default and when a function returns no value, it is required to include
‘void’ as the function type since the default is “int”.
 Name of the function is global
 No function can be defined in another function body
 Function return type cannot be an array or a function type.

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:

return_data_type function_name(data_type var1, data_type var2,…………)


{
/* function body */
}

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.

Rules for Parameters:


 The number of parameters in the actual and formal parameter list should be consistent
 Parameter association in C is positional.
 Actual parameters and formal parameters must be of compatible data types.
 Actual (input) parameters may be a variable, constant, or any expression matching the type of
the corresponding formal parameter.

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();

Department of Computer Science and Engineering, CBIT, 2018-19 Page 13


PPS Course material – BE1/4 CSE-3

Example: A function to find the factorial of a given number.

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.

Department of Computer Science and Engineering, CBIT, 2018-19 Page 14


PPS Course material – BE1/4 CSE-3

 If any modification done to the formal parameters will not be effected in corresponding actual
arguments in the calling function.

//Program to demonstrate call-by-value 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:

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;

Department of Computer Science and Engineering, CBIT, 2018-19 Page 15


PPS Course material – BE1/4 CSE-3

}
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.

What is needed 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
 It acts as a terminating condition. Without an explicitly defined base case, a recursive function
would call itself indefinitely.
 It is the building block to the complete solution. In a sense, a recursive function determines its
solution from the base case(s) it reaches.

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:

Department of Computer Science and Engineering, CBIT, 2018-19 Page 16


PPS Course material – BE1/4 CSE-3

Example 2:

Department of Computer Science and Engineering, CBIT, 2018-19 Page 17


PPS Course material – BE1/4 CSE-3

Example 3:

Output:

Example 4:

Department of Computer Science and Engineering, CBIT, 2018-19 Page 18


PPS Course material – BE1/4 CSE-3

Comparing Recursion and Iteration:


 Recursion is a powerful tool for solving complex problem particularly when the underlying
problem are data be treated are already defined in recursive terms.
 Recursion can lead to solutions that are much clearer and easier to modify than their
iterative counterparts.
 Recursion require substantial amount of runtime overhead ( repeated function calls)
 It makes inefficient utilization of memory as every time a new recursive call is made, a
function call incurs a booking overhead in the form of a runtime stack.
 Recursion is useful when the return values of the recursive function are used in further
processing within the calling version of the function.
 Iterative versions are always faster and take less memory compared to recursive function.

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.

Department of Computer Science and Engineering, CBIT, 2018-19 Page 19


PPS Course material – BE1/4 CSE-3

Example to illustrate scope rules in blocks


int main()
{
int x=3; // variable declaration in outer block
printf(“\nvalue of x in outer block: %d”,x);
{
int x=45; //variable re-declared in inner block
printf(“\nValue of x in inner block: %d”,x);
}
rrintf(“\nValue of in outer block after execution inner block: %”,x);
return 0;
}
Output:
value of x in outer block: 3
Value of x in inner block: 45
value of x in outer block after execution of inner block: 3

STORAGE CLASSES: These are used to indicate following:


 Where the variables would be stored,
 How long they would be exist,
 What would be their region of existence, and
 What would be the default values
C provides four storage class specifiers namely:
 auto
 register
 static
 extern
Storage
Place of Default
Class Scope Life Time
Memory value
Specifier
Auto Primary Within a block or Exists from the time of entry in the Garbage
memory function where it is function or block to its return to the
declared calling function
Register Registers Within the block or Exists from the time of entry in the Garbage
of CPU function where it is function of to the end of block
declared
Static Primary For local within the For local, retains the value of the 0
memory block or function variable from one entry of the block
where it is declared. or function to the next or next call
For global accessible For global, preserves value in the
within the program file program file
where it is declared
Extern Primary Exists as long as the program is in 0
memory execution
References:
1. Pradip Dey, Manas Ghosh “Programming in C”, Second edition, Oxford, Chapter 1.
2. http://nptel.ac.in/courses/106104128
3. http://tutorialpoint.com/cprogramming

Department of Computer Science and Engineering, CBIT, 2018-19 Page 20

You might also like