[go: up one dir, main page]

0% found this document useful (0 votes)
13 views34 pages

Unit Iii

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)
13 views34 pages

Unit Iii

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

24CSE401 - UNIT III

UNIT III
Decision making statements - Switch statement - Looping statements – Pre-processor
directives - Compilation process – One dimensional array – Two dimensional array –
Multidimensional array.

Decision making statements - Switch statement – Looping statements

Decision making statements in a programming language help the programmer to


transfer the control from one part to other part of the program.

Flow of control: The order in which the program statements are executed is known as flow
of control. By default, statements in a c program are executed in a sequential order.
The default flow of control can be altered by using flow control statements. These
statements are of two types.
Selection-Conditional Branching

1.Branching

Jump-unconditional Branching
2.Iteration statements

Branching statements
Branching statements are used to transfer program control from one point to another.
2 types
a) Conditional Branching:- Program control is transferred from one point to another
based on the result of some condition
Eg) if, if-else, switch
b) Unconditional Branching:- Program control is transferred from one point to another
without checking any condition
Eg) goto, break, continue, return

a) Conditional Branching : Selection statements


Statements available in c are
 The if statement
 The if-else statement
 The switch case statement
(i)The if statement
C uses the keyword if to execute a statement or set of statements when the logical
condition is true.
Syntax:
if (test expression)
Statement; Test F
expres
sion

T
Statement
1
24CSE401 - UNIT III

 If test expression evaluates to true, the corresponding statement is executed.


 If the test expression evaluates to false, control goes to next executable
statement.
 The statement can be single statement or a block of statements. Block of
statements must be enclosed in curly braces.
Example:
#include <stdio.h>
void main()
{
int n;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
if(n>0)
printf(“the number is positive”);
getch();
}
Output:
enter the number:50
the number is positive

(ii)The if-else statement


Syntax: Test
expr
if (test expression) essio
Statement T; n
T F
else
Statement F; Stateme
Stateme
ntT ntF

 If the test expression is true, statementT will be executed.


 If the test expression is false, statementF will be executed.
 StatementT and StatementF can be a single or block of statements.

Example:1 Program to check whether a given number is even or odd.


#include <stdio.h>
void main()
{
int n,r;
clrscr();
printf(“Enter a number:”);
scanf(“%d”,&n);
r=n%2;
if(r==0)
printf(“The number is even”);
2
24CSE401 - UNIT III

else
printf(“The number is odd”);
getch();
}

Output:
Enter a number:15
The number is odd

Example:2 To check whether the two given numbers are equal


void main()
{
int a,b;
clrscr();
printf(“Enter a and b:” );
scanf(“%d%d”,&a,&b);
if(a==b)
printf(“a and b are equal”);
else
printf(“a and b are not equal”);
getch();
}
Output:
Enter a and b: 2 4
a and b are not equal

(iii) Nested if statement


If the body the if statement contains another if statement, then it is known as nested if
statement
Syntax:
if (test expression) if (test expression)
if (test expression) {
statement;
if (test expression)
(Or) ….
This nesting can be done up to any level. statement;
else Syntax: }
Statement F;
if (test expression1)
{
…..
if (test expression2)
{
….
if (test expression3)
This is known as if ladder
{
….
if (test expression n) 3
}}}
24CSE401 - UNIT III

iv) Nested if-else statement


Here, the if body or else body of an if-else statement contains another if statement or if
else statement
Syntax:
if (condition)
{
statement 1;
statement 2;
}
else
{
statement 3;
if (condition)
statementnest;
statement 4;
}
Example:
Program for finding greatest of 3 numbers
#include<stdio.h>
void main()
{
int a,b,c;
printf(“Enter three numbers \n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“a is greatest”);
}
}
else
{
if(b>c)
{
printf(“b is greatest”);
}
else
{
printf(“C is greatest”);
}
}
}
Output
Enter three numbers 2 4 6
C is greatest
4
24CSE401 - UNIT III

v) Switch statement
 It is a multi way branch statement.
 It provides an easy & organized way to select among multiple operations depending
upon some condition.
Execution
1. Switch expression is evaluated.
2. The result is compared with all the cases.
3. If one of the cases is matched, then all the statements after that matched case gets
executed.
4. If no match occurs, then all the statements after the default statement get executed.
 Switch ,case, break and default are keywords
 Break statement is used to exit from the current case structure
Flowchart
switch(expression)

case: break
constant 0 statement

case :
statement break
constant 1

default
statement break

Syntax
switch(expression) End of switch
{
case value 1:
program statement;
program statement;
……
break;
case value 2:
program statement;
Program statement;
……
break;

case value n:
program statement;
program statement;
……
break; 5
default:
program statement;
program statement;
}
24CSE401 - UNIT III

Example1
void main()
{
char ch;
printf(“Enter a character \n”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘A’:
printf(“you entered an A\n”);
break;
case ‘B’:
printf(“you entered a B\n”);
break;
default:
printf(“Illegal entry”);
break;
}
getch();
}
Output
Enter a character
A
You entered an A

Example2
void main()
{
int n;
printf(“Enter a number \n”);
scanf(“%d”,&n);
switch(n%2)
{
case 0:printf(“EVEN \n”);
break;
case 1:printf(“ODD \n”);
break;
}
getch();
}

Output:
Enter a number
5
ODD

6
24CSE401 - UNIT III

b)Unconditional branching statements

i)The goto Statement


This statement does not require any condition. Here program control is transferred to
another part of the program without testing any condition.
Syntax:
goto label;

 label is the position where the control is to be transferred.


Example:
void main()
{
printf(“www.”);
goto x;
y:
printf(“mail”);
goto z;
x:
printf(“yahoo”);
goto y;
z:
printf(“.com”);
getch();
}
Output: www.yahoomail.com

b)break statement
 A break statement can appear only inside a body of , a switch or a loop
 A break statement terminates the execution of the nearest enclosing loop or
switch.
Syntax
break;
break;

Example:1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
break;
printf(“\t %d”,c);
c++;
7
24CSE401 - UNIT III

}
}

Output : 1 2

Example :2
#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if (i==5)
break;
printf(“ %d”,i);
}
}
Output :1 2 3 4

iii) continue statement


 A continue statement can appear only inside a loop.
 A continue statement terminates the current iteration of the nearest enclosing
loop.
Syntax:
continue;

Example :1
#include<stdio.h>
void main()
{
int c=1;
while(c<=5)
{
if (c==3)
continue;
printf(“\t %d”,c);
c++;
}
}
Output : 1 2 4 5

Example :2
#include<stdio.h>
main()
{
int i;
8
24CSE401 - UNIT III

for(i=0;i<=10;i++)
{
if (i==5)
continue;
printf(“ %d”,i);
}
}

Output :1 2 3 4 6 7 8 9 10

iv) Return statement:


A return statement terminates the execution of a function and returns the control to the
calling function.
Syntax:

return;

(or)

return expression;

Iteration Statements (Looping Statements)


Iteration is a process of repeating the same set of statements again and again until the condition
holds true.
Iteration or Looping statements in C are:
1. for
2. while
3. do while
Loops are classified as
 Counter controlled loops
 Sentinel controlled loops
Counter controlled loops
 The number of iterations is known in advance. They use a control variable called loop
counter.
 Also called as definite repetitions loop.
 E.g: for
Sentinel controlled loops
 The number of iterations is not known in advance. The execution or termination of the loop
depends upon a special value called sentinel value.
 Also called as indefinite repetitions loop.
 E.g: while

1. for loop
It is the most popular looping statement.
Syntax:
for(initialization;condition2;incrementing/updating)
{
Statements; 9
}
24CSE401 - UNIT III

There are three sections in for loop.


a. Initialization section – gives initial value to the loop counter.
b. Condition section – tests the value of loop counter to decide whether to execute the
loop or not.
c. Manipulation section - manipulates the value of loop counter.

Execution of for loop


1. Initialization section is executed only once.
2. Condition is evaluated
a. If it is true, loop body is executed.
b. If it is false, loop is terminated
3. After the execution of loop, the manipulation expression is evaluated.
4. Steps 2 & 3 are repeated until step 2 condition becomes false.

Ex 1: Write a program to print 10 numbers using for loop


void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d”,i);
}
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10
Ex2: To find the sum of n natural number. 1+2+3…+n
void main()
{
int n, i, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
4
sum=10

2. while statement
 They are also known as Entry controlled loops because here the condition is checked before the
execution of loop body.
Syntax:
10
24CSE401 - UNIT III

while (expression)
{
statements;
}

Execution of while loop


a. Condition in while is evaluated
i. If it is true, body of the loop is executed.
ii. If it is false, loop is terminated
b. After executing the while body, program control returns back to while header.
c. Steps a & b are repeated until condition evaluates to false.
d. Always remember to initialize the loop counter before while and manipulate loop counter
inside the body of while.

Ex 1: Write a program to print 10 numbers using while loop


void main()
{
int i=1;
clrscr();
while (num<=10)
{
printf (“%d”,i);
i=i+1;
}
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10

Ex2: To find the sum of n natural number. 1+2+3…+n


void main()
{
int n, i=1, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
while(i<=n)
{
sum=sum+i;
i=i+1;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
4
Sum=10

3. do while statement
11
24CSE401 - UNIT III

 They are also known as Exit controlled loops because here the condition is checked after the
execution of loop body.
Syntax:
do
{
statements;
}
while(expression);

Execution of do while loop


a. Body of do-while is executed.
b. After execution of do-while body, do-while condition is evaluated
i. If it is true, loop body is executed again and step b is repeated.
ii. If it is false, loop is terminated

 The body of do-while is executed once, even when the condition is initially false.

Ex1: Write a program to print 10 numbers using do while loop


void main()
{
int i=1;
clrscr();
do
{
printf (“%d”,i);
i=i+1;
} while (num<=10);
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10

Ex2: To find the sum of n natural number. 1+2+3…+n


void main()
{
int n, i=1, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
do
{
sum=sum+i;
i=i+1;
} while(i<=n);
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n
12
24CSE401 - UNIT III

4
Sum=10

Three main ingredients of counter-controlled looping


1. Initialization of loop counter
2. Condition to decide whether to execute loop or not.
3. Expression that manipulates the value of loop.

Nested loops
 If the body of a loop contains another iteration statement, then we say that the loops are nested.
 Loops within a loop are known as nested loop.
 Syntax
while(condition)
{
while(condition)
{
Statements;
}
Statements;
}

PRE-PROCESSOR DIRECTIVES

 The C preprocessor is a microprocessor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros. Preprocessor
directives are executed before compilation.

All preprocessor directives starts with hash # symbol.

Let's see a list of preprocessor directives.


 #include
 #define
 #undef
 #ifdef
 #ifndef
 #if
 #else
 #elif
 #endif
 #error
 #pragma
13
24CSE401 - UNIT III

S.no Preprocessor Purpose Syntax

1. #include Used to paste code of given file into current #include <filename>
file. It is used include system-defined and #include “filename”
user-defined header files. If included file is
not found, compiler renders error.
2. #define Used to define constant or micro #define PI 3.14
substitution. It can use any basic data type
3. #undef Used to undefine the constant or macro #define PI 3.14
defined by #define #undef PI
4. #ifdef Checks if macro is defined by #define. If #ifdef MACRO
yes, it executes the code otherwise #else //code
code is executed, if present. #endif
5. #ifndef Checks if macro is not defined by #define. #ifndef MACRO
If yes, it executes the code otherwise #else //code
code is executed, if present. #endif

6. #if Evaluate the expression or condition. If #if expression


condition is true, it executes the code //code
otherwise #elseif or #else or #endif code is #endif
executed.
7. #else Evaluates the expression or condition if #if expression
condition of #if is false. It can be used with //if code
#if, #elif, #ifdef and #ifndef directives #else
//else code
#end if
8. #error Indicates error. The compiler gives fatal #error First include
error if #error directive is found and skips then c ompile
further compilation process
9. #Pragma Used to provide additional information to #pragma token
the compiler. The #pragma directive is used
by the compiler to offer machine or
operating-system feature.

COMPILATION PROCESS

What is compilation?

Compilation is the process the computer takes to transform a program written in a high-level language
from source code into machine code that the computer can understand.

14
24CSE401 - UNIT III

Compiling a C Program

A sequence of binary instructions consisting of 1 and 0 bits is called as machine code. High-level
programming languages such as C, C++, Java, etc. consist of keywords that are closer to human
languages such as English. Hence, a program written in C (or any other high-level language) needs to
be converted to its equivalent machine code. This process is called compilation.

Note that the machine code is specific to the hardware architecture and the operating system. In other
words, the machine code of a certain C program compiled on a computer with Windows OS will not
be compatible with another computer using Linux OS. Hence, we must use the compiler suitable for
the target OS.

C Compilation Process Steps

In this tutorial, we will be using the gcc (which stands for GNU Compiler Collection). The GNU
project is a free-software project by Richard Stallman that allows developers to have access to
powerful tools for free.

The gcc compiler supports various programming languages, including C. In order to use it, we should
install its version compatible with the target computer.

15
24CSE401 - UNIT III

The compilation process has four different steps −

 Preprocessing

 Compiling

 Assembling

 Linking

The following diagram illustrates the compilation process.

16
24CSE401 - UNIT III

Example

To understand this process, let us consider the following source code in C languge (main.c) -

Output

Run the code and check its output −

The ".c" is a file extension that usually means the file is written in C. The first line is the preprocessor
directive #include that tells the compiler to include the stdio.h header file. The text
inside /* and */ are comments and these are useful for documentation purpose.

The entry point of the program is the main() function. It means the program will start by executing
the statements that are inside this function’s block. Here, in the given program code, there are only
two statements: one that will print the sentence "Hello World" on the terminal, and another statement
that tells the program to "return 0" if it exited or ended correctly. So, once we compiled it, if we run
this program we will only see the phrase "Hello World" appearing.

17
24CSE401 - UNIT III

What Goes Inside the C Compilation Process?

In order for our "main.c" code to be executable, we need to enter the command "gcc main.c", and the
compiling process will go through all of the four steps it contains.

Step 1: Preprocessing

The preprocessor performs the following actions −

 It removes all the comments in the source file(s).

 It includes the code of the header file(s), which is a file with extension .h which contains C
function declarations and macro definitions.

 It replaces all of the macros (fragments of code which have been given a name) by their values.

The output of this step will be stored in a file with a ".i" extension, so here it will be in "main.i".

In order to stop the compilation right after this step, we can use the option "-E" with the gcc
command on the source file, and press Enter.

Step 2: Compiling

The compiler generates the IR code (Intermediate Representation) from the preprocessed file, so this
will produce a ".s" file. That being said, other compilers might produce assembly code at this step of
compilation.

We can stop after this step with the "-S" option on the gcc command, and press Enter.

This is what the main.s file should look like –

18
24CSE401 - UNIT III

Step 3: Assembling

The assembler takes the IR code and transforms it into object code, that is code in machine language
(i.e. binary). This will produce a file ending in ".o".

We can stop the compilation process after this step by using the option "-c" with the gcc command,
and pressing Enter.
19
24CSE401 - UNIT III

Note that the "main.o" file is not a text file, hence its contents won't be readable when you open this
file with a text editor.

Step 4: Linking

The linker creates the final executable, in binary. It links object codes of all the source files together.
The linker knows where to look for the function definitions in the static libraries or the dynamic
libraries.

Static libraries are the result of the linker making a copy of all the used library functions to the
executable file. The code in dynamic libraries is not copied entirely, only the name of the library is
placed in the binary file.

By default, after this fourth and last step, that is when you type the whole "gcc main.c" command
without any options, the compiler will create an executable program called main.out (or main.exe in
case of Windows) that we can run from the command line.

We can also choose to create an executable program with the name we want, by adding the "-o"
option to the gcc command, placed after the name of the file or files we are compiling.

So now we could either type "./hello.out" if you didn’t use the "-o" option or "./hello" to execute the
compiled code. The output will be "Hello World" and following it, the shell prompt will appear
again.

20
24CSE401 - UNIT III

Arrays
Definition:
An array is a data structure that is used to store data of the same type. The position of an
element is specified with an integer value known as index or subscript.
E.g.
1 3 5 2 a(integer array)

1.2 3.5 5.4 2.1 b(float array )

[0] [1] [2] [3]


Characteristics:
i) All the elements of an array share a common name called as array name
ii) The individual elements of an array are referred based on their position.
iii) The array index in c starts with 0.

In general arrays are classified as:


1.Single dimensional array
2.Two-dimensional and Multi-dimensional array

1. Single or one dimensional array


 It is also known as one-dimensional arrays or linear array or vectors
 It consists of fixed number of elements of same type
 Elements can be accessed by using a single subscript. eg) a[2]=9;
Eg)
1 3 5 2
a
[0] [1] [2] [3] subscripts or indices

Declaration of Single Dimensional Array


Syntax:
datatype arrayname [array size];

E.g. int a[4]; // a is an array of 4 integers


char b[6]; //b is an array of 6 characters

Initialization of single dimensional array


Elements of an array can also be initialized.
Rules
a) Elements of an array can be initialized by using an initialization list. An initialization list is
a comma separated list of initializers enclosed within braces.
Eg) int a[3]={1,3,4};
b) If the number of initializers in the list is less than array size, the leading array locations gets
initialized with the given values. The rest of the array locations gets initialized to
0 - for int array
21
24CSE401 - UNIT III

0.0 - for float array


\0 - for character array

Eg) int a[2]={1};


a 1 0

char b[5]={‘A’.’r’,’r’};

b ‘A’ ‘r’ ‘r’ ‘\0’ ‘\0’

Usage of single dimensional array


The elements of single dimensional array can be accessed by using a subscript
operator([]) and a subscript.

Reading storing and accessing elements:


An iteration statement (i.e loop) is used for storing and reading elements.
Ex:1 Program to calculate the average marks of the class
#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float avg;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
avg=(float)sum/n;
printf(“average=%f”,avg);
}
Output:
Enter number of students
5
Enter marks of students
55
60
78
85
90
Average=73.6

22
24CSE401 - UNIT III

EXAMPLE PROGRAMS:
1.Computing Mean
2.Computing Median
3.Computing Mode

1.Computing Mean:
\* C Program to to find the mean of n numbers using array *\
#include <stdio.h>
void main()
{
int m[5],i,sum=0,n;
float mean;
printf(“enter number of students \n”);
scanf(“%d”,&n);
printf(“enter marks of students \n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&m[i]);
}
for(i=0;i<n;i++)
sum=sum+m[i];
mean=(float)sum/n;
printf(“Mean=%f”,mean);
}
Output:
Enter number of students
5
Enter marks of students
55
60
78
85
90
Mean=73.6

2.Computing Median:
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,temp,n,a[20],sum=0;
float median;
printf("enter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
23
24CSE401 - UNIT III

printf("\n enter %d number:",i+1);


scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
if(n%2==0)
{
median=((a[n/2]+a[n/2 -1])/2.0);
}
else
{
median=a[n/2];
}
printf("\n the median value is %f",median);
getch();
}
Output:
Enter N:5
Enter 1 number:11
Enter 2 number:12
Enter 3 number:13
Enter 4 number:14
Enter 5 number:15
The median value is 13.000000

3.Computing Mode:
#include<stdio.h>
#include<conio.h>
void main()
{
int maxvalue = 0, maxCount = 0, i, j,a[20],n,count=0;
clrscr();
printf("enter the N value:");
scanf("%d",&n);
for(i = 0; i < n;i++)
{
24
24CSE401 - UNIT III

printf("\n Enter %d number:",i+1);


scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for (j = i+1; j < n;j++)
{
if(a[j] == a[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxvalue = a[i];
printf("\nThe mode value is %d",maxvalue);
}
}
getch();
}
Output:
Enter the N value:5
Enter 1 Number:0
Enter 2 Number:6
Enter 3 Number:7
Enter 4 Number:2
Enter 5 Number:7
The mode value is 7

2. Two dimensional arrays (2 D Arrays)


 A 2D array is an array of 1-D arrays and can be visualized as a plane that has rows and
columns.
 The elements can be accessed by using two subscripts, row subscript (row no), column
subscript(column no).
 It is also known as matrix.
E.g,
1 2 3 6 7
9 10 5 0 4
a[3][5]
3 1 2 1 6

Declaration

datatype arrayname [row size][column size]

25
24CSE401 - UNIT III

e.g) int a [2][3]; //a is an integer array of 2 rows and 3 columns


number of elements=2*3=6

Initialization
1. By using an initialization list, 2D array can be initialized.
e.g. int a[2][3] = {1,4,6,2}

1 4 6
a
2 0 0

2. The initializers in the list can be braced row wise.


e.g int a[2][3] = {{1,4,6} , {2}};

Example: Matrix Addition


#include<stdio.h>
#include<conio.h>
main()
{
int a[25][25],b[25][25], c[25][25], i, j m, n;
clrscr();
printf(“\n Enter the rows and columns of two matrices… “);
scanf(“%d %d “, &m, &n)
printf{“\n Enter the elements of A matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&a[i][j]);
printf{“\n Enter the elements of B matrix…”);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”, &b[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j]=a[i][j] + b[i][j];
printf(“\n The addition of two matrices”);
for(i=0;i<m;i++)
{
printf(“\n”);
for(j=0;j<n;j++)
{
printf(“\t %d”,c[i][j]);
}
}
getch();
}
26
24CSE401 - UNIT III

Output:
Enter the rows and columns of two matrices…. 3 3
Enter the elements of A matrix… 1 2 3 4 5 6 7 8 9
Enter the elements of B matrix… 1 2 3 4 5 6 7 8 9
The addition of two matrixes
246
8 10 12
14 16 18

Example: Matrix Multiplication


#include <stdio.h>
#include <conio.h>
main()
{
int a[10][10], b[10][10], c[10][10];
int r1, c1, r2, c2;
int i, j, k;
clrscr();
printf("Enter order of matrix A : ");
scanf("%d%d", &r1, &c1);
printf("Enter order of matrix B : ");
scanf("%d%d", &r2, &c2);
if (c1 != r2)
{
printf("Matrix multiplication not possible");
getch();
exit(0);
}
printf("Enter matrix A elements\n");
for(i=0; i<r1; i++)
for(j=0; j<c1; j++)
scanf("%d", &a[i][j]);
printf("Enter matrix B elements\n");
for(i=0; i<r2; i++)
for(j=0; j<c2; j++)
scanf("%d", &b[i][j]);
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
c[i][j] = 0;
for(k=0; k<c1; k++)
{
c[i][j] =c[i][j]+ a[i][k] * b[k][j];
}
}
27
24CSE401 - UNIT III

}
printf("Product matrix C\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}

Output
Enter order of matrix A : 2 3
Enter order of matrix B : 3 2
Enter matrix A elements
111
111
Enter matrix B elements
22
22
22
Product matrix C
66
66

Example: Matrix Scaling


#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
void main()
{
int graphdriver=DETECT,graphmode,errorcode;
int i;
int x2,y2,x1,y1,x,y;
printf("Enter the 2 line end points:");
printf("x1,y1,x2,y2");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
initgraph(&graphdriver,&graphmode,"c:\\tc\\bgi");
line(x1,y1,x2,y2);
printf("Enter scaling co-ordinates ");
printf("x,y");
scanf("%d%d",&x,&y);
x1=(x1*x);
28
24CSE401 - UNIT III

y1=(y1*y);
x2=(x2*x);
y2=(y2*y);
printf("Line after scaling");
line(x1,y1,x2,y2);
getch();
closegraph();
}

Example: Matrix Determinant


C code for Determinant of 2X2 matrix:

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j;
long determinant;
clrscr();
printf("Enter the 4 elements of matrix: ");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d",&a[i][j]);
}
printf("\nThe matrix is\n");
{
for(i=0;i<2;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",a[i][j]);
}
}
29
24CSE401 - UNIT III

determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1];


printf("\nDeterminant of 2X2 matrix: %ld",determinant);
getch();
}
Output:
Enter the 4 elements of matrix 4 8 3 9
4 8
3 9
Determinant of 2x 2 matrix : 12

C code for Determinant of 3X3 matrix:

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
long determinant;
clrscr();
printf("Enter the 9 elements of matrix: ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("\nThe matrix is\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
30
24CSE401 - UNIT III

determinant = a[0][0]*((a[1][1]*a[2][2]) - (a[2][1]*a[1][2])) -a[0][1]*(a[1][0]*a[2][2] -


a[2][0]*a[1][2]) + a[0][2]*(a[1][0]*a[2][1] - a[2][0]*a[1][1]);
printf("\n Determinant of 3X3 matrix: %ld", determinant);
getch();
}
Output:
Enter the 9 elements of matrix: 1 2 3 4 5 6 7 8 9
1 2 3
4 5 6
7 8 9
Determinant of 3X3 matrix:0

Example: Matrix Transpose


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j,m,n;
clrscr();
printf("How many rows");
scanf("%d",&n);
printf("How many columns");
scanf("%d",&m);
printf("\nEnter the matrix:\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d",a[i][j]);
printf("\n");
}
printf("\nTranspose of given matrix:\n");
for(i=0;i<m;++i)
{
for(j=0;j<n;++j)
printf("%d ",a[j][i]);
printf("\n");
}
getch();
}

31
24CSE401 - UNIT III

Output:
How many rows 2
How many columns 2

Enter the matrix: 1 2 3 4


1 2
3 4
Transpose of given matrix:
1 3
2 4

3.Multidimensional array
A multidimensional array in simple terms is an array of arrays. Like we have one index in a
one-dimensional array, two indices in a two-dimensional array, in the same way we have n
indices in an n-dimensional array or multidimensional array. Conversely, an n-dimensional
array is specified using n indices. An n-dimensional m1 × m2 × m3 ×….. mn array is a
collection m1 * m2 * m3 *…… *mn ements. In a multidimensional array, a particular element is
specified by using n subscripts as A[I1] [I2] [I3]..... [In], where,

I1 <= M1 I2 <= M2 I3 <= M3 …….. In <= Mn

A multidimensional array can contain as many indices as needed and the requirement of the
memory increases with the number of indices used. However, practically speaking we will
hardly use more than three indices in any program. Figure 5.32 shows a three-dimensional
array. The array has three pages, four rows, and two columns.

A multidimensional array is declared and initialized similar to one- and two-dimensional


arrays.

32
24CSE401 - UNIT III

Example
Consider a three-dimensional array defined as int A[2][2][3]. Calculate the number of
elements in the array. Also show the memory representation of the array in row major order
and column major order.

Note
A three-dimensional array consists of pages. Each page in turn contains m rows and n
columns.

The three-dimensional array will contain 2 × 2 × 3 = 12 elements.

Example : Write a program to read and display a 2 × 2 × 2 array.

#include <stdio.h>
#include <conio.h>
int main()
{
int array [2] [2] [2], i, j, k;
clrscr();
printf("\n Enter the elements of the matrix");
for (i = 0; i < 2;i++)
{
for(j=0;j< 2;j++)
{
for (k=0; k < 2;k++)
scanf("%d", &array [i] [j] [k]);
}
}
}

33
24CSE401 - UNIT III

printf("\n The matrix is: ");


for (i=0; i < 2; i++)
{
printf("\n\n");
for(j=0;j< 2;j++) subs
{
printf("\n");
for (k=0; k < 2; k++)
printf("\tarray [%d] [%d] [%d] = %d", i, j, k], array[i][j] [k]);
}
}
getch();
return 0;
}

Output
Enter the elements of the matrix
12345678
The matrix is:
arr [0] [0] [0] = 1 arr [0] [0] [1] = 2
arr [0] [1] [0] = 3 arr [0] [1] [1] = 4
arr [1] [0] [0] = 5 arr [1] [0] [1] = 6
arr [1] [1] [0] = 7 arr [1] [1] [1] = 8

34

You might also like