Unit - II Decision Making
Unit - II Decision Making
AATTUKARAMPATTI, DHARMAPURI-9
It allows the computer to evaluate the text expression first and then, depending on whether
the value of the expression (relation or condition) is true or false the result is produced.
Based on this result it transfer the control to a particular statement.
-1–
The if statement may be implement in different forms depending on the
complexity of conditions to be tested. The different forms are
Simple if statement
if…..else statement
Nested if…..else statement
Elseif ladder
Entry
test False
expressio
n
?
True
True test
expressio
n
?
Statement-block
False
Statement-x
Next Statement
Example:-
The following program checks whether a given number is positive.
# include <stdio.h> More that one test condition can be included in a
void main() test expression by using && and || conditions.
{
int x;
printf(“\n Enter a number”);
Scanf(“%d”,&x);
if(x>0)
{
printf(“\n The number is
Positive”);
}
getch() -3–
}
Example:-
If (weight <50 && height>170)
Here the if statement will return true only if both the conditions are true i.e., if weight is less
than 50 and height is greater than 170
The If…Else Statement:-
The if….else statement is an extension of simple if statement. The general form is
Syntax:-
if test_expression)
{
True-block statements(s)
}
else
{
False-block statement(s)
}
statement-x;
If the test expression is true, then the true block statements are executed; otherwise the false block
statement will be executed.
Otherwise the false-block statements are executed.
The text expression executes either true-block or false-block, not both.
In both the cases, the control is transferred subsequently to the statement-x;
test
expressio
n
?
False-block statement False-block statement
Statement-x
-4–
Example:-
The following program checks whether a given number is positive or negative
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
printf("\n Enter the a number");
scanf("%d", &x);
if(x>0)
{
printf("\n The number is Positive");
}
else
{
printf("\n The number is Negative");
}
getch();
}
If (test_condition1)
{
if(test_condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x; -5–
Entry
test
False condition 1 True
?
Statement-x
-6–
Next Statement
If the condition 1 is false the statement3 will be executed; otherwise it continues to perform the 2 nd
test.
If the condition 2 is true the statement1 will be evaluated otherwise the statement2 will be
evaluated and then the control is transferred to x.
Example:-
The following program checks whether a given number is positive or negative or zero.
# include<stdio.h> else
#include<conio.h> {
main() if(C > B)
{ printf(“%f \n”,C);
float A, B, C; else
printf(“Enter three values \n”); printf(“%f \n”,B);
scanf(“|%f %f %f”,&A, &B, &C); }
printf(“\nLargest value is:”); }
if(A > B) OUTPUT
{ if(A > C) Enter three values:
printf(“%f \n”,A); 5 8 24
else Largest value is 24
printf(“%f \n”,C);
}
-7–
The Elseif Ladder:-
A multi-path decision is a chain of If statement in which the statement associated with each else
is and IF statement
if (condition 1)
statement 1;
else if (condition 2)
statement2;
else if (condition 3)
statement 3;
else if (condition n)
statement n ;
else
default statement;
statement-x;
Entry
False True
test
condition
1 ?
Statement-1 test
False condition 2 True
?
-8–
Statement-2
test
condition
3?
Statement-x
Default
Statement
Statement-X
Next Statement
Switch
Expression
Expression = value -1
Block -1
Statement-x
The ? : Operator:-
This operator is a combination of ? and :, and takes three operands.
This operator is popularly known as the conditional operator.
The general form of use of the conditional operator is as follows.
- 11 –
if (x <0)
flag = 0;
else
flag=1;
can be written as
flag = (x < 0 ) ? 0 : 1;
Unconditional statements:-
The GOTO statement:-
C supports the goto statement to branch unconditionally from one point of the program to
another.
The goto requires a label in order to identify the place where the branch is to be made.
A label is any valid variable name and must be followed by a colon.
The label is placed immediately before the statement when the control is to be transferred.
The general from is
Forward Jump Backward Jump
The label: can be anywhere in the program before or after the goto label; statement
When a goto statement is encountered the flow of control will jump to the statement immediately
following the label in the goto statement.
Backward Jump: If the label is before the statement goto label; a loop will be formed and some
statement will be executed repeatedly. Such a jump is known as a backward jump.
Forward jump: If the label is placed after the goto label, some statements will be skipped and
the jump is known as a forward jump.
Decision Making And Looping:-
Loop statements are used to perform repetitive processes without the use of goto statements.
A program loop consists of two segments.
Body of the loop
Control statement.
- 12 –
The control statement tests certain conditions and then directs the repeated execution of the
statements contained in the body of the loop.
Depending on the position of the control statements in the loop, a control structure may classify
in to two type.
Entry-Controlled loop
Exit-Controlled loop
Entry – Controlled loop:-
In this loop, the control conditions are tested before the start of the loop execution.
If the conditions are not satisfied, then the body of the loop will not be executed.
Otherwise it is called as pre-test loop.
test False
condition
True ?
Body of the loop
True
- 13 –
In this loop, the test is performed at end of the body of the loop and therefore the body is
executed unconditionally for the first time. Another name for Exit-controlled loop is post-test
loop.
A looping process includes the following four steps:-
o Setting and initialization of a condition variable.
o Execution of the statements in the loop.
o Test for a specified value of the condition variable for execution of the loop.
o Incrementing or updating the condition variables.
The C language provides for three loop constructs for performing loop operations. They are
The while statement
The do statement
The for statement
Entry
The While Statement:-
The basic format of the while statement is False
Test
condition
While (test-condition) ?
{
body of the loop
} True
Body of the loop
Next statement
The while is an entry–controlled loop statement.
The test-condition is evaluated and if the condition is true, then the body of the loop is executed.
After execution of the body, the test-condition is once again evaluated and if it is true, the body
is executed once again.
This process of repeated execution of the body continues until the test-condition finally becomes
false and the control is transferred out of the loop.
The body of the loop may have one or more statements.
The braces are need only if the body contains two or more statements.
- 14 –
Eg:
-----------
# include <stdio.h> OutPut:-
#include <conio.h> 1
----------- voidmain() 2
{
sum = 0;
int num = 1;
3
n = 1; clrscr (); 4
while9num <=10) 5
while(n <= 10)
{ 6
{ printf(“%d\n”, num); 7
num ++; 8
sum = sum + n* n;
}
n = n + 1; getch (); 9
} 10
}
printf(“sum = %d \n”,sum);
-----------
-----------
The Do Statement:-
The do-while is an exit controlled loop.
On reaching the do statement, the program proceeds to evaluate the body of the loop first.
The end of the loop, the test-condition in the while statement is evaluated.
In while loop the body of the loop may not be executed at all if the condition is not satisfied at
the very first attempt.
Such situations can be handled with the help of the do statement.
If the condition is true, the program continues to evaluate the body of the loop once again.
This process continues as long as the condition is true. Entry
do
Body of the loop
{
body of the loop
}
While (test-condition)
True Test
condition
Since the test-condition is evaluated at the bottom
?
of the loop, the do…..while construct
provides an exit-controlled loop and therefore the
body of the loop is always executed at least once. False
Next statement
- 15 –
Eg:
-----------
do
#include<stdio.h> OutPut:-
{ #include<conio.h> 1
printf(“Input a number\n”); void main() 2
number = getnum(); { 3
int num=1; 4
}
clrscr();
while(number > 0); do
5
----------- { 6
printf(“%d\n”, num); 7
num ++; 8
} while(num<=10); 9
getch(); 10
}
- 16 –
When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop.
Now, the control variable is either incremented or decremented as per the condition.
Eg 1) for(x = 0; x <= 9; x = x + 1)
{ #include<stdio.h> OutPut:-
printf)”%d”,x);
#include<conio.h> x square(x)
void main() 1 1
} { 2 4
printf(“\n”); int i,square; 3 9
clrscr(); 4 16
Eg 2) sum = 0;
printf("x\t square(x)\n\
for(i = 1; i < 20 && sum <100; ++i) n");
{ for(i=1;i<5;i++)
sum =sum + i; printf("%d\t%d\n",i,i*i);
getch();
printf(“%d %d \n”,sum);
}
}
- 17 –
for(i=1;i<20&&sum<100;i++)
{
sum =sum +1;
printf(“%d%d\n”,I,sum);
}
And also permissible to use expression in the assignment statements of initialization and
increment sections.
Another unique aspect of for loop is that one or more sections can be omitted, if necessary.
Example:-
m=5
for(;m!=100;)
{
printf(“%d\n”,m);
m=m+5;
}
Nesting of For Loops:-
C allows one for statement within another for statement.
Loops perform a set of operations repeatedly until the condition becomes false.
The number of times a loop is repeated is decided in advance.
C permits a jump from one statement to another with in a loop as well as a jump out of a loop.
JUMPS IN LOOPS
C permits a jump from one statement to another within a loop as well as the jump out of a loop.
- 18 –
Jumping out of a Loop:-
An early exit from a loop can be accomplished by using the break statement or the goto
statement.
When the break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.
When the loops are nested, the break would only exit from the loop containing it. That is, the
break will exit only a single loop.
Break statement:-
The break is used inside a looping statement or conditional statement.
When a break statement is encountered inside a loop, the loop is immediately exit and program
continues with the statement immediately following the loop.
When the loops are nested the break would only exit from the loop containing it.
GOTO Statement:-
Goto Statement is used to transfer the control to any place in a program.
Another important use of goto is to exit from deeply nested loops when an error occurs.
Skipping a part of a Loop:-
Continue statement:-
Like the break statement, C supports another similar statement called the continue statement.
However, unlike the break which causes the loop to be terminated, the continue, as the name
implies, causes the loop to be continued with the next iteration after skipping any statements in
between.
The continue statement tells the compiler, “SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.
The format of the continue statement is simply Syntax:-
Continue
In while and do loops, continue causes the control to go directly to the test-condition and then to
continue the iteration process.
In the case of for loop, the increment section of the loop is executed before the test-condition is
evaluated.
Jumping out of program:-
The exit ( ) function can bed used to jump out of the program.
- 19 –
The exit ( ) function takes an integer value as its argument. zero is used indicate normal
termination and nonzero value to indicate termination due to some error or abnormal condition.
The exit () function requires the inclusion of the header file <stdilb.h>
Example:-
if(text-condition) exit(0);
Array:-
Introduction:-
An Array is a collection of elements of similar data type.
This collection is finite and the elements are stores at adjacent memory locations.
Thus array has to be finite in nature.
The size of the should be predefined.
Thus we can say array of n number of elements. Remember usually array elements are stored
starting from oth location hence n number of elements can be counte3d from o to n-1.
The range of array is between a [0] to a [n-1]. (Here a is name of array].
Range means-total number of elements in the array.
All these elements are always stored at contiguous memory locations.
Any element of the array can be represented using index and name of the array.
That means a[0] represents the value stored at O th location of the array, a[3] represents the value
stored at 3 rd location of the array and so on.
Definition:-
An array is a group of related data items stored under a common name.
A collection of data elements arranged to be indexed in one or more dimension
- 20 –
The arrays are stored in contagious memory.
An array fixed-size is a sequenced collection of elements of the same data type that share a
common name.
An array can be used to represent a list of number or list of names. An array is a derived data
type.
An array is a group of logically related data items of the same data – type addressed by a
common name and all items are stored in contiguous memory.
An array is finite because it contains only a limited number of elements, and ordered, as all the
elements are stored one by one in contiguous locations of the computer memory in a linear
ordered fashion.
Eg:-
Int a[5];
a – represents the array name
5 – represents the size / subscript
Syntax:-
datatype array-name[size]:
Example:-
An array of integers to store the age of all students in a class.
An array of strings of characters to store the names of all villagers in a village.
Note:-
An array is known as a linear data structure because all elements of the array are stored in a
linear order.
The data structure is generally a built-in data type in all programming languages.
The declaration syntax for an array A of 100 integers in BASIC, FORTRAN, PASCAL
AND C are as given below.
Types Of Array:-
1. One dimensional array
Now that the elements in array are always stored in contiguous memory locations.
Now let us see how to handle this array.
Declaration of one-dimensional arrays:-
Arrays must be declared before they are used so that the compiler can allocate space for them in
memory.
Syntax:-
Type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float, or
char.
- 22 –
The size indicates the maximum number of elements that can be stored inside the array.
Example:
int value[5];
Declares the value to be an array of integer containing 5 integer elements. The computer reserves
five storage locations as shown below.
Value [0]
Value [1]
Value[2]
Value[3]
Value[4]
Eg:-
main()
{
int i,j;
/* enter the values */
cout<<”\enter the values”;
for(i=0;i<10;i++)
cin>>a[i];
/*display the values*/
for(i=0;i<10;i++)
cout<<a[i];
}
Example:-
char address[50];
declares the address as a character array variable that can hold a maximum of 50 characters.
Rules:-
Any reference to the arrays outside the declared limits would not necessarily cause an error.
Rather, it might result in unpredictable program results.
The sized should be either a numeric constant or a symbolic constant.
The c language treats character strings simply as arrays of characters.
The size in a character string represents the maximum number of characters that the string can
hold for instance.
Char name[10];
- 23 –
Declares the name as character array (string) variable that can hold a maximum of 10 characters.
INPUT: JSV College
Each character of the string is treated as an element of array name and is stored in the memory
as follows.
J The last element position is always occupied by a null
character ‘\0’, so the size should be chosen one more than the
S
actual string being stored.
V
C
O
L
L
E
G
E
- 24 –
Example:
float total [5]={0.0,15.75,-10}; will initialize the first three elements to 0.0,15.75 and 10.0
and the remaining elements to zero.
char name[5]={‘a’,’b’,’c’}; remaining elements filled with NULL.
The size can be omitted. In such case the compiler allocated enough space for all initialized
elements.
Example:-
o int counter[ ] ={1,1,1,1};
o char name[ ]={‘j’,’o’,’h’,’n’,’\o’};
300 400
Each dimension of the array is indexed from zero to its maximum size minus one.
The first index selects the row and the second index selects the column with in tha trow.
Initialization:-
Two –dimensional arrays can be initializedd similar to that of the one-dimensional arrays.
Static type array_name[row size] [column size]=list of values;
Eg:-
int table[2][3]={0,0,0,1,1,1};
The above declaration will initialize the elements of the first row to 0 and the second row to 1. \
The initialization is done row by row.
The above statement can also be written as:
int table[2][3]={{0,0,0},{1,1,1};
If the initialization has some missing values then they are automatically initialized to 0.
Example:-
int table[2][3]={
- 26 –
{1,1},
{2}
}
In the above example the first two elements of the first row is initialized to one, the first element
of the second row is initialized to 2 and the remaining elements are initialized to 0.
When all the elements are to be initialized to zero the following short-cut method may be used.
Example:-
int a[3] [5] ={{0},{0},{0};
In this example the first element of each row is explicitly initialized to zero while other elements
are automatically initialized to zero.
The following statement will also achieve the same result.
Example:-
int array [3] [5]={0,0}’
Example:-
Program to read and write two dimensional array in the form of matrix,
main()
int a[3] [3],I,j;
/*TO READ A MATRIX*/
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>a[i] [j];
/*TO WRITE A MATRIX*/
for(i=0;i<3;i++)
{
Cout<<”\n””\n”;
for(j=0;j<3;j++)
cout<<a[i] [j];
}
}
Multi Dimensional Array:-
C allows arrays of three or more dimensions.
The exact limit is determined by the compile
The general form of a multi-dimensional array is.
Syntax:-
type array_name [s1] [s2] [s3]……[sm];
- 27 –
Where si is the size of the ith dimensions.
Example:-
int survery [3][2][12];
float table[5][4][5][3];
In the above example, survery is a three-dimensional array declared to contain 180 integer type
elements.
Similarly table is a four-dimensional array containing 300 elements of floating-point type.
The total number of elements in any dimension of array is the product of all sizes included in the
declaration. So it will be s1*s2*s3*…*sm.
Higher dimension arrays are required in the field of scientific computing, weather forecasting,
timespace analysis, etc.,
A three-dimensional array can be represented as a series of two-dimensional arrays.
ANSI C does not specify any limit for array dimension, most compilers permit seven to ten
dimensions.
#include<stdio.h>
#include<string.h> for(j=0;j<3;j++)
#include<conio.h>
void main() cin>>b[i] [j];
{ for(i=0;i<3;i++)
main() for(j=0;j<3;j++)
{ c[i] [j] =a[i] [j] + b[i]
int a[3] [3] , b [3] [3] , c [3] [3] ; [j] ;
int i, j; cout<<”sum \n”;
cou<<”\n enter a matrix”; for(i=0;i<3;i++)
for(i=0;i<3;i++) {
for(j=0;j<3;j++) Cout<<”\n”;
cin>>a[i] [j]; for(j=0;j<3;j++)
cout<<”\n enter b matrix “; cout<< c[i] [j];
Dynamic array:-
for(i=0;i<3;i++)
getch();
}
Definition:- }
- 28 –
The dynamic array is an array data structure which can be resized during runtime which means
elements can be added and removed.
An array created at compile time by specifying size in the source code has a fixed size and
cannot be modified at run time.
The process of all allocating memory at compile time is known as static memory allocation and
the arrays that receive static memory allocation are called static arrays.
The approach works fine as long as the user knows exactly what the data requirements are.
C allows allocating memory to arrays at run time. This feature is known as dynamic memory
allocation and the array created at run time are called dynamic arrays.
Dynamic arrays are created by using pointer variables and memory management functions
malloc, calloc and realloc.
These functions are included in the header fine #include<stdlib.h>
The concept of dynamic arrays is used in creating and manipulating data structure such as linked
list stacks and queues.
It is possible to allocate memory to arrays at run time.
This feature is known as dynamic memory allocation and the arrays created at run time are called
dynamic arrays.
#include<stdio.h>
#include <stdlib.h> printf("\n");
#include<conio.h> for(j=1;j<=2;j++)
printf("Enter number %d: ",i);
#include <stdio.h>
void main() {
scanf("%d",&array[i]);
{
#include <conio.h> c[i][j]=a[i][j]+b[i][j];
int a[10][10],b[10][10],c[10][10]; }printf("%d",c[i][j]);
intintmain(){
i,j,k; } for(i=0;i<3;i++)
clrscr();
int* array; }
printf("\nThe Dynamic Array is: \n");
printf("Matrix a:"); }
int n,i;
for(i=1;i<=2;i++) OutPut:-
for(i=0;i<n;i++){
{
printf("Enter the number of elements: Matrix a:
printf("The value of %d is %d\
printf("\n"); 3
");for(j=1;j<=2;j++) 3
n",i,array[i]);
scanf("%d",&a[i][j]);
scanf("%d",&n); 3
}
} 3
array = (int*) malloc(n*sizeof(int)); printf("Size= %d\n",i);
printf("Matrix b:"); Matrix b:
getch();
for(i=1;i<=2;i++)
for(i=0;i<n;i++) 3
return 0;
{ 3
{ printf("\n"); }
3
for(j=1;j<=2;j++) 3
scanf("%d",&b[i][j]); Addition of Matrix A and B:
} 66
printf("\n Addition of Matrix A and B:"); 66
for(i=1;i<=2;i++)
{
- 29 –
*********************Unit II Completed**********************
- 30 –