0% found this document useful (0 votes)
22 views30 pages

Unit - II Decision Making

The document discusses different types of decision making and branching statements in C language including if, if else, nested if else, and else if ladder statements. Examples are provided for each type of statement to control program flow based on various conditions.

Uploaded by

ttramkumr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views30 pages

Unit - II Decision Making

The document discusses different types of decision making and branching statements in C language including if, if else, nested if else, and else if ladder statements. Examples are provided for each type of statement to control program flow based on various conditions.

Uploaded by

ttramkumr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 30

JSV COLLEGE OF ARTS AND SCIENCE

AATTUKARAMPATTI, DHARMAPURI-9

C lass : I B.Sc., (C.S) Staff : P. Ravi M.CA.,


Subject : Programming in “C” H.O.D : J. Ganesan M.CA., B.Ed.,

Unit – II Making and Branching


Introduction:-
 A C program is a set of statements which are normally executed sequentially in order in
which they appear.
 In some cases we may have to change the order or execution of statements based on
certain conditions or repeats a group of statements.
 C language possesses such decision making capabilities by supporting the following
statements.
 If statements
 Switch statement
 Conditional operator statement
 Goto Statement
 These statements are known as decision-making statements. These are used to control the
flow of execution, they are also known as control statements.
Decision making and branching:-
 The if statement is a powerful decision-making statement used to control the flow
execution of statements.
 It is basically a two-way decision statement and is used in conjunction with an
expression.
 C language supports the following statements known as control or decision making
Statements.
Syntax:-
If (test_expression)

 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

 Some examples of decision making, using if statements are


 If (bank balance is zero)
borrow money
 If (room is dark)
put on lights
 If (code is 1)
person is male
 If (age is more than 55)
person is retired
Simple If Statement:-
 The if statement is used to control the flow of execution of statements.
 It checks the given condition whether the given condition is true
 Syntax:-
If (test_expression)
{
statement-blocks;
}
statement-x;
-2–
 The “statement-block” may be a single statement or a group of statement
 If the test expression must be enclosed in parentheses
 The statement-block may be a single statement or a group of statements.
 If the test expression is true the statement-block will be executed otherwise the statement-block
will be skipped and the execution will jump to the statement-x.
 When the test expression is true both the statement-block and the statement-x are executed in
sequence.
Flowchart of simple if control:-
Entry

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

Nesting of if…..else statements


 When a series of decisions are involved, we may have to use more than one if….else statements, in
nested form as follows.

If (test_condition1)
{
if(test_condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x; -5–
Entry

test
False condition 1 True
?

False test True


condition
2 ?

Statement-3 Statement-2 Statement-1

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

Example:- The following program checks whether a given number is positive or


negative or zero.
#include<stdio.h> printf("Zero");
#include<conio.h> else
void main() printf("\d The number is Positive");
{ getch();
int n; }
printf("\n Enter the a number");
scanf("%d",&n); OUTPUT
if(n<=0) Enter Numbers:
if(n<0) 12
printf("\d The number is Negative"); The Number is positive
else

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

 The conditions are evaluated from the top.


 As soon as a true condition is found, the statement associated with it is executed and the control
is transferred to the statement-x.
 When all the n conditions become false, the final else containing the default-statement will be
executed.

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

main() charges = 230 + 0.8 * (units – 400)


{ else
int units, cno; charges = 390 + (units – 600);
float charges; printf(“\n \ncustomer no =%d,charges =%.2f \
printf(“Enter customer no. and units n”,cno,charges);
consumed \n”); }
scanf(“%d %d”,&cno, &units ); OUTPUT
if(units <= 200) Enter customer no. and units consumed 101
150
charges = 0.5 * units;
Customer no=101 charges = 75.00
else if(units <= 400)
charges = 100+ 0.65 * (units – 200)
else if (units <= 600)

The Switch Statement:-


 Switch statement is used for complex programs when the number of alternatives increases.
 The switch statement tests the value of the given variable against the list of case values and when
switch
a match is found, a block (expression)
of statements associated with that case is executed.
The general form of{ switch statement is
case value1: block1;
break;
case value2: block 2;
break;
……………………
default:
default block;
break;
} -9–
statement x;
 The expression is an integer expression or characters.
 Value 1, value2…. are constants or constant expressions and are known as case labels.
 Each of these values should be unique within a switch statement.
 Block1, block2 are statement list and may contain zero or more statements.
 The break statement at the end of each block signal the end of particular case and causes an exits
from the switch statement, transferring the control to the statement x following switch.
 The default is an optional case, when present it will be executed if the value of the expression
does not match with any of the case values.
 When the switch is executed, the value of the expression is compared against the value value1,
value2… if a case is found whose value matches with the values of the expression, the block of
statements that follows the case are executed.

Switch
Expression

Expression = value -1
Block -1

Expression = value -2 Block -1

(no match) defualt


Default
Block -1

Statement-x

Rules for switching statements:-


- 10 –
 The switch expression must be an integral type.
 Case labels must be constants or constant expressions.
 Case labels must be unique. No two labels can have the same value.
 Case labels must end with semicolon.
 The break statement transfers the control out of the switch statement.
 The break statement is optional. If present, it will be executed when the expression does not find
a matching case label.
 The default may be placed anywhere but usually placed at the end.
 It is permitted to nest switch statements.

# include <stdio.h> case 3 :


voidmain() printf(“yellow”);
{ break;
int c;
default:
printf(“Enter a number:”);
scanf(“%d”,&c); print(“invalid”);
switch©
break;
{
case 1: }
printf(“blue”);
}
break;
Output:-
case 2:
Enter a number : 3
printf(“green”);
yellow
break;

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.

conditional expression ? expression 1: expression 2

 The conditional expression is evaluated first.


 If the result is non zero, expression 1 is evaluated and is returned as the value of the conditional
expression.
 Otherwise, expression 2 is evaluated and its value is returned.
 For example:-

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

Body of the loop


Test False
condition
?

test False
condition
True ?
Body of the loop

True

(a) Entry controlled loop (b) Exit controlled loop


Exit – Controlled loop:-

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

The For Statement:-


Simple “for” Loops:-
 The for loop is another entry-controlled loop that provides a more concise loop control
structure.
The general form of the for loop is

for (initialization; test-condition; increment)


{
body of the loop
}

The execution of the for statement is as follows:


 Initialization of the control variables is done first, using assignment statements such as I = 1 and
count =0. The variables I and count are known as loop-control variables.
 The value of the control variable is tested using the test-condition.
 The test-condition is a relational expression, such as i < 10 that determines when the loop will
exit.
 If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the
execution continues with the statement that immediately follows the loop.

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

Additional features of for loop:-


 The for loop in c has several capabilities that are not found in other loop constructs.
 For example we can initialize more than one variables at a time a in the for statements.
p = 1;
for (n=0;n<17;++n) can be written as
for (p=1,n=0;n<17;++n)
 Here the initialization section has two parts p =1 and n=1 are separated by comma.
 Like the initialization section, the increment section may also have more than one part.
 The multiple arguments in the increment section are separated by commas.
 Example:-
for(n=1,m=50;n<=m;n=n+1,m=m-1)
{
p=m/n;
printf(“%d%d\n”,n,m,p);
}
 The third feature is that the test-condition may have any compound relation and the testing need
not be limited only to the loop control variable.
 Example:
sum=0;

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

BASIC : DIMENSION A[100]


FORTRAN : DIM A[100]
PASCAL : A : ARRAY[1…1000] 0f Integer
C : int a[100]

Types Of Array:-
1. One dimensional array

2. Two dimensional arrays


- 21 –
3. Multi dimensional arrays
One Dimensional Array:-
Definition:
 A list of data items can be given to one variable name using subscript is called one dimensional
array.
 If only one subscript/index is required to reference all the elements in an array, then the array is
termed one-dimensional array or simply an array.
 The arrays are defined as the collection of similar type of elements.
 This means an array either all the elements can be of integer type or float type or all of character.
 The subscript can begin with number0.
 That is
x[0], x[1]……………..x[n]
 The subscripts of an array can be integer constants, integer variable like I or expression that yield
integers.
 This means an array either all the elements can be of integer type or float type or all of character.
o Data_type name_of_array[size_of_array];
10

 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

Initialization Of One Dimensional Array:-


 An array is declared, its elements must be initialized. Otherwise, they will contain “garbage”.
 An array can be initialized at either of the following stages.
 At compile time
 At run time.
Compile time initialization:-
 We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared.
 Syntax:- Type array-name [size]={list of values};

 The values in the list are separated by commas.


 Examples:-
 int number [3] ={0,0,0};
 If the number of values in the list is less than the number of elements, then only that many
elements will be initialized.
 The remaining elements are initialized to zero if the array type is numeric and NULL if the type
is character.

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

Run time initialization:-


 An array can be explicitly initialized at run time.
 This approach is usually applied for initializing large arrays.
 For example, consider the following segment of a c program.
 Example:-
-----------------------
-----------------------
for (i=0; I <100; I = I +1)
{
if I < 50
sum[i] = 0.0;
else
sum[i]=1.0;
}
-----------------------
-----------------------
 The first 50 elements of the array sum are initialized to zero while the remaining 50 elements are
initialized to 1.0 at run time. for(j=0;j<n;j++)
#include<stdio.h> if(num[i]>num[j])
#include<string.h> {
#include<conio.h> temp=num[i];
void main() num[i]=num[j];
{ num[j]=temp;
int num[100]; }
int n,i,j,temp; }
clrscr(); printf("\nSorted list is\n");
printf("Enter the number of elements:\ for(i=0;i<n;i++)
n"); printf("%d",num[i]);
scanf("%d",&n); getch();
printf("\nThe elements in the array are:\ }
n");
for(i=0;i<n;i++) OutPut:-
{ Enter the number of elements:3
scanf("%d",&num[i]); The elements in the array are:2 3 5
} Sorted list is : 5 3 2
for(i=0;i<n;i++)
{ - 25 –
Two Dimensional Arrays:-
 Two-dimensional arrays can be used to store table of values. They can used to store a set of
values in matrix form consisting of row and columns.
 Two dimensional arrays are used in situation where a table of values need to be stored in array .
 Two pairs of square brackets are required for two dimensional arrays.
 Two dimensional arrays are stored in a row column matrix where the left index indicates
column.
Syntax:-
type array_name [row size] [column size];
Eg:-
a [2] [2];
column 0 column 1
row 0 [0][0] [0][1]
310 275

row 1 [1][0] [1][1]

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 –

You might also like