arraypdf
arraypdf
Sushant Paudel
PROBLEM
If we need to sort 30 integer type data and
display them, we have to define 30
variables of integer data type as follows:
int a, b, c,…, z, a1, a2, a3, a4;
This is possible but inefficient.
Further as the number of integers required
increases, more and more variables need to
be defined.
Solution: ARRAY
ARRAY: Array is the collection of similar data types
or collection of similar entity stored in contiguous
memory location. Array of character is a string. Each
data item of an array is called an element. And each
element is unique and located in separated memory
location. Each of elements of an array share a variable
but each element having different index no. known as
subscript. An array can be a single dimensional or
multi-dimensional and number of subscripts
determines its dimension. And number of subscript is
always starts with zero. One dimensional array is
known as vector and two dimensional arrays are
known as matrix.
ADVANTAGES:
array variable can store more than one value
at a time where other variable can store one
value at a time.
Example:
int arr[100];
int mark[100];
The most important property of an array is that its
elements are stored in contiguous memory
locations
E.g. int num[5];
2 4 6 8 10
2000 2002 2004 2006 2008
DECLARATION OF AN ARRAY :
Its syntax is :
Data type array name [size];
int arr[100];
int mark[100];
int ar[5]={10,20,30,100,5}
The declaration of an array tells the compiler that, the data type, name
of the array, size of the array and for each element it occupies memory
space. Like for int datatype, it occupies 2 bytes for each element and
for float it occupies 4 byte for each element etc.
while(i<10)
{
sum=sum+arry[i];
i++;
}
avg=sum/10;
printf("\nthe sum of elements of array is %f",sum);
printf("\n the average of the sum of elements of the array is %f:",avg);
}
main () // C program to find sum and average of n elements of the array
{
int a[100],i,n,sum=0;
float ave;
printf("How many number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the numbers:\n");
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
printf("The sum=%d",sum);
ave=sum/n;
printf("The average=%f",ave);
getch();
}
Void main() //Write a program to input n numbers and find the smallest number
{
int a[100],i,n,smallest;
printf("How many number:");
scanf("%d",&n);
printf("Enter the number:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
smallest=a[0];
for(i=0;i<n;i++)
{
if(smallest>a[i])
{
smallest=a[i];
}
}
printf("Smallest number=%d",smallest);
getch();}
SORTING
Sorting is the process of arranging items in
some sequence (ascending or descending) by
value or by alphabet or by any other weight.
Various sorting techniques exist but they are
beyond the scope of this course (Included in
Data Structures and Algorithms).
We will be using a simple sorting technique in
the coming slide to sort numbers in ascending
order.
void main()
{
int num[100], i, j, n, temp;
printf("\nHow many numbers you want to sort?:\t");
scanf("%d", &n);
for(i=0;i<n;i++)
scanf("%d", &num[i]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
printf("\nThe numbers in ascending order are:\n");
for(i=0;i<n;i++)
printf("\t%d", nums[i]);
getch();
}
Assignment:
• Write a program to input n numbers and find the greatest number
• Write a program to read salary of n employees and count the
number of employees whose salary is in between 10000 and 15000
• Write a program to read marks obtained by n students in a subject
and count the number of students whose mark is in between 60 and
80
Points to Remember
• An array is a collection of similar elements.
• The first element in the array is numbered 0, so the last element is 1
less than the size of the array.
• An array is also known as subscripted variable.
• Before using an array its type and dimension must be declared.
• Stored in contiguous memory.
MULTIDIMENSIONAL ARRAYS
Multidimensional arrays are those having
more than one dimension.
Multidimensional arrays are defined in the
same way as one dimensional arrays, except
that a separate pair of square brackets is
required for each subscript or dimension or
index.
Thus a 2-D (two dimensional) array requires
two pairs of square brackets, a 3-D array
requires three pairs of square brackets and
so on.
• Syntax for defining multidimensional array is:
data_type array_name[dim1][dim2]…[dimN];
• Here, dim1, dim2,…,dimN are positive valued
integer expressions that indicate the number of
array elements associated with each subscript.
Thus, total no. of elements=dim1*dim2*…*dimN
E.g.
• int survey[3][5][12];
• Here, survey is a 3-D array that can contain
3*5*12=180 integer type data. This array survey
may represent a survey data of rainfall during last
three years (2009,2010,2011) from months Jan. to
Dec. in five cities. Its individual elements are from
survey[0][0][0] to survey[2][4][11].
• MULTIDIMENSIONAL ARRAYS…
• E.g.
• int matrix[2][3];
• Here, matrix is a 2-D array that can contain
2*3=6 elements. This array matrix can
represent a table having 2 rows and 3
columns from matrix[0][0] to matrix[1][2].
Column1 Column2 Column3
12 13 144 36 33 536 36 56
65508 65510 65512 65514 65516 65518 65520 65522
Sample code
void main()
{
int num[4][2];
int i. j;
//use nested loop
for(i=0; i<4; i++) // first outer loop refers to the row
{
for(j=0; j<2; j++) // second inner loop refers to the column
{
printf(“\nEnter a number:”);
scanf(“%d”,&num[i][j]); //similarly we can print
the element also
}
}
}
Initializing a Two Dimensional Array
int num[4][2] ={
{1,2},
{3,4},
{5,6},
{7,8}
};
OR
int num[4][2] = {1,2,3,4,5,6,7,8};
Arr[4][4]
Row/column
0 1 2 3
2 4 6 8
0
10 20 30 40
1
5 10 15 20
2
3 6 9 12
3
#include<stdio.h> //program to Initialize a Two Dimensional Array
int main()
{
int arr[4][4]={
{2,4,6,8},
{10,20,30,40},
{5,10,15,20},
{3,6,9,12}
};
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("arr[%d][%d]:%d\n",i,j,arr[i][j]);
}
}
}
#include<stdio.h> //program to Initialize a Two Dimensional Array
int main()
{
int arr[4][4]={
{2,4,6,8},
{10,20,30,40},
{5,10,15,20},
{3,6,9,12}
};
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("\t%d",arr[i][j]);
}
printf("\n");
}
}
int main() /*a program to input values into a 2D array and display them*/
{
int array[2][3],i,j;
printf("enter the elements of 2d array\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&array[i][j]);
}
}
printf("the elements of 2d array are:\n") ;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\t%d",array[i][j]);
}
printf("\n");
}
}
Mat[0][1] Mat[0][2]
1 2 3
Mat[0][0]
Transpose
Trans[3][3]
Mat[0][0] Mat[0][1] Mat[0][2] Mat[0][0] Mat[1][0] Mat[2][0]
Mat[3][3] Trans[3][3]
getch();
}
Matrix addition
2 3 4 1 2 3 1 1 1
6 7 8 4 5 6 2 2 2
10 11 12 7 8 9 3 3 3
a[3][3]
C[3][3] b[3][3]
#include<stdio.h> //Write a program to add elements of two 3X3 matrix
#include<conio.h>
main ()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the elements of first matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of second matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("The sum of two matrix is as follows:\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
WRITE A PROGRAM TO FIND THE SUM OF SQUARES IN A DIAGONAL
OF A SQUARE MATRIX
Matrix Multiplication
M N N P
M N N P M P
A[M][N]*B[N][P]=C[M][P]
First[2][3] Second[3][2]
1 4
1 2 3
2 5
4 5 6
3 6
1*1+2*2+3*3 1*4+2*5+3*6
Mult[2][2]
4*1+5*2+6*3 4*4+5*5+6*6
14 32
32 77
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int r1,c1,r2,c2,i,j,k,sum=0;
int first[10][10],second[10][10],mult[10][10];
printf("enter the row and column of first matrix\n");
scanf("%d%d",&r1,&c1);
printf("enter the elements of first matrix\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&first[i][j]);
}
}
printf("enter the row and column of second
matrix\n");
scanf("%d%d",&r2,&c2);
printf("enter the elements of second matrix\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&second[i][j]);
}
}
if(c1!=r2)
{
printf("matrix multiplication is not possible\n");
getch();
exit(0);
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<c1;k++) //c1=r2
{
sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
sum=0;
}
}
printf("the matrix after the multiplication is:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",mult[i][j]);
}
printf("\n");
}
}
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=0,j=0,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[0][0]*second[0][0] {
Sum=0+1*1=1 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=0,j=0,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[0][1]*second[1[0] }
Sum=1+2*2=5
i=0,j=0,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[0][2]*second[2][0]
Sum=5+3*9=14
14 Mult[i][j] // i=0,j=0
Mult[0][0]=sum=14
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=0,j=1,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[0][0]*second[0][1] {
Sum=0+1*4=4 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=0,j=1,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[0][1]*second[1[1] }
Sum=4+2*5=14
i=0,j=1,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[0][2]*second[2][1]
Sum=14+3*6=32
14 32
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=1,j=0,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[1][0]*second[0][0] {
Sum=0+4*1=4 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=1,j=0,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[1][1]*second[1[0] }
Sum=4+5*2=14
i=1,j=0,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[1][2]*second[2][0]
Sum=14+6*3=32
14 32
32
1 2 3 1 4
4 5 6 2 5 for(i=0;i<r1;i++)
First[2][3] 3 6 {
second[3][2]
for(j=0;j<c2;j++)
i=1,j=1,k=0 {
sum=sum+first[i][k]*second[k][j]; for(k=0;k<c1;k++) //c1=r2=3
Sum=sum+first[1][0]*second[0][1] {
Sum=0+4*4=16 sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
i=1,j=1,k=1 sum=0;
sum=sum+first[i][k]*second[k][j]; }
Sum=sum+first[1][1]*second[1[1] }
Sum=16+5*5=41
i=1,j=1,k=2
sum=sum+first[i][k]*second[k][j];
Sum=sum+first[1][2]*second[2][1]
Sum=41+6*6=77
14 32
32 77
Mat[0][1] Mat[0][2]
1 2 3
Mat[0][0]
#include <stdio.h>
#include <conio.h>
void main()
{
char city[9]={'N','E','W',' ','Y','O','R','K','\0'};
int i=0;
while(city[i]!='\0')
{
printf("%c\t ",city[i]);
i++;
}
getch();
}
READING STRING FROM TERMINAL
• The input function scanf can be used with %s
format specification to read in a string of
characters.
• E.g.
char name[20];
scanf(“%s”, name);
• No ampersand(&) is required before variable
name.
• Problem:
“scanf() terminates its input on the first white
space it encounters”
#include <stdio.h>
#include <conio.h>
void main()
{
char name[20];
printf("\n Enter your name:");
scanf("%s", name);
printf("\n Your name is %s", name);
getch();
}
READING STRING FROM TERMINAL…
• Some versions of scanf() support the following
conversion specification for strings:
%[characters]
%[^characters]
• The specification %[characters] means that only
the characters specified within the brackets are
allowed in the input of string. If the input string
contains any other characters, the reading of
string will be terminated at the first encounter of
such a character.
• The specification %[^characters] means that the
characters specified after the caret(^) are not
allowed in the string and reading will be
terminated.
#include <stdio.h>
#include <conio.h>
void main()
{
char name[20];
printf("\nEnter your name (in uppercase):");
scanf("%[A-Z]",name);
printf("\nYour name is %s",name);
getch();
}
THIS PROGRAM CAN READ STRINGS WITH
BLANK SPACES
#include <stdio.h>
#include <conio.h>
void main()
{
char name[30];
printf("\n Enter your full name:");
scanf("%[^\n]", name);
printf("\n Your name is %s", name);
getch();
}
WRITING STRING TO SCREEN
• The printf() function with %s format is used to
print strings to the screen.
• The format %s can be used to display an array
of characters that is terminated by the null
character.
• E.g.
char name[19]=“Ram Prasad Adhikari”;
printf(“%s”, name);
gets() and puts ()
• The gets() function is used to read a string of
text, containing whitespaces, until a newline
character is encountered.
Syntax: gets(variable_name);
• It takes a string from user and stores in a string
variable variable_name.
• The puts() function is used to display the string
onto the screen.
Syntax: puts(variable_name);
COUNTING THE LENGTH OF THE STRING
#include <stdio.h>
#include <conio.h>
void main()
{
char input_string[50];
int i=0, length=0;
printf("\nEnter your text:\t");
gets(input_string);
while(input_string[i]!='\0') R A M \0
{
length++;
i++;
}
printf("\nThe length of your text is: %d character(s)", length);
getch();
}
strlen()
The function strlen() returns an integer which
denotes the length of the string passed into the
function.
• The length of the string is defined as the number
of characters present in the string, excluding the
null character.
• Syntax:
integer_variable=strlen(input_string);
• Use header file <string.h>.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int length=0;
char string1[20];
printf("enter the string\n");
gets(string1);
length=strlen(string1);
printf("\nthe length of string is %d",length);
getch();
return 0;
}
PROGRAM TO READ YOUR NAME FROM KEYBOARD AND OUTPUT A LIST OFASCII
CODES THAT REPRESENT YOUR NAME
void main()
{
char name[30];
int length, i;
printf("Enter your name:\t");
gets(name);
length=strlen(name);
printf("\nThe ASCIIvalues of characters in the name %s are:\n",name);
for(i=0;i<length;i++)
printf("%c = %d\n", name[i], name[i]); R A M \0
getch(); Name[0] Name[1] Name[2]
}
PROGRAM TO READ A STRING FROM KEYBOARD(UNTIL ENTER KEY) AND
COUNT THE NUMBERS OF VOWELS, CONSONANTS, SPACES, SEMICOLONS AND
COMMAS IN THAT STRING
#include <string.h>
void main()
{
char s[80];
int len, i, space=0, vowel=0, consonant=0, semicolon=0, comma=0;
printf("Enter string:\t");
gets(s);
len=strlen(s);
for(i=0;i<len;i++)
{
if(s[i]=='a'||s[i]=='e'||s[i]== 'i'||s[i]=='o'||s[i]=='u')
vowel++;
else if(s[i]==';')
semicolon++;
else if(s[i]==',')
comma++;
else if(s[i]==' ')
space++;
else
consonant++;
}
printf("\nThe number of vowel(s):%d", vowel);
printf("\nThe number of semicolon(s):%d", semicolon);
printf("\nThe number of comma(s):%d", comma);
printf("\nThe number of space(s):%d", space);
printf("\nThe number of consonant(s):%d", consonant);
getch();
}
COPYING ONE STRING TO ANOTHER
#include <stdio.h>
#include <conio.h>
void main()
{
char copy[50], paste[50];
int i;
printf("\n Enter your name (to copy):\t");
gets(copy); R A M \0
for(i=0;copy[i]!='\0';i++) copy[4]
{
paste[i]=copy[i];
paste[4]
}
paste[i]='\0';
printf("\n The name is (pasted as):\t");
puts(paste);
getch();
}
Another Way: strcpy()
• The strcpy() function copies one string to
another.
• It accepts two strings as parameters and
copies the second string character by
character into the first string including the
null character of the second string.
• The source string may be a string constant
like “Ramesh Kumar”.
• Syntax:
strcpy(destination_string, source_string);
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
char copy[50], paste[50];
int i;
printf("\nEnter your name (to copy):\t");
gets(copy);
strcpy(paste, copy);
printf("\nThe name is (pasted as):\t");
puts(paste);
getch();
}
COMBINING STRINGS
• Also called String Concatenation.
• Just as we cannot assign one string to another
directly, we cannot join two strings together by
the simple arithmetic addition. So, the statements
such as
string3=string1+string2;
string1=string2+“hey”;
are completely invalid.
• Here, the characters from string1 and string2
should be copied into string3 one after another.
Also the size of string3 should be large enough to
hold the total characters.
#include <stdio.h> //COMBINING STRINGS
#include <conio.h>
void main()
{ First_name[7]
int i, j;
R A M E S H \0
char first_name[7]=“Ramesh" ;
char last_name[9]=“Adhikari"; A D H I K A R I \0
char name[16]; Last_name[9]
for(i=0;first_name[i]!='\0';i++)
R A M E S H A D H I K A R I \0
name[i]=first_name[i];
name[i]=' '; //name[6] i.e i=6 name[16]
for(j=0;last_name[j]!='\0';j++)
name[i+j+1]=last_name[j];
name[i+j+1]='\0';
printf("%s", name);
getch(); }
Another Way: strcat()
• The strcat() function concatenates
two strings i.e. it appends one string
at the end of another.
• It accepts two strings as parameters
and stores the contents of the second
string at the end of the first string.
• Syntax:
strcat(first_string, second_string);
#include <string.h>
void main()
{
char first_name[30]= “Ramesh" ;
char last_name[]= "Adhikari";
strcat(first_name, last_name);
puts(first_name);
getch();
}
COMPARISON OF TWO STRINGS
• C does not permit the comparison of two
strings directly; i.e. statements such as
if(name1==name2)
(name==“abc”)
are not permitted.
• The comparison of two strings has to be done
character by character.
• The comparison is done until there is a
mismatch or one of the strings terminates into
a null character, whichever occurs first.
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[30], str2[40];
int i=0;
printf("Enter first string:\t");
gets(str1);
printf("\n Enter second string:\t");
gets(str2);
while(str1[i]==str2[i] && str1[i]!='\0' &&str2[i]!='\0') R A M \0
i++;
R A M \0
if(str1[i]=='\0' && str2[i]=='\0')
printf("\n Strings are equal.");
else
printf("\n Strings are unequal");
getch();
}
Another Way: strcmp()
• The strcmp() function compares two strings
to find out whether they are same or
different.
• It accepts two strings as parameters and
returns an integer 0 if the strings are equal.
• If the two strings are unequal, then it
returns an integer that has the numeric
difference (ASCII value difference) between
the first non-matching characters in the
strings.
#include <stdio.h>
#include <conio.h>
void main()
{
char str1[30],str2[40];
int i=0,value;
printf("Enter first string:\t");
gets(str1);
printf("\n Enter second string:\t");
gets(str2);
value=strcmp(str1,str2);
if(strcmp(str1,str2)==0)
printf("\n Strings are equal.");
else
printf("\n Strings are unequal");
getch();
}
Reversing a String
#include <stdio.h>
#include <conio.h>
void main()
{
char string[25], reverse_string[25]; R A M \0
int length, i, j;
printf("\nInput string to be reversed:");
gets(string); M A R \0
length=strlen(string);
for(j=0,i=length-1;j<length;j++,i--)
reverse_string[j]=string[i]; //Reverse_sring[0]=string[2]
reverse_string[j]='\0';
//Reverse_sring[1]=string[1]
puts(reverse_string);
getch(); //Reverse_sring[2]=string[0]
}
Another Way: strrev()
• The function strrev() is used to reverse all
characters in a string except the null
character at the end of string.
• E.g. The reverse of string “CSIT” is “TISC”.
• Syntax:
• strrev(string);
• Here, the characters in the string “string” are
reversed and the reversed string is stored in
“string”.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[25];
printf("\n Input string to be reversed:");
gets(string);
strrev(string);
printf("\n The reversed string is: %s", string);
getch(); }
/*Program to read a string and check for palindrome*/
#include <stdio.h>
#include <conio.h>
void main()
{
char string[50];
int len, i, p=1;
printf("Enter string:\t");
gets(string);
len=strlen(string);
for(i=0;i<(len/2);i++)
{
if(string[i]!=string[len-i-1])
{
p=0;
}
} R A H A R \0
if(p==0)
printf("\nThe input string is not palindrome.");
else //String[0]=string[5-0-1]
printf("\nThe input string is palindrome."); //String[1]=string[5-1-1]
getch();
} //String[2]=string[5-2-1]