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

Unit3 arraysNEP

This document provides an overview of arrays, strings, and functions in C programming. It discusses single and multi-dimensional arrays, how to declare, initialize, and access array elements. It also covers character arrays and strings, noting that strings must be null-terminated. Functions for input and output of arrays and strings are presented, including scanf(), printf(), gets(), and puts(). Examples of programs that work with arrays to store and process data are provided, such as adding matrices and finding the average of student marks.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Unit3 arraysNEP

This document provides an overview of arrays, strings, and functions in C programming. It discusses single and multi-dimensional arrays, how to declare, initialize, and access array elements. It also covers character arrays and strings, noting that strings must be null-terminated. Functions for input and output of arrays and strings are presented, including scanf(), printf(), gets(), and puts(). Examples of programs that work with arrays to store and process data are provided, such as adding matrices and finding the average of student marks.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

UNIT-3

Arrays, Strings and Functions

Arrays:
Introduction
An Array is a fixed-size sequenced collection of elements of the same data type. It is
one of the derived data types in C. The elements are referred to by a number called
index or subscript.
A list of items given one variable name using only one subscript is called a single
subscripted variable or one dimensional array. Array elements are stored in
consecutive memory locations. The general form of array declaration is,
datatype variable_name [size];
Type specifies the data type, size specifies the maximum number of elements that can
be stored in the array.
e.g. int group [10];
The C language treats strings as array of characters. Character strings are terminated
by a null character ‘\0’
e.g. char name [5]={‘R’,’a’,’m’,’a’,’\0’};
After an array is declared its elements must be initialized. An array can be initialized
in 2 ways,
 At compile time
 At run time
The general form of initializing an array during declaration is,
datatype array_name [size] = {list of values};
e.g. int x [3] = {5, 7, 9};
Character array can be initialized as,
e.g. char name [] = {‘J’, ‘o’, ‘h’, ‘n’, ‘\0’};   or char name []=”John”;
The values to the array elements can be assigned as follows:
int x [10];
x [0] =35; x [2] = 13;
x [1] = 20; x[3] = 19;
Program to accept n integers and store them in an array and print them.
#include<stdio.h>
int main()
{
int n, i, num[20];
printf(“Enter the size of an array\n”);
scanf(“%d”, &n);
printf(“Enter elements of the array\n”);
for(i=0; i<n; i++)
scanf(“%d”, &num[i]);
printf(“Array list is\n”);
for(i=0; i<n; i++)
printf(“num [%d] =%d\n”, I, num[i]);
return 0;
}
Program to read marks scored by n students and find the average of
marks(Demonstration of single dimensional array)
#include<stdio.h>
int main()
{
int n,i,mark[100],sum=0;
float average;
printf("Enter the number of students\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the total marks for student %d:",i+1);
scanf("%d",&mark[i]);
sum=sum+mark[i];
}
average=sum/n;
printf("\nAverage mark of all the students=%f\n",average);
return 0;
}
Two dimensional Array:
Two dimensional array is used to represent elements in a table with rows and columns,
provided each element  is of the same type. Each array element is accessed by a pair of
indices that represents the elements position in each dimension.
Two dimensional array is declared as follows:
Datatype array_name [row_size] [col_size];
e.g. int a[3] [3]
Two dimensional array can be initialized as follows:
1. Row by Row method:
e.g. int table [2] [3] = {0, 0, 0, 1, 1, 1};
2. Matrix form:
e.g. int table [2] [3] = {{0, 0, 0},{1, 1, 1}};
Program to read and display square Matrix 
#include <stdio.h>
int main()
{
    int a[10][10];
    int n,i,j;
    printf("Enter the order of matrix\n");
    scanf("%d",&n);
    printf("Enter matrix elements\n");
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    printf("Matrix A\n");
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("%d\t",a[i][j]);
        }
        printf("\n");
    }
    return 0;
}
Program to add and subtract 2 M*N matrix

#include <stdio.h>
int main()
{
    int n, i, j, a[10][10], b[10][10], c[10][10], d[10][10];
    printf("Enter the order of the matrix\n");
    scanf("%d",&n);
    printf("Enter %d elements of matrix A\n", n*n);
    for(i=0;i<n;i++)
    {
       for(j=0;j<n;j++)
       {
           scanf("%d", &a[i][j]);
       }
    }
    printf("Enter %d elements of matrix B\n",n*n);
    for(i=0;i<n;i++)
    {
       for(j=0;j<n;j++)
       {
           scanf("%d", &b[i][j]);
       }
    }
    for(i=0;i<n;i++)
    {
      for(j=0;j<n;j++)
       {
           c[i][j]=a[i][j]+b[i][j];
           d[i][j]=a[i][j]-b[i][j];
       }
    }
    printf("Matrix A\n");
    for(i=0;i<n;i++)
    {
       for(j=0;j<n;j++)
       {
           printf("%4d",a[i][j]);
       }
       printf("\n");
    }
    printf("Matrix B\n");
    for(i=0;i<n;i++)
    {
       for(j=0;j<n;j++)
       {
           printf("%4d",b[i][j]);
       }
       printf("\n");
    }
    printf("Matrix C\n");
    for(i=0;i<n;i++)
    {
       for(j=0;j<n;j++)
       {
           printf("%4d",c[i][j]);
       }
       printf("\n");
    }
    printf("Matrix D\n");
    for(i=0;i<n;i++)
    {
       for(j=0;j<n;j++)
       {
           printf("%4d",d[i][j]);
       }
       printf("\n");
    }
    return 0;
}
 Program to multiply 2 matrices of different order

#include <stdio.h>
int main()
{
    int n,i,j,k,r1,c1,r2,c2,a[10][10],b[10][10],c[10][10];
    printf("Enter the order of the matrixA\n");
    scanf("%d%d",&r1,&c1);
    printf("Enter the order of the matrixB\n");
    scanf("%d%d",&r2,&c2);
    if(c1==r2)
    {
    printf("Enter %d X %d elements of matrix A\n",r1,c1);
    for(i=0;i<r1;i++)
    {
       for(j=0;j<c1;j++)
       {
           scanf("%d", &a[i][j]);
       }
    }
    printf("Enter %d X%d elements of matrix B\n",r2,c2);
    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<r2;k++)
              c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
       }
    }
    printf("Matrix A\n");
    for(i=0;i<r1;i++)
    {
       for(j=0;j<c1;j++)
       {
           printf("%4d",a[i][j]);
       }
       printf("\n");
    }
    printf("Matrix B\n");
    for(i=0;i<r2;i++)
    {
       for(j=0;j<c2;j++)
       {
           printf("%4d",b[i][j]);
       }
       printf("\n");
    }
    printf("Matrix C\n");
    for(i=0;i<r1;i++)
    {
       for(j=0;j<c2;j++)
       {
           printf("%4d",c[i][j]);
       }
       printf("\n");
    }
    }
    else
        printf("Multiplication not possible\n");
     return 0;
}
Program to read, display and to find the trace of a square matrix
#include <stdio.h>
int main()
{
int n,i,j,a[10][10];
float trace=0;
printf("Enter the order of the square matrix\n");
scanf("%d",&n);
printf("Enter %d elements of matrix A\n",n*n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Matrix A\
n"); for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%4d",a[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
{
trace=trace+a[i][j];
}
}
}
printf("Trace=%f\n",trace);
return 0;
}

Character Array and Strings:


A string is a sequence of characters that is treated as a single data item. In ‘C’, an
array of characters is called a string.
Declaration of a string:
char stringName [size];
e.g. char city [10];
Initialization:
e.g. 1. char city [9] = “New York”;
        2. char city [9] = {‘N’, ”e’, ’w’, ’y’, ’o’, ’r’, ’k’};
NOTE: 1. String always ends with a null character.
             2. We can initialize a character Array without specifying the size.
              e.g.  char city[]={‘L’, ‘O’, ‘N’, ‘D’, ‘O’, ‘N’};
Reading and writing string from terminal
The function scanf can be used with %s formed specification to read in a string of
character.
e.g. char add[10];
       scanf (“%s”, add);
NOTE: The scanf function terminates its input on the first white space it finds.
‘&’ is not used for string in scanf() function because
 ‘&’ is used to get the address of the variable. C does not have a string type.
String is an array of characters and an array variable stores the address of the
index location.
 By default the variable itself points to the base address and therefore to access
base address of the string there is no need of adding an extra &.
We also use the library function ‘gets()’ to read a string of text containing white
spaces. ‘gets()’ function takes string variable as a parameter.
e.g. char buf[20];
       gets(buf);
       printf (“%s”, buf);
printf function with %s format is used to print strings to the screen.
puts()
‘puts()’ is a function which can also be used to print a string.
e.g. char line[20];
       gets(line);
       puts(line);
Program to accept a string and reverse it:
#include<stdio.h>
int main()
{
char string[25], revstr[25];
int nchars, count;
printf(“Enter the no of characters in the string\n”);
scanf(“%d”, &nchars);
printf(“Enter the string of %d characters\n”,nchars);
scanf(%s”, string);count=nchar-1;
for(i=count; i>=0;i--)
revstr[count-i]=string[i];
revstr[nchars]=’\0’;
printf(“Input string=%s\n”, string);
printf(“Reverse string = %s \n”, revstr);
return 0;
}
Note: gets() function can be used in place of scanf() to read a string in the
above program. But if gets() is used after scanf() reads an integer the problem
is , scanf() reads an integer and leaves a newline character in the buffer so
gets() only reads newline and ignores the string hence we need to use
flush(stdin) after scanf() to flush the buffer and then use gats() to read a string.

Program to find the length of a string without using built in function


#include <stdio.h>
int main()
{
char
str[100]; int
i,len=0;
printf("Enter the string\
n"); scanf("%s",str);

for(i=0;str[i]!='\0';i+
+) len++;

printf("Length of a string: %d\n",len);

return 0;
}

String Handling functions:


C library supports a large number of string handling functions that can be used to
carry out many of the string manipulations.
Functions Actions
strcat() Concatenates two strings
strcmp() Compare two strings
strcpy() Copies one string over another
strlen() Finds the length of a string
1. strcat () function:
The strcat() function joins 2 strings together. The syntax is,
strcat (string1, string2)
Here string2 is appended to string1. The string at string2 remains unchanged.
strcat() function may also append a string constant to a string variable.
strcat (“part1”,”GOOD”)
C permits nesting of strcat functions
strcat(strcat(string1,string2),string3);

2. strcmp() function:
The strcmp() function compares two strings and returns 0 if they are equal.
The syntax is,
                      strcmp( string1, string2);
string1 and string2 may be string variables or string constants.
e.g. strcmp (“their”,”there”);
Will return -9 which is numeric difference between ASCII ‘i’ and ASCII ‘r’. If
the value is negative string1 is alphabetically above string2.
3. strcpy() function:
The syntax is,
                      strcpy( string1, string2);
The contents of string2 is assigned to string1. String2 may be an character
array variable or a string constant. 
e.g. 1. strcpy (city,”Delhi”); will assign Delhi to string variable city.
       2. strcpy (city1,city2);  will assign the contents of string variable city2 to
string variable city1.
4. strlen() function: 
This function counts and returns the number of characters in a string.
The syntax is,
                       n=strlen(string);
where n is an integer variable.

Program to demonstrate string functions.


#include<stdio.h>
#include<string.h>
int main()
{
char s1[20],s2[20],s3[20];
int x,len;
printf("Enter 2 strings\n");
scanf("%s
%s",s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf("Strings are not equal\n");
}
else
{
printf("Strings are equal\n");
}
strcat(s1,s2);
printf("The concatenation of string s1 and s2 is=%s\n",s1);
strcpy(s3,s2);
printf("The copied string s3 from s2 is=%s\n",s2);
len=strlen(s1);
printf("s1=%s\t and length=%d\
n",s1,len);
return 0;
}

POINTERS
Pointers are variables that contain an address of another variable in memory. The
address of a variable can be accessed by using the operator ‘&’ immediately
preceding a variable.
E.g. p=&x;
Advantages of pointers:
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function through
function arguments.
3. Pointers allow C to support dynamic memory management.
4. Pointers reduce length and complexity of programs.
5. The use of pointer arrays to character strings results in saving of data storage
space in memory.
6. They increase the execution speed and thus reduce the program execution
time.
Declaring and initializing pointers:
The declaration of a pointer variable takes the following form:
Datatype *pt_name;
Where the asterisk (*) tells that the variable pt_name is a pointer variable.
 pt_name needs a memory location
 pt_name points to a variable of type datatype of that variable. E.g. int *p;
Declares the variable ‘p’ as a pointer variable that points to an integer data
type. p=&quantity;
cause pointer ‘p’ to point to quantity. i.e, ‘p’ contains the address of quantity.
A pointer variable can be initialized in its declaration itself.
E.g. int x,*p=&x;
      ⇒ int x;
         int *p;
        p=&x;
NOTE: 1. The initialization is of ‘p’ and not *p
        2. The target variable ‘x’ should be declared first then the pointer.
             E.g. int *p=&x, x; is not valid.
Accessing a variable through its pointer
The value of the variable can be accessed using unary operator * , known as
indirection operation.
E.g. int quantity, n;
       int *p;
       p=&quantity;
       n = *p;
NOTE: ‘*’ means value at address
              n=*p is equivalent to n=*&quantity. Which is equivalent to
n=quantity.

Program to demonstrate pointers in C.


#include<stdio.h>
int main()
{
   int x, y;
 int *ptr;
 x=10;
ptr=&x;
y=*ptr;
printf(“value of x=%d\n”, x);
printf(“%d is stored at address %u\n”, x, &x);
printf(“%d is stored at address %u\n”, *&x, &x);
printf(“%d is stored at address %u\n”,*ptr, ptr);
printf(“%d is stored at address %u\n”, y, &*ptr);
printf(“%u is stored at address %u\n”, ptr, &ptr);
printf(“%d is stored at address %u\n”, y, &y);
*ptr=25;
printf(“\n Now x= %d\n”,x);
return 0;
}
Note: *ptr=25 assigns 25 at the memory location whose address is the value of ptr.
Pointer expression:
Like other variables, pointer variables can be used in expressions.
E.g. If p1 and p2 are pointer variables, then the following statements are valid.
E.g. y = (*p1)*(*p2);
       sum =sum+(*p1);
      *p2=*p2+10;
      z=(5*(-(*p2)))/*p1;
C allows to add integers to or subtract integers from pointers.
It also allows to subtract or add one pointer from another.
E.g. p1=p1+1;
   p1++;
This will cause pointer p1 to point to the next value of its type.
If p1 is an integer pointer with an initial value say 2800 then p1=p1+1, then p1 will
be 2802 after the operation.
That is when we increment a pointer, its value is increased by the length of the data
type that it points to. This length is called the scale factor.
Program to illustrate pointer in expression
#include<stdio.h>
int main()
{
   int a , b, *p1, *p2, x, y, z;
  a=12;
  b=4;
  p1=&a;
  p2=%b;
  x=*p1 * *p2 - 6;
  y= 4 * - *p2/*p1 + 10;
 printf(“Address of a = %u\n”, p1);
 printf(“Address of b=%u\n”, p2);
 printf(“\n”);
 printf(“a=%d, b=%d”, a, b);
 printf(“x=%d\n, y=%d\n”, x, y);
 *p2=*p2+3;
*p1=*p2-5;
z=*p1 * *p2 - 6;
printf(“\n a= %d, b= %d”, a,b);
printf(“z=%d\n,z);
return 0;
}
Note: y= 4 * - *p2/*p1 + 10 ≡ ((4*(-(*p2)))/(*p1))+10.
Since all the variables are of type int the entire evaluation is carried out using
integer arithmetic.

Pointers and arrays:


When an array is declared the compiler allocates a base address and sufficient
amount of storage to contain all the elements of the array in contiguous memory
locations. The base address is the location of the first element of the array. The
compiler also defines the array name as a constant pointer to the first element.
If we declare ‘p’ as an integer pointer, then we can make the pointer ‘p’ to point to
the array x by the following assignment.
p = x;
This is equivalent to p = &x[0];
We can access every value of x using p++ to move from one element to another.
E.g. p = &x[0];
   p+1 = &x[1];
        p+2 = &x[2];
Address of x[2]=base address+(2*scale factor of int)
                         =1000 + (2*2) = 1004

Program to illustrate the usage of pointers on array

#include <stdio.h>
int main()
{
    int *p, sum, i;
    int x[5]={2,3,4,5,7};
    i=0;
    p=x;
    sum=0;
    printf("Elements\t Value\t address\n\n");
    while (i<5)
    {
        printf("x[%d]\t  %d\t %u\n", i,*p, p);
        sum = sum + *p;
        i++;
        p++;
    }
    printf("Sum=%d\n",sum);
    return 0;
}
 
Program to Reverse a String using Pointer
#include
<stdio.h>
#include
<string.h> int
main()
{
char str1[100],str2[100];
char *p1,*p2;

printf("Enter a String\n");
scanf("%s",str1);
p1=str1+strlen(str1)-1;
p2=str2;
while(p1>=str1)
{
*p2=*p1;
p2++; p1--;
}
*p2='\0';
printf("Original String: %s\n",str1);
printf("Reverse String: %s",str2);
return 0;
}

USER DEFINED FUNCTIONS


A function is a self-contained block of code that performs a particular task.
2 Types:
1. Predefined (library function): The function is already defined by the ‘C’
compiler. It can only be utilized by including the header files in the programs. 
a. stdio.h – printf(), scanf()
b. math.h – sqrt(),pow()
c. string.h – strcpy(), strcmp(), strlen(), strcat()

2. User-defined function: To make use of a user-defined functions we need to


establish 3 elements.
i. Function declaration
ii. Function definition
iii. Function call

Function declaration: It is also known as function prototype consists of 4 parts.


1. Function type ( return type)
2. Function name
3. Parameter list
4. Terminating semicolon.

The Syntax is,


Function_type function_name (parameter list);
e.g. int mul (int x, int y);

A prototype declaration may be placed in 2 places in a program.


1. Above all the functions
2. Inside a function definition.
The place of declaration decides the scope of the function.

Function definition  
A function definition consists of function header and function body.
A general format is,

Function_type function_name (parameter list)


{
        Local variable_declaration;
        Executable stmt;
        Return stmt;
}
NOTE:
 Function type specifies the type of value the function is expected to return
to the program calling the function.
 Function name is any valid c identifier.
 Parameter list declares the variables that will receive the data sent by the
calling program. They serve as input data to the function to carry out the
specified task. Since they represent actual input values, they are referred
to as formal parameters.
 Local variables declaration specifies the variable needed by the function.
 Executable statements that perform the task of the function.
 A return statement that returns the value evaluated by the function. It can
take one of the following forms,
return; or return (expression);
The plain return does not return any value. When a return is encountered, the
control is passed back to the calling function.
The second form of return with an expression returns the value of the
expression.
E.g.        int mul(int x, int y)
         {
                 int p;
                 p=x*y;
                 return p;
          }
 Returns the value of p which is the product of the value of x and y.
Examples of function definitions are:
a. float mul (float x,float y)
{
    float result;
    result= x*y;
    return result;
}
b. void sum(int a, int b)
{
    printf(“Sum=%s”,a+b);
    return;
}

c. void display(void)
{
    printf(“No type, no parameter”);
}
Function calls:
A function can be called by simply using the function name followed by a list of
actual parameters if any, enclosed in parenthesis.
E.g. void main()
       { 
            int y;
            y=mul(10,5);
            printf(“%d\n”,y);
      }
     int mul (int x, int y)
    {
         int p;
         p=x*y;
         return p;
    }
The function call sends two integer values to the function which are assigned
to x and y respectively. The function computes the product of x and y and
assigns the result to the local variable ‘p’ and returns the value 50 to the main
where it is assigned to y again and then displayed.
Category of Functions:
A function depending on whether arguments are present or not and whether a
value is returned or not, may belong to one of the following categories,
Category 1: Function with no argument and no return type.
Category 2: Function with arguments and no return type value.
Category 3: Function with arguments and one return value.
Category 4: Function with no argument but return a value.
1. No argument and no return value: In this type of function, there is no data
transfer between the calling function and the called function. Here the
function does not receive any data from the calling function nor does it
return a value to the calling function.
#include<stdio.h>
void value();
int main()
{
    value();
     return 0;
}
void value()
{
    float area;
    int radius;
    printf("Enter the radius\n");
    scanf("%d",&radius);
    area=3.14*radius*radius;
    printf("Area=%f\n",area);

}
2.  Arguments but no return value: Here there is one way data transfer from
calling function to called function. When the calling function invokes the
function it also passes the values to the called function as arguments. The
values sent by the calling function are the actual arguments and the values
received by the called functions are the formal arguments.
    The formal and actual arguments should match in number, type and order.
The values of the actual arguments are assigned to the formal arguments on a
one to one basis starting with the first argument.
#include<stdio.h>
void printline(char c)
int main()
{
printline(‘Z’);
printf(“\n This illustrates the use of C function\n”);
printline(‘C’);
return 0;
}
void printline(char ch)
{
int i;
for(i=1; i<=52; i++)
printf(“%c”,ch);
printf(“\n”);
}
3. Arguments with return values: Such functions have 2 way data
communication that receives a predefined form of input and output a
desired value.
// illustration of function with arguments and return value.
#include<stdio.h>
int largest(int, int);
int main()
{
int x, y, max;
printf(“Enter the values of x and y\n”);
scanf(“%d%d”, &x, &y);
max=largest(x , y);
printf(“The largest =%d\n”, max);
return 0;
}
int largest(int p, int q)
{
if(p>q)
return(p)
else
return(q);
}
4. No arguments but returns a value:
Here, the called function does not receive any data from the calling function. It
Manages with its local data to carry out the specified task. However, after the
specified processing the called function returns the computed data to the
calling function. It is a one way data communication between the calling
function and called function.

#include<stdio.h>
int getnumber(void);
int main()
{
int m = getnumber();
printf(“%d”, m);
return 0;
}
int getnumber(void)
{
int number;
scanf(“%d”, &number);
return(number);
}
Passing arrays to functions:
To pass an array to a called function, it is sufficient to list the name of the
array, without any subscripts and the size of the array as arguments.
E.g.: largest(a, n);
Where ‘a’ is an array and ‘n’ the size. The called function expecting this call
must be appropriately defined.
e.g. float(largest(float array[] ,int size).
It is not necessary to specify the size of the array here.
// To find the largest in an array.
#include<stdio.h>
int main()
{
float largest(float a[], int n);
float value[4]={2.5, -4,75, 1.2, 3.67};
printf(“%f\n”, largest(value,4);
return 0;
}
float largest(float a[], int n)
{
int i;
float max;
max = a[0];
for(i=1; i<n; i++)
if(max<a[i])
max=a[i];
return(max);
}

Program to check a number for prime by defining isprime( ) function


#include<stdio.h>
int flag=0;
int isprime(int n)
{
int i,flag=1;
for(i=2;i<n;i++)
{
if(n%i==0)
{
flag=1;
break;
}
}
}

int main()
{
int n;
printf("Enter the number\n");
scanf("%d",&n);
flag=isprime();
if(flag==1 && n!=0 && n!=1)
printf("%d is a prime number\n",n); else
printf("%d is not a prime number\n",n);

return 0;
}

Program to read, display and add two m x n matrices using


functions
#include <stdio.h>
int i,j,r,c,a[10][10],b[10][10],sum[10][10];
void readmatrix(int m[10][10])
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&m[i][j]);
}
}
}

void addmatrix( )
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum[i][j]=a[i][j]+b[i][j];

}
}
}

void displaymatrix(int m[10][10])


{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%4d",m[i][j]);
}
printf("\n");
}
}
int main()
{
printf("Enter the order of the matrix\n");
scanf("%d%d",&r,&c);

printf("Enter %d elements of matrix A\n",r*c);


readmatrix(a);

printf("Enter %d elements of matrix B\n",r*c);


readmatrix(b);

addmatrix(a,b);

printf("Matrix A\n");
displaymatrix(a);

printf("Matrix B\n");
displaymatrix(b);

printf("Resultant Matrix\n");
displaymatrix(sum);
return 0;
}
Program to read, display and multiply two m x n matrices using
functions
#include <stdio.h>
int i,j,r1,c1,r2,c2,a[10][10],b[10][10],mul[10][10];
void readmatrix(int r,int c,int m[10][10])
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&m[i][j]);
}
}
}

void multiplymatrix(int a[10][10],int b[10][10])


{
int k;
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mul[i][j]=0;
for(k=0;k<r2;k++)
mul[i][j]=mul[i][j]+(a[i][k]*b[k][j]);
}
}
}

void displaymatrix(int r,int c,int m[10][10])


{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%4d",m[i][j]);
}
printf("\n");
}
}
int main()
{
printf("Enter the order of the matrixA\n"); scanf("%d
%d",&r1,&c1);

printf("Enter the order of the matrixB\n"); scanf("%d


%d",&r2,&c2);
if(c1==r2)
{

printf("Enter %d elements of matrix A\n",r1*c1);

readmatrix(r1,c1,a);

printf("Enter %d elements of matrix B\n",r2*c2);


readmatrix(r2,c2,b);

multiplymatrix(a,b);

printf("Matrix A\n");
displaymatrix(r1,c1,a);

printf("Matrix B\n");
displaymatrix(r2,c2,b);

printf("Resultant Matrix\
n");
displaymatrix(r1,c2,mul);
}
else
printf("Multiplication not possible\n");
return 0;
}

Pointers and functions:


1. Call by Value: The process of passing the actual value of variable is known as
call by value. In this parameter passing method, values of actual parameters
are copied to function’s formal parameter and the 2 types of parameters are
stored in different memory locations. So any changes made inside functions
are not reflected in actual parameter.
2. Call by reference: When we pass addresses to a function, the parameters
receiving the addresses should be pointers. The process of calling a function
using pointers to pass the address of variable is call by reference. Both the
actual and formal parameters refer to same locations, so any changes made
inside the functions are actually reflected in actual parameters of caller, there
the values are passed using ‘&’ the address and the parameter receiving
should be pointers:
3. CALL BY VALUE
#include <stdio.h>
void swap(int a,int b);
int main()
{
    int a,b;
    printf("Enter 2 numbers\n");
    scanf("%d %d", &a, &b);
    swap(a,b);
    return 0;
}
void swap(int a, int b)
{
    int temp;
    temp=a;
    a=b;
    b=temp;
    printf("\n\n After swap\n a =%d\n b=%d\n", a, b);
}

CALL BY REFERENCE
#include <stdio.h>
void swap(int *a,int *b);
int main()
{
    int a,b;
    printf("Enter 2 numbers\n");
    scanf("%d%d",&a,&b);
    swap(&a,&b);
    printf("\n\nAfter swap\na=%d\nb=%d\n",a,b);
    return 0;
}
void swap(int *a,int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
 

Program to Swap Two Numbers using Pointers

#include <stdio.h>
void swap(int *a,int *b)
{
int
temp;
temp=*
a;
*a=*b;
*b=temp;
}

int main()
{
int a,b;
printf("Enter 2 numbers\
n"); scanf("%d
%d",&a,&b);

swap(&a,&b);
printf("\n\nAfter swap\na=%d\nb=%d\
n",a,b);
return 0;
}

----------------------------------------------------------------------------------------------

You might also like