Unit3 arraysNEP
Unit3 arraysNEP
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;
}
for(i=0;str[i]!='\0';i+
+) len++;
return 0;
}
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.
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.
#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;
}
Function definition
A function definition consists of function header and function body.
A general format is,
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);
}
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;
}
void addmatrix( )
{
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum[i][j]=a[i][j]+b[i][j];
}
}
}
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]);
}
}
}
readmatrix(r1,c1,a);
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;
}
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;
}
#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;
}
----------------------------------------------------------------------------------------------