0% found this document useful (0 votes)
3 views

Programming in C (1)

Uploaded by

Gizmo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Programming in C (1)

Uploaded by

Gizmo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 75

C is a general-purpose, high-

Programming in C level language that was


originally developed by
Dennis M. Ritchie in 1972.
My first ‘C’ Program
•The first line of the program #include <stdio.h> is a
preprocessor command, which tells a C compiler to
include stdio.h file before going to actual compilation.

•The next line int main() is the main function where the
program execution begins.

•The next line /*...*/ will be ignored by the compiler and it


has been put to add additional comments in the program.
So such lines are called comments in the program.

•The next line printf(...) is another function available in C


which causes the message "Hello, World!" to be displayed
on the screen.

•The next line return 0; terminates the main() function and


returns the value 0.
Fundamental
Comments are like helping text in your C program and
they are ignored by the compiler. They start with /* and
terminate with the characters */

semicolon is a statement terminator.


That is, each individual statement
must be ended with a semicolon. It
indicates the end of one logical entity.

identifier is a name used to


identify a variable, function, or any
A line containing only other user-defined item. An
whitespace, possibly with a identifier starts with a letter A to Z,
comment, is known as a blank a to z, or an underscore '_'
line, and a C compiler totally followed by zero or more letters,
ignores it. underscores, and digits (0 to 9).
Keywords Data types
. Types & Description

1 Basic Types
auto else long switch They are arithmetic types and are further classified
into: (a) integer types and (b) floating-point types.
break enum register typedef
2 Enumerated types
case extern return union
They are again arithmetic types and they are used
char float short unsigned to define variables that can only assign certain
discrete integer values throughout the program.
const for signed void
continue goto sizeof volatile 3 The type void
The type specifier void indicates that no value is
default if static while available.
do int struct _Packed 4 Derived types
They include (a) Pointer types, (b) Array types, (c)
double Structure types, (d) Union types and (e) Function
types.
The following list shows the reserved words in C.
These reserved words may not be used as constants Data types in c refer to an extensive system used for
or variables or any other identifier names. declaring variables or functions of different types. The type of
a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
Char and Integer type Floating point type
Type Storage Value range
size
Type Storage Value Precision
size range
char 1 byte -128 to 127 or 0 to 255
unsigned 1 byte 0 to 255 float 4 byte 1.2E-38 to 6 decimal
char 3.4E+38 places
signed char 1 byte -128 to 127 double 8 byte 2.3E-308 to 15 decimal
1.7E+308 places
-32,768 to 32,767 or -
2 or 4 long double 10 byte 3.4E-4932 to 19 decimal
int 2,147,483,648 to
bytes 1.1E+4932 places
2,147,483,647
unsigned 2 or 4 0 to 65,535 or 0 to
int bytes 4,294,967,295
What are your findings?
short 2 bytes -32,768 to 32,767
unsigned 2 bytes 0 to 65,535
short
long 8 bytes -9223372036854775808 to
9223372036854775807
unsigned 8 bytes 0 to 18446744073709551615
long
Variable type
Sr.No. Type & Description

1 char
Typically a single octet(one byte). This A variable is nothing but a name given to a storage area
is an integer type. that our programs can manipulate. Each variable in C has
a specific type, which determines the size and layout of
2 int
the variable's memory; the range of values that can be
The most natural size of integer for the
stored within that memory; and the set of operations that
machine.
can be applied to the variable.
3 float
A single-precision floating point value. The name of a variable can be composed of letters, digits,
and the underscore character. It must begin with either a
4 double letter or an underscore. Upper and lowercase letters are
A double-precision floating point value.
distinct because C is case-sensitive. Based on the basic
5 void types explained in the previous chapter, there will be the
Represents the absence of type. following basic variable types −
String
Strings are actually one-dimensional array of
characters terminated by a null character '\0'.
Thus a null-terminated string contains the
characters that comprise the string followed by
a null.
The following declaration and initialization
create a string consisting of the word "Hello". To
hold the null character at the end of the array,
the size of the character array containing the
string is one more than the number of
characters in the word "Hello.“

Actually, you do not place the null character at


the end of a string constant. The C compiler
automatically places the '\0' at the end of the
string when it initializes the array.

What is the output of the program?


String functions
Sr.No. Function & Purpose

1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of
string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less
than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);
Returns a pointer to the first occurrence of
character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of
string s2 in string s1.

Output =
String input

You can use the scanf() function to read a string. You can use gets() function to read a line of
The scanf() function reads the sequence of characters string. And, you can use puts() to display the
until it encounters a whitespace (space, newline, tab string.
etc.). Even though Dennis Ritchie was entered in the
above program, only "Ritchie" was stored in the name
string. It's because there was a space after Ritche
String input

VS

Suppose we have a character array of 15 characters and


Let’s say the maximum number of characters are N input is greater than 15 characters, gets() will read all these
and input length is greater than N but still fgets() will characters and store them into variable.Since, gets() do not
read only N-1 character and print it. check the maximum limit of input characters, so at any time
compiler may return buffer overflow error.
Data Types Modifiers
Arithmetic operators Relational operators
Operator Description Example Operator Description Example
== Checks if the values of two operands are (A == B) is not true.
+ Adds two operands. A + B = 30 equal or not. If yes, then the condition
− Subtracts second A − B = -10 becomes true.
operand from the first. != Checks if the values of two operands are (A != B) is true.
equal or not. If the values are not equal,
* Multiplies both A * B = 200
then the condition becomes true.
operands.
> Checks if the value of left operand is (A > B) is not true.
/ Divides numerator by B/A=2
greater than the value of right operand. If
de-numerator.
yes, then the condition becomes true.
% Modulus Operator and B%A=0
< Checks if the value of left operand is less (A < B) is true.
remainder of after an
than the value of right operand. If yes,
integer division.
then the condition becomes true.
++ Increment operator A++ = 11 >= Checks if the value of left operand is (A >= B) is not true.
increases the integer greater than or equal to the value of right
value by one. operand. If yes, then the condition
-- Decrement operator A-- = 9 becomes true.
decreases the integer <= Checks if the value of left operand is less (A <= B) is true.
value by one. than or equal to the value of right operand.
If yes, then the condition becomes true.
Logical operators Bitwise operators
Operator Description Example Operator Description Example
& Binary AND Operator copies a (A & B) = 12, i.e.,
&& Called Logical AND operator. If (A && B) is false. bit to the result if it exists in 0000 1100
both the operands are non- both operands.
zero, then the condition
becomes true. | Binary OR Operator copies a (A | B) = 61, i.e.,
bit if it exists in either operand. 0011 1101
|| Called Logical OR Operator. If (A || B) is true.
any of the two operands is non- ^ Binary XOR Operator copies (A ^ B) = 49, i.e.,
zero, then the condition the bit if it is set in one 0011 0001
becomes true. operand but not both.

! Called Logical NOT Operator. It !(A && B) is true.


is used to reverse the logical Assume A = 60 and B = 13 in binary format, they will be
state of its operand. If a as follows −
condition is true, then Logical A = 0011 1100
NOT operator will make it false. B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
Assignment operators
Operator Description Example
%= Modulus AND assignment
operator. It takes modulus C %= A is
using two operands and equivalent to C
assigns the result to the =C%A
left operand.
<<= Left shift AND assignment C <<= 2 is
operator. same as C = C
<< 2
>>= Right shift AND C >>= 2 is
assignment operator. same as C = C
>> 2
&= Bitwise AND assignment C &= 2 is same
operator. as C = C & 2
^= Bitwise exclusive OR and C ^= 2 is same
assignment operator. as C = C ^ 2
|= Bitwise inclusive OR and C |= 2 is same
assignment operator. as C = C | 2
Bitwise operators Bitwise shift operators
Decision making
Decision making structures require that the programmer specifies one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.

Sr.No. Statement & Description


1 if statement An if statement consists of a boolean expression
followed by one or more statements.
2 if...else statement An if statement can be followed by an
optional else statement, which executes when the Boolean
expression is false.

3 nested if statements You can use one if or else if statement


inside another if or else if statement(s).
4 switch statement A switch statement allows a variable to be
tested for equality against a list of values.

5 nested switch statements You can use one switch statement


inside another switch statement(s).
If - selection
If … else selection
If … else ladder

Can you
follow the
lesson so
far?
Nested if

Can you spot the


difference between this
program with the
previous?
What is a Switch
Statement?
Switch statement tests the value
of a variable and compares it with
multiple cases. Once the case
match is found, a block of
statements associated with that
particular case is executed.

Each case in a block of a switch


has a different name/number
which is referred to as an
identifier. The value provided by
the user is compared with all the
cases inside the switch block until
the match is found.

If a case match is NOT found, then


the default statement is executed,
and the control goes out of the
switch block.
Example1 Example2
Example3
If you are checking on the value of
a single variable in if…else…if,
then is better to use the switch
statement
Loops A loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement in most of the programming
languages −

Sr.No. Loop Type & Description Sr.No. Control Statement &


Description
1 while loop Repeats a statement or group
of statements while a given condition is 1 break statement Terminates
true. It tests the condition before the loop or switch statement
executing the loop body. and transfers execution to the
statement immediately
2 for loop Executes a sequence of following the loop or switch.
statements multiple times and abbreviates
the code that manages the loop variable.
2 continue statement Causes
the loop to skip the remainder
3 do...while loop It is more like a while of its body and immediately
statement, except that it tests the retest its condition prior to
condition at the end of the loop body. reiterating.

4 nested loops You can use one or more 3 goto statement Transfers
loops inside any other while, for, or control to the labeled
do..while loop. statement.
How for loop works?
When you need to execute a block of code several number of
times then you need to use looping concept in C language. In C
Programming Language for loop is a statement which allows
code to be repeatedly executed. It contains 3 parts.

for loop in C language is used to iterate the statements or a part


of the program several times. •Initialization: This step is execute first and
•Initialization this is execute only once when we are
•Condition entering into the loop first time. This step is
•Increment or Decrements allow to declare and initialize any loop control
variables.

•Condition: This is next step after


initialization step, if it is true, the body of the
loop is executed, if it is false then the body of
the loop does not execute and flow of control
goes outside of the for loop.

•Increment or Decrements: After


completion of Initialization and Condition
steps loop body code is executed and then
Increment or Decrements steps is execute.
This statement allows to update any loop
How for loop works? Then, the test expression is evaluated. If the test expression is false
The initialization statement is (0), for loop is terminated. But if the test expression is true
executed only once. (nonzero), codes inside the body of for loop is executed and the
update expression is updated.
A program asking #include <stdio.h>
#include <stdio.h> user to input #include <string.h>
int main() password, maximum
{ try is 3 times int main()
int password=2468; { char password[10]="3sheeps";
int pass,c; char attempt[10];
for (c=1; c<=3; c++ ) printf("enter password:\n");
{ for(int a=1;a<=3;a++)
printf("Enter password(Try %d)\n: ",c); {
scanf("%d",&pass); scanf("%s", attempt);
if(pass==password) if( strcmp( attempt, password)==0)
{ c=3;} { printf("logged in\n");
else if(c<3) break; }
{printf("Try again\n"); } if(strcmp(attempt, password)!=0)
} { if(a<=2)
if (pass==password) { printf("try again\n"); }
{printf("Login success\n");} else
else printf("no attempts left"); }
{printf("Login failed");} }
return 0; return 0;
} }
In the above example we have a for loop inside
another for loop, this is called nesting of loops.
One of the example where we use nested for
loop is Two dimensional array.

What’s the difference between above for


loop and a simple for loop?
1. It is initializing two variables. Note: both are separated by
comma (,).
2. It has two test conditions joined together using AND (&&)
logical operator. Note: You cannot use multiple test
conditions separated by comma, you must use logical
operator such as && or || to join conditions.
3. It has two variables in increment part. Note: Should be
separated by comma.
Example
How while loop works?
In while loop First check the condition if condition is true then
control goes inside the loop body other wise goes outside the
body. while loop will be repeats in clock wise direction

Here, statement(s) may be a single statement


or a block of statements. The condition may be
any expression, and true is any nonzero value.
The loop iterates while the condition is true.
When the condition becomes false, the
program control passes to the line immediately
following the loop
How while loop works?
The while loop evaluates the test expression.

If the test expression is true (nonzero),


codes inside the body of while loop are
executed. The test expression is
evaluated again. The process goes on
until the test expression is false.
When the test expression is false, the
while loop is terminated.
Example Example
How do … while loop works?

A do while loop is a control flow statement that


executes a block of code at least once, and then
repeatedly executes the block, or not, depending
on a given condition at the end of the block (in
while).
when we need to repeat the statement block at least one
time then use do-while loop. In do-while loop post-
checking process will be occur, that is after execution of
the statement block condition part will be executed.
How do...while loop works?

The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is evaluated to 0
(false). When the test expression is false (nonzero), the do…while loop is terminated.
Example
1.First, we have initialized a variable 'num' with
value 1. Then we have written a do-while loop.

2.In a loop, we have a print function that will


print the series by multiplying the value of num
with 2.

3.After each increment, the value of num will


increase by 1, and it will be printed on the
screen.

4.Initially, the value of num is 1. In a body of a


loop, the print function will be executed in this
way: 2*num where num=1, then 2*1=2 hence
the value two will be printed. This will go on
until the value of num becomes 10. After that
loop will be terminated and a statement which
is immediately after the loop will be executed.
In this case return 0.
break Statement
The break statement terminates the loop

It is sometimes
desirable to skip some
statements inside the
loop or terminate the
loop immediately
without checking the
test expression.
Function How to define a function?
A function is a group of statements that A function definition in C programming consists of a function
together perform a task. Every C program header and a function body. Here are all the parts of a function −
has at least one function, which is main(),
•Return Type − A function may return a value. The return_type is
and all the most trivial programs can define
the data type of the value the function returns. Some functions
additional functions. perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
You can divide up your code into separate
functions. How you divide up your code •Function Name − This is the actual name of the function. The
among different functions is up to you, but function name and the parameter list together constitute the
logically the division is such that each function signature.
function performs a specific task.
•Parameter − A parameter is like a placeholder. When a function
is invoked, you pass a value to the parameter. This value is
A function declaration tells the compiler referred to as actual parameter or argument. The parameter list
about a function's name, return type, and refers to the type, order, and number of the parameters of a
parameters. A function definition provides function. Parameters are optional; that is, a function may contain
the actual body of the function. no parameters.

•Function Body − The function body contains a collection of


statements that define what the function does.
Function prototype
A function prototype is simply the declaration of a
function that specifies function's name,
parameters and return type. It doesn't contain
function body. A function prototype gives
information to the compiler that the function may
later be used in the program.

Function definition
Function definition contains the block of code to
perform a specific task i.e. in this case, adding
two numbers and returning it.
Passing argument to function Return value

The return statement


terminates the
execution of a function
and returns a value to
the calling function. The
program control is
transferred to the
calling function after
return statement.
Types of function
Function with no argument and no return value
Function with no argument and a return value
Function with argument with no return value
Function with argument with return value
Conversion of data types using function
Type casting refers to changing an variable of one
data type into another. The compiler will
automatically change one type of data into
another if it makes sense. For instance, if you
assign an integer value to a floating-point variable,
the compiler will convert the int to a float. Casting
allows you to make this type conversion explicit, or
to force it when it wouldn’t normally happen.
When the type conversion is performed
automatically by the compiler without
programmers intervention, such type of conversion
is known as implicit type conversion or type
promotion. The type conversion performed by
the programmer by posing the
data type of the expression of
specific type is known as explicit
type conversion. The explicit type
conversion is also known as type
casting.
1. Implicit Type Conversion
When the type conversion is performed
automatically by the compiler without
programmers intervention, such type of conversion
is known as implicit type conversion or type
promotion. 2. Explicit Type Conversion
The type conversion performed by the programmer
by posing the data type of the expression of
specific type is known as explicit type conversion.
The explicit type conversion is also known as type
casting.

The following rules have to be followed


while converting the expression from one
type to another to avoid the loss of
information:

1.All integer types to be converted to float.


2.All float types to be converted to double.
3.All character types to be converted to
Variable Scope
Variable scope means the visibility of variables
within a code of the program.

In C, variables which are declared inside a


function are local to that block of code and
cannot be referred to outside the function. • We declare an integer global variable with
However, variables which are declared outside all 1348 as initial value.
functions are global and accessible from the • We declare and define a test() function which
entire program neither takes arguments nor returns a value.
Global variable
This function only prints the global variable
value to demonstrate that the global variables
can be accessed anywhere in the program.
• We print the global variable within the main
function.
• We call the test function in order to print the
global variable value
The static variables have a local scope. However, they
are not destroyed when exiting the function. Therefore,
a static variable retains its value forever and can be
accessed when the function is re-entered. A static
variable is initialized when declared and needs the
prefix static.

Local variable

Static variable
A function's arguments are used to receive the
necessary values by the function call. They are
matched by position; the first argument is passed to
the first parameter, the second to the second
parameter and so on.

By default, the arguments are passed by value in


which a copy of data is given to the called function.
The actually passed variable will not change.
We consider the following program which
demonstrates parameters passed by value:

Pass by value

Pass by value
Pass by reference
#include <stdio.h>
void swap(int *x, int *y);

int main () {

int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

swap(&a, &b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0; }

void swap(int *x, int *y)


{
int temp;
temp = *x;
*x = *y;
*y = temp;
Pass by reference }
Pass by value Pass by reference
Pass by value means that a copy of the actual Pass by reference (also called pass by address) means
parameter’s value is made in memory, i.e. the caller to pass the reference of an argument in the calling
and callee have two independent variables with the function to the corresponding formal parameter of the
same value. If the callee modifies the parameter called function so that a copy of the address of the
value, the effect is not visible to the caller. actual parameter is made in memory, i.e. the caller and
the callee use the same variable for the parameter. If the
Overview: callee modifies the parameter variable, the effect is
visible to the caller’s variable.
• Passes an argument by value.
• Callee does not have any access to the Overview:
underlying element in the calling code.
• A copy of the data is sent to the callee. • Passes an argument by reference.
• Changes made to the passed variable do not • Callee gives a direct reference to the programming
affect the actual value. element in the calling code.
• The memory address of the stored data is passed.
• Changes to the value have an effect on the original
data.
Factorial of a number
The factorial of a positive number n is given by:
factorial of n (n!) = 1*2*3*4....n
Factorial using recursive function
How recursion works? • In the above example program,
the factorial() function call is initiated from
main() function with the value 3.

• Inside the factorial() function, the function calls


factorial(2), factorial(1) and factorial(0) are
called recursively.

• In this program execution process, the function


call factorial(3) remains under execution till the
execution of function calls factorial(2),
factorial(1) and factorial(0) gets completed.

• Similarly the function call factorial(2) remains


under execution till the execution of function
calls factorial(1) and factorial(0) gets completed.

• In the same way the function call factorial(1)


remains under execution till the execution of
function call factorial(0) gets completed.

• The complete execution process of the above


program is shown in the following figure.
Array Declaring array
Arrays a kind of data structure that can store a fixed-size
sequential collection of elements of the same type. An
array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables
This is called a single-dimensional array.
of the same type.
The arraySize must be an integer constant greater than
zero and type can be any valid C data
Instead of declaring individual variables, such as
number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0],
Initializing array
numbers[1], and ..., numbers[99] to represent individual
variables. A specific element in an array is accessed by an
index.
All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the
highest address to the last element.
Accessing array elements

The above statement will take the 10th element


from the array and assign the value to salary
variable.
The following example Shows how to use all the three
above mentioned concepts viz. declaration, assignment,
and accessing arrays
The following example Shows how to use all the three
above mentioned concepts viz. declaration, assignment,
and accessing arrays
Sorting of Array (bubble sort)

#include<stdio.h>
int main() printf("\nData after sorting: ");
{
int i,a[10],temp,j; for(j=0;j<10;j++)
{ printf(" %d", a[j]); }
printf("Enter any 10 num in array: \n"); return 0;
}
for(i=0;i<10;i++)
{ scanf("%d",&a[i]);
}
printf("\nData before sorting: ");

for(j=0;j<10;j++)
{ printf(" %d",a[j]); }

for(i=0;i<10-1;i++)
{ for(j=0;j<10-i-1;j++)
{ if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp; } } }
Sorting of Array (bubble sort)

Bubble sort is the simplest sorting algorithm. In this


technique we follow given step to short given elements in
increasing order.

Steps to Sort data


•First compare First (previous) element with its next
elements.
•If next element is grater than previous element just ignore it.
•If next element is smaller than previous element then
interchange their position.

Advantage of Bubble short


It is very simple and easy method to short elements.

Dis-Advantage of Bubble short


It is time consuming and slow process to short elements.
Sorting with Array (selection sort)

#include<stdio.h> if (position!=c)
{
int main() swap=array[c];
{ int array[100], n, c, d, position, swap; array[c]=array[position];
array[position]=swap; } }
printf("How many elements you want to
enter: "); printf("Sorted list in ascending
scanf("%d", &n); order:\n");
printf("Enter any %d elements: \n", n);
for (c=0; c<n; c++)
for (c=0; c<n; c++) { printf("%d ", array[c]); }
{ scanf("%d", &array[c]); } return 0;
}
for (c=0; c<(n-1); c++)
{ position=c;
for (d=c+1; d<n; d++)
{ if (array[position]>array[d])
{ position=d; } }
Sorting with Array (selection sort)

Selection sort is based of maximum and minimum value. First check


minimum value in array list and place it at first position (position 0) of
array, next find second smallest element in array list and place this value
at second position (position 1) and so on. Same process is repeated until
sort all element of an array.

•Find the minimum element in the list.


•Swap it with the element in the first position of the list.
•Repeat the steps above for all remaining elements of the list starting from
the second position.

Advantage of this sorting technique


It performs well on small lists.

Dis-Advantage of this sorting technique


poor efficiency when dealing with a huge list of
items.
Sorting with Array (insertion sort)

#include<stdio.h>
int main() printf("After Sorting elements: ");
{ int i, j, num, temp, arr[20]; for(i=0; i<num; i++)
{ printf("%d ", arr[i]); }
printf("Enter size of array: "); return 0;
scanf("%d", &num); }

printf("Enter %d elements in arry: \n", num);

for(i=0; i<num; i++)


{ scanf("%d", &arr[i]); }

for(i=1; i<num; i++)


{ temp=arr[i];
j=i-1;
while((temp<arr[j])&&(j>=0))
{ arr[j+1]=arr[j];
j=j-1; }
arr[j+1]=temp;
}
Sorting with Array (insertion sort)

Insertion Sort is a simplest data Sorting algorithm which


sorts the array elements by shifting elements one by one
and inserting each element into its proper position. This
technique is also used for sort array elements. With the
help of below animated image you can easily understand
and you can also see real life example in second image.

Advantage of this sorting technique


It is a simple data Sorting algorithm. It is
also better than Selection Sort and Bubble
Sort algorithms.
Dis-Advantage of this sorting technique
This sorting technique is slower than quick
sort sorting algorithm.
2D Array
Matrix calculation using 2D array
Matrix calculation using 2D array
#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k; for(i=0;i<m;++i)
printf("Enter rows and columns of first matrix:"); {
scanf("%d%d",&m,&n); for(j=0;j<q;++j)
printf("Enter rows and columns of second {
matrix:"); c[ i ][ j ]=0;
scanf("%d%d",&p,&q); for(k=0;k<n;++k)
c[ i ][ j ]=c[ i ][ j ]+(a[ i ][ k ]*b[ k ][
if(n==p) j ]);
{ printf("%d ",c[ i ][ j ]);
printf("\nEnter first matrix:\n"); }
for(i=0;i<m;++i) printf("\
for(j=0;j<n;++j) n"); }}
scanf("%d",&a[ i ][ j ]); else
printf("\nSorry!!!! Matrix multiplication can't be
printf("\nEnter second matrix:\n"); done");

for(i=0;i<p;++i) return 0;
for(j=0;j<q;++j) }
scanf("%d",&b[ i ][ j ]);

printf("\nThe new matrix is:\n");


Matrix calculation using 2D array
Passing array to functions

To pass multidimensional arrays to a function,


only the name of the array is passed to the
function(similar to one-dimensional arrays).
Multi-Dimensioanl Array
In Example 1:
In C programming an array can have two, three, or •int designates the array type integer.
even ten or more dimensions. The maximum •table is the name of our 3D array.
dimensions a C program can have depends on •Our array can hold 500 integer-type
which compiler is being used. elements. This number is reached by
More dimensions in an array means more data be multiplying the value of each dimension. In
held, but also means greater difficulty in managing this case: 5x5x20=500.
and understanding arrays.
In Example 2:
•Array arr is a five-dimensional array.
How to Declare a Multidimensional Array in C •It can hold 4500 floating-point elements
A multidimensional array is declared using the (5x6x5x6x5=4500).
following syntax: .
type array_name[d1][d2][d3][d4]………[dn];

Where each d is a dimension, and dn is the size of


final dimension.

Examples:
1.int table[5][5][20];
2.float arr[5][6][5][6][5];
Multi-Dimensional Array

If you want to store


values in any 3D array
point first to table
number, then row
number, and lastly to
column number.
Some hypothetical
examples:

arr[0][1][2] = 32;
arr[1][0][1] = 49;
Multi-Dimensional Array

*if you want to store values in


multiple locations
automataically then you
should use a loop.
Multi-Dimensional Array

You might also like