0% found this document useful (0 votes)
40 views83 pages

Chapter 07 - Arrays - Students

Uploaded by

soumyadeepctry04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views83 pages

Chapter 07 - Arrays - Students

Uploaded by

soumyadeepctry04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Arrays

1
Session Objectives
• To learn about array declaration and manipulation
• To learn about matrix operation using two dimensional arrays
• To learn about string handling using arrays.

2
Session Topics
• Accessing the array elements and array initialization
• Single and multidimensional array
• Strings and string variables: Reading and Printing a
string
• Functions and arrays

3
Why do we need an array?
Let’s consider the situation where we need to get 10 student’s age and
store it for some calculation.
Since age is an integer type, we can store it something like below,

Example:
int ag1, age2, age3, age4, age5, age6, age7, age8, age9, age10;
Arrays
main( )
{
int x ;
x=5;
x = 10 ;
printf ( "\nx = %d", x ) ;
}
• Ordinary variables (the ones which we have used so far) are capable of
holding only one value at a time.
• However, there are situations in which we would want to store more than
one value at a time in a single variable.
Arrays
• Marks of students
• 6 subjects
• 6 variable

• 24 hours
• 24 variables

• 100 students
• 100 variables
• For example, suppose we wish to arrange the percentage marks
obtained by 100 students in ascending order.
• In such a case we have two options to store these marks in
memory:
(a) Construct 100 variables to store percentage marks obtained by
100 different students, i.e. each variable containing one
student’s marks.
(b) Construct one variable (called array or subscripted variable)
capable of storing or holding all the hundred values.
Formal Definition of Array
An array is a collective name given to a group of ‘similar quantities’.

• These similar quantities could be percentage marks of 100 students, or


salaries of 300 employees, or ages of 50 employees. What is important is
that the quantities must be ‘similar’.

• An array lets you declare and work with a collection of values of the
same type. All elements of any given array must be of the same type. i.e.
we cannot have an array of 10 numbers, of which 5 are ints and 5 are
floats.
• For example, you might want to create a collection of five integers.
Example :int a, b, c, d, e;
• Using arrays it could be declared as below. int arr[5];
This reserves memory for an array that to hold five integer values

• Each member in the group is referred to by its position in the group. For
example, assume the following group of numbers, which represent
percentage marks obtained by five students. per = { 48, 88, 34, 23, 96 }
Formal Definition of Array
• per = { 48, 88, 34, 23, 96 }
• If we want to refer to the second number of the group, the usual notation
used is per2. Similarly, the fourth number of the group is referred as per4.
• However, in C, the fourth number is referred as per[3]. This is because
in C the counting of elements begins with 0 and not with 1. Thus, in this
example per[3] refers to 23 and per[4] refers to 96.
• In general, the notation would be per[i], where, i can take a value 0, 1, 2,
3, or 4, depending on the position of the element being referred. Here
per is the subscripted variable (array), whereas i is its subscript.
• Thus, an array is a collection of similar elements. These similar elements
could be all ints, or all floats, or all chars, etc. Usually, the array of
characters is called a ‘string’, whereas an array of ints or floats is called
simply an array.
Memory Allocation in Arrays

• The five separate integers inside this array are


accessed by an index. All arrays start at
index 0 and go to (n-1) in
C. For example:
int a[4];

a[0] = 12;
a[1] = 9;
a[2] = 5;
a[3] = 14;

• You need to make a declaration before using an array and to specify


its data type, its name and, in most cases
• Make sure the array has a valid name

10
A Simple Program Using Array
A program to find average marks obtained by a class of 30 students in a
test.
main( )
{
int avg,
sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ; /* read data from an array*/
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}
Array Declaration
• To begin with, like other variables an array needs to be declared so
that the compiler will know what kind of an array and how large an
array we want.
• General syntax:, storage_class data_type array[expression];

• In our program we have done this with the statement: int marks[30] ;

• Here, int specifies the type of the variable, just as it does with
ordinary variables and the word marks specifies the name of the
variable. The [30] however is new.

• The number 30 tells how many elements of the type int will be in our
array. This number is often called the ‘dimension’ of the array. The
bracket ( [ ] ) tells the compiler that we are dealing with an array.

12
Accessing Elements of an Array
• Once an array is declared, individual elements in the array can be
referred.
• This is done with subscript, the number in the brackets following the
array name.
• This number specifies the element’s position in the array. All the array
elements are numbered, starting with 0. Thus, marks[2] is not the
second element of the array, but the third.
• In our program we are using the variable i as a subscript to refer to
various elements of the array. This variable can take different values
and hence can refer to the different elements in the array in turn. This
ability to use variables as subscripts is what makes arrays so useful.
Entering Data into an Array
• Here is the section of code that places data into an array:
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
• The for loop causes the process of asking for and receiving a student’s
marks from the user to be repeated 30 times.
• The first time through the loop, i has a value 0, so the scanf( ) function
will cause the value typed to be stored in the array element marks[0],
the first element of the array.
• This process will be repeated until I becomes 29. This is last time
through the loop, which is a good thing, because there is no array
element like marks[30].
• In scanf( ) function, we have used the “address of” operator (&) on the
element marks[i] of the array.
1. Write a program in C to store numbers and calculate the average of
the numbers using an array.

2. Write a program in C to find the largest number using an array.


for (int i = 0; i < n; ++i) {
printf("Enter number%d: ", i + 1);
scanf("%lf", &arr[i]);
}
// storing the largest number to arr[0]
for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
Write a program in C to read n number of values in an array and display
it in reverse order.
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}
printf("\nThe values store into the array are : \n");
for(i=0;i<n;i++)
{
printf("% 5d",a[i]);
}
printf("\n\nThe values store into the array in reverse are :\n");
for(i=n-1;i>=0;i--)
{
printf("% 5d",a[i]);
}
Write a program in C to count a total number of duplicate elements in an
array.
int arr1[100];
int arr2[100];
int arr3[100];
int n,mm=1,ctr=0;
/*----------------- Store Array Elements ------------------------------------*/
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
/*----------------- copy in other array ------------------------------------*/
for(i=0;i<n; i++)
{
arr2[i]=arr1[i];
arr3[i]=0;
}
/*------------------- mark the elements are duplicate -------------------------*/
for(i=0;i<n; i++)
{
for(j=0;j<n;j++)
{
if(arr1[i]==arr2[j])
{
arr3[j]=mm;
mm++;
}
}
mm=1;
}
/*--------------- Prints the array ------------------------------------*/
for(i=0; i<n; i++)
{
if(arr3[i]==2){ctr++;}
}
printf("The total number of duplicate elements found in the array is:
%d \n", ctr);
Array Elements in Memory
• Consider the following array declaration:
int arr[8] ;
• What happens in memory when we make this declaration?
• 16 bytes get immediately reserved in memory, 2 bytes each for the 8
integers
• If the array is not being initialized, all eight values present in it would
be garbage values.

• This happens because the storage class of this array is assumed to be


auto. If the storage class is declared to be static then all the array
elements would have a default initial value as zero.

• Whatever there is initial values, all the array elements would always be
present in contiguous memory locations.
Bounds Checking
• Data entered with a subscript exceeding the array size will simply be
placed in memory outside the array; probably on top of other data, or
on the program itself.
• This will lead to unpredictable results, to say the least, and there will
be no error message to warn you that you are going beyond the array
size. In some cases the computer may just hang.
• Thus, the following program may be terminated or may crash.

main( ) {
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[i] = i ;
}
Initializing Arrays
• You can assign values to the array in several ways
• this example demonstrates
int main() {
int arrayOfInts1[8] = {1, 2, 3, 4, 5, 6, 7, 8};
int arrayOfInts2[8];
int arrayOfInts3[ ] = {1,2,3,4,5,6,7,8}; /* an unsized array */
int arrayOfInts4[10];
int i; arrayOfInts2[0] = 1;
arrayOfInts2[1] = 2; • Till the array elements are not given any specific
arrayOfInts2[2] = 3; values, they are supposed to contain garbage
arrayOfInts2[3] = 4; values.
arrayOfInts2[4] = 5; • If the array is initialised where it is declared,
arrayOfInts2[5] = 6; mentioning the dimension of the array is optional
arrayOfInts2[6] = 7;
as in the 3rd example above.
arrayOfInts2[7] = 8;
for(i=0 ; i<8 ; i++)
= i + 1;
arrayOfInts4[i]
} return 0;
24
Reading Data from an Array
• One of the feature about array indexing is that, you can use a loop to
manipulate the index. For example, the following code initializes all of
the values in the array to 0:
int a[5];
int i;
for
(i=0;
i<5; i+
+)
a
[
i
]

0
;
• The following code initializes the values in the array sequentially and 25
then prints them out:
#include <stdio.h>
Example : READ and Display

#include <stdio.h>
#include <stdio.h>
int main()
int main() {
{
int a[5], i;
int a[5], i;

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


a[i] = i; scanf(“%d
”,&a[i]);
for (i=0; i<5; i++)
printf("a[ for (i=0; i<5; i++)
%d] = } printf("a[
%d\n", %d] =
i, a[i]); %d\n",
} i, a[i]);

26
Example : READ, Process and Display

#include<stdio.h> else
void main( ) a[i]=a[i]*a[i];
{ }
int n,a[100]; for(i=0;i<n;i++)
int i; printf("a[%d]=%d\n",i,a[i]);
printf("How many numbers"); }
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{ if(i%2==0)
{
a[i]=a[i]+5;
}

27
Advantages of Arrays
•In an array, accessing an element is very easy by using the index number.
•2D Array is used to represent matrices.
• To store multiple values of similar type then the Array can be used and
utilized efficiently.

Disadvantages of Arrays
Array size is fixed: The array is static, which means its size is always
fixed. The memory which is allocated to it cannot be increased or
decreased.
int main()
{
int arr[10];
// Assign values to array
arr[0] = 5;
arr[5] = 6;
arr[7] = -9;
// Print array element at index 0
printf("Element at index 0 is %d\n",arr[0]);

// Print array element at index 11


printf("Element at index 11" is %d", arr[11]);

return 0;
}
Element at index 0 is 5
Element at index 11 is -1176897384
Array is homogeneous: The array is homogeneous, i.e., only one type of
value can be store in the array. For example, if an array type “int“, can
only store integer elements and cannot allow the elements of other
types such as double, float, char so on.

Array is Contiguous blocks of memory: The array stores data in


contiguous(one by one) memory location. Below is the representation
of the same:
Insertion and deletion are not easy in Array: The operation insertion
and deletion over an array are problematic as to insert or delete
anywhere in the array, it is necessary to traverse the array and then shift
the remaining elements as per the operation. This operation cost is
more.
for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
printf("\nEnter the new element to be inserted: ");
scanf("%d", &x);
printf("Enter the position where element is to be inserted: ");
scanf("%d", &pos);
//shift all elements 1 position forward from the place
//where element needs to be inserted
n=n+1;
for(i = n-1; i >= pos; i--)
array[i]=array[i-1];
array[pos-1]=x; //Insert the element x on the specified position

//print the new array


for (i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
}
Example 2: calculation of Mean

int main( ) int main( )


{ {
int a[100], i,n; int s,i,n;
float sum=0,mean; float sum=0,mean;
printf(“How many numbers”); printf(“How many numbers”);
scanf(“%d”,&n); scanf(“%d”,&n);
for (i=0; i < n; i++) for (i=0; i < n; i++)
scanf(“%d”,&a[i]); {
for (i=0; i <n; i++) scanf(“%d”,&a)
sum=sum+a[i]; ; sum=sum+a;
mean=sum/n; }
printf(“Mean of the given numbers mean=sum/n;
is:%f”,mean); printf(“Mean of the given numbers
} is:%f”,mean);
}

35
Here is a program that prints out the memory locations in which the
elements of this array are stored.
Operation on Arrays

1. Traversal
2. Copying
3. Reversing
4. Insertion
5. Sorting
6. Deletion
7. Searching
8. Merging
Sorting elements of an array

Sorting elements of array means to order the elements in ascending


or descending order – usually in ascending order.

There are a number of algorithms or techniques available for sorting


arrays in C, however we shall do the basic technique here.

The basic approach to sorting is Bubble sort method where in nested


loop is used to sort elements of array.
Approach using Bubble Sort: (Ascending Order)

 Create an array of fixed size.


 Take a variable which stores the number of elements of the array
 Iterate via for loop to take array elements as input, and print them.
 The array elements are in unsorted fashion, to sort them, make a
nested loop.
 In the nested loop, the each element will be compared to all the
elements below it.
 In case the element is greater than the element present below it, then
they are interchanged.
 After executing the nested loop, we will obtain an array in ascending
order arranged elements.
Approach using Bubble Sort: (Ascending Order)

Input: arr[] = {5, 1, 4, 2, 8}


First Pass:
Bubble sort starts with very first two elements, comparing them to check
which one is greater.
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two
elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in
order (8 > 5), algorithm does not swap them.
Approach using Bubble Sort: (Ascending Order)

Input: arr[] = {5, 1, 4, 2, 8}


Second Pass:
Bubble sort starts with very first two elements, comparing them to check
which one is greater.
Now, during second iteration it should look like this:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
int main() {
int i, j, temp, n, arr[30];
printf("Enter the number of elements in your array: \n");
scanf("%d", &n);
printf("Enter the array elements: \n");
for (i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
if (arr[i] > arr[j]) { //to check if current element greater than i+1th element, if yes;
perform swap.
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
} }
printf("\nThe array sorted in ascending order is as given below: \n");
for (i = 0; i < n; ++i) {
printf("%d\n", arr[i]);
}
return 0;}
Deletion of an element from the array

Step 1: Input the size of the array arr[] and declare the variables.
Step 2: Use a loop to insert the elements in an array.
Step 3: Now, input the position of the particular element that the user or programmer
wants to delete from an array. For user location starts from position 1. However array
index starts from 0. Hence, when we delete the element we need to delete element
present at location = position -1.
Step 4: Compare the position of an element (pos) from the total no. of elements
(num+1). If the pos is greater than the limit, the deletion of the element is not possible
and jump to step 7.
Step 5: Else removes the particular element and shift the rest elements' position to the
left side in an array. What we essentially do is, shift the element next to the element to
be deleted to the location = position -1, i.e. the next element is placed in position of
deleted element and so on we keep shifting the remaining elements by one position to
the left.
Step 6: Display the resultant array after deletion or removal of the element from an
array.
Step 7: Terminate or exit from the program.
printf("Enter the location from where you wish to delete the element:\n");
scanf("%d", &position);

num = array[position-1];
if (position >= n+1 || position < 0) /*n+1, since user will count element as
position 1 onwards. Internally though indexing starts from 0, which user would
not know.*/
printf("Deletion not possible as entered location is invalid.\n");
else
{
for (i = position - 1; i < n - 1; i++) //since array index starts from 0; thus position
in terms of array index is position-1
array[i] = array[i+1];
printf("Resultant array after deletion of element %d from location %d:\n", num,
position);
for (i = 0; i < n - 1; i++)
printf("%d\n", array[i]);
}
return 0;
}
Searching element of an array
 We accept the array input from user.
 The user will enter the element that needs to be searched in the
array.
 We scan the entire array sequentially to search for entered element
‘num‘.
 On discovering the element in the array at location i, we display it
to the user.
 If the element occurs at more than one place as well, the search
continues until end of array is reached.
 If even after scanning entire array element is not found, ( i==n) then
same is conveyed to user.
int array[100], num, i, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements: \n");
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter a number to search\n");
scanf("%d", &num);
for (i = 0; i < n; i++)
{
if (array[i] == num) /* When required element is found */
{
printf("The element: %d is present at location %d.\n", num, i+1);
}
if (i == n)
printf("The element %d is not present in the array.\n", num);
return 0;
}
Merging of two arrays

 Input the length of both the arrays.

 Input the arrays elements from user.

 Copy the elements of the first array to the merged array when
initialising it.

 Copy the elements of the second array to the merged array while
initialising the second array.

 Sort the merged array.

 Display the merged array.


//Declaring the size of arrays
int s1, s2, s3;
printf("\n Enter the size of 1st array ");
scanf("%d", & s1);
printf("\n Enter the size of 2nd array ");
scanf("%d", & s2);
s3 = s1 + s2;
printf("\n Enter the elements of 1st array\n");
// Declaring the array
int arr1[s1], arr2[s2], arr3[s3];
//Initialising the array
for (int i = 0; i < s1; i++) {
scanf("%d", & arr1[i]);
arr3[i] = arr1[i];
}
int k = s1;
printf("\nEnter the elements of 2nd array \n");
for (int i = 0; i < s2; i++) //Array Initialised
{
scanf("%d", & arr2[i]);
arr3[k] = arr2[i];
k++;
}
printf("\nThe merged array before sorting : \n\t");
for (int i = 0; i < s3; i++)
printf("%d ", arr3[i]); //Print the merged array before sorting

printf("\n The merged array after sorting\n\t");


for (int i = 0; i < s3; i++) //Sorting the array
{
int tem;
for (int j = i + 1; j < s3; j++) {
if (arr3[i] > arr3[j]) {
tem = arr3[i];
arr3[i] = arr3[j];
arr3[j] = tem;
}
}
}

for (int i = 0; i < s3; i++) //Printing the sorted Array


{
printf(" %d ", arr3[i]);
}
}
Minimum Calculation
#include <stdio.h>
main( )
{
int a[size],i, min;
printf(“Give size of the array \n”); \
scanf(“%d”, &size);

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


scanf(“%d”, &a[i]);
min = 99999;
for (i=0; i<size; i++)
{
if (a[i] < min)
min = a[i];
}
printf(“\n Minimum is %d”, min);
}

50
GPA Calculation
#include <stdio.h>
#define nsub 6
main()
{
int grade_pt[nsub], cred[nsub],i, gp_sum=0, cred_sum=0, gpa;
printf(“Input gr. points and credits for six subjects \n”);
for (i=0; i<nsub; i++)
scanf(“%d %d”, &grade_pt[i], &cred[i]);
for (i=0; i<nsub; i++)
{
gp_sum += grade_pt[i] * cred[i];
cred_sum += cred[i];
}
gpa= gp_sum / cred_sum;
printf(“\n Grade point average: is
%d”, gpa);
}

51
#include <stdio.h>
void main()
{ int arr1[100];
int n, i, j, tmp;
printf("\n\nsort elements of array in ascending order :\n ");
printf("----------------------------------------------\n");
printf("Input the size of array : ");
scanf("%d", &n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{ printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr1[j] <arr1[i])
{
tmp = arr1[i]; arr1[i] = arr1[j]; arr1[j] = tmp;
}
}
}
printf("\nElements of array in sorted ascending order:\n");
for(i=0; i<n; i++)
{
printf("%d ", arr1[i]);
}
printf("\n\n");
}
#include <stdio.h>
void main ()
{

int number[30]; printf("The numbers arranged in descending


order are given below\n");
int i, j, a, n;
printf("Enter the value of N\n"); for (i = 0; i < n; ++i)
scanf("%d", &n); {
printf("%d\n", number[i]);
printf("Enter the numbers \n"); }
for (i = 0; i < n; ++i)
scanf("%d", &number[i]); }

/* sorting begins ... */

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


{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
Two-Dimensional Arrays
• Two – dimensional array is the simplest form of a multidimensional
array.
• The basic form of declaring a two-dimensional array of size x, y:

Syntax:

int x[i][j];
Elements in two-dimensional arrays are commonly referred to by x[i][j]
where i is the row number and ‘j’ is the column number.

54
2-D Array

•We have seen that an array variable can store a list of values.
•Many applications require us to store a table of values.

•The table contains a total of 20 values, five in each line.


–The table can be regarded as a matrix consisting of four rows and
five columns.
- C allows us to define such tables of items by using two-
dimensional arrays.

55
2-D Array
• A two – dimensional array can be seen as a table with ‘x’ rows and
‘y’ columns where the row number ranges from 0 to (x-1) and the
column number ranges from 0 to (y-1).

A two – dimensional array ‘x’ with 3 rows and 3 columns is shown


below:

56
Memory Map of a 2-Dimensional Array
Col 0 Col 1 Col 2 Col 3 Col 4
Row 0 75 82 90 65 76
Row 1 68 75 80 70 72
Row 2 88 74 85 76 80
Row 3 50 65 68 40 70

S[0][0] S[0][1] S[0][2] S[0][3] S[0][4] S[1][0] S[1][1] S[1][2] S[1][3] S[1][4] S[2][0] S[2][1] S[2][2] S[2][3] S[2][4] S[3][0] S[3][1] S[3][2] S[3][3] S[3][4]

75 82 90 65 76 68 75 80 70 72 88 74 85 76 80 50 65 68 40 70
Memory Map of a 2-Dimensional Array
• Let us repeat the arrangement of array elements in a two-dimensional
array of students, which contains roll nos. in one column and the marks
in the other.

• The array arrangement shown in previous figure is only conceptually


true. This is because memory doesn’t contain rows and columns.
In memory whether it is a one-dimensional or a two-dimensional array the
array elements are stored in one continuous chain.

• We can easily refer to the marks obtained by the third student using the
subscript notation as shown below:
printf ( "Marks of third student = %d", stud[2][1] ) ;
Declaring 2-D Arrays
General form:
storage_class data_type array_name [row_size][column_size];
•Examples:
int marks[4][5];
float sales[12]
[25];
double matrix[100][100];
static double matrix[100]
[100];
• Accessing Elements of a 2-D Array
• Similar to that for 1-D array, but
use two indices.
–First indicates row, second
indicates column.
- Both the indices should be expressions which evaluate to
integer values.

59
Initialising a 2-Dimensional Array
int stud[4][2] = { { 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
or even this would work...
int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;
of course with a corresponding loss in readability.

• It is important to remember that while initializing a 2-D array it is


necessary to mention the second (column) dimension, whereas the first
dimension (row) is optional.
Thus the declarations,
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
are perfectly acceptable,
whereas, int arr[2][ ] = { 12, 34, 23, 45, 56, 45
int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ; would never work.
Example :Read and Display
#include<stdio.h>
main()
{
int a[100][100], p, q, m, n;
printf("\n Enter row and col:");
scanf("%d %d", &m, &n);
for (p=0; p<m; p++)
{
for (q=0; q<n; q++) {
printf("\n Enter element %d and %d: ", p, q);
scanf("%d", &a[p][q]);
}
}
for (p=0; p<m; p++)
{
printf ("\n|");
for (q=0; q<n; q++)
{
printf(" %d ", a[p][q]);
}
printf("|");
}
}
63
Example :Read, Process and Display
#include<stdio.h>
main()
{
int a[100][100], p, q, m, n;
printf("\n Enter row and col:");
scanf("%d %d", &m, &n);
for (p=0; p<m; p++)
{
for (q=0; q<n; q++) {
printf("\n Enter element %d and %d: ", p, q);
scanf("%d", &a[p][q]);
}
}
for (p=0; p<m; p++)
for (q=0; q<n; q++)
a[p][q]=a[p][q]+5;
for (p=0; p<m; p++)
{
printf ("\n|");
for (q=0; q<n; q++)
{
printf(" %d ", a[p][q]);
}
printf("|"); 64
}
}
An Example -2D array
Program that stores roll number and marks obtained by a student
side by side in a matrix.
main( ) {
int stud[4][2] ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
}
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
}

There are two parts to the program—in the first part through a for loop we
read in the values of roll no. and marks, whereas, in second part through
another for loop we print out these values.
Example : Addition of two Matrices
/* Stored values into the array*/
printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}

printf("Input elements in the second matrix :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
/* calculate the sum of the matrix */
for(i=0;i<n;i++)
for(j=0;j<n;j++)
crr1[i][j]=arr1[i][j]+brr1[i][j];

printf("\nThe Addition of two matrix is : \n");


for(i=0;i<n;i++){
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",crr1[i][j]);
}
printf("\n\n");
}
Example : Multiplication of two Matrices
printf("Input elements in the first matrix :\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}
printf("Input elements in the second matrix :\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
//multiplication of matrix
for(i=0;i<r1;i++)
for(j=0;j<c2;j++)
crr1[i][j]=0;
for(i=0;i<r1;i++) //row of first matrix
{
for(j=0;j<c2;j++) //column of second matrix
{
sum=0;
for(k=0;k<c1;k++)
sum=sum+arr1[i][k]*brr1[k][j];
crr1[i][j]=sum;
}
}
printf("\nThe multiplication of two matrices is : \n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",crr1[i][j]);
}
Example : Transpose of two Matrices

printf("Input elements in the first matrix :\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("element - [%d],[%d] :
",i,j);
scanf("%d",&arr1[i][j]);
}
}
/* The transpose of a matrix is*/

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
brr1[j][i]=arr1[i][j];
}
}
#include<stdio.h>
main() Example : Matrix Addition
{
int a[100][100], b[10][10], c[10][10], p, q, m, n;
printf("\n Enter row and col:");
scanf("%d %d", &m, &n);
printf("\n Matrix A");
for (p=0; p<m; p++)
{
for (q=0; q<n; q++) {
printf("\n Enter element %d and %d: ", p, q);
scanf("%d", &a[p][q]);
}
}
printf("\n Matrix B");
for (p=0; p<m; p++) printf("\n Matrix B");
{ for (p=0; p<m; p++)
for (q=0; q<n; q++) { {
printf("\n Enter element %d and %d: ", p, q); printf ("\n|");
scanf("%d", &b[p][q]); for (q=0; q<n; q++)
} {
} printf(" %d ", c[p][q]);
printf("\n Matrix Addition");
for (p=0; p<m; p++) }
for (q=0; q<n; q++) printf("|");
c[p][q]=a[p][q]+b[p][q]; }
}
What will be the output of the following programs:

# include <stdio.h>
int main( )
{
int num[ 26 ], temp ;
num[ 0 ] = 100 ;
num[ 25 ] = 200 ;
temp = num[ 25 ] ;
num[ 25 ] = num[ 0 ] ;
num[ 0 ] = temp ;
printf ( "%d %d\n", num[ 0 ],
num[ 25 ] ) ;
return 0 ;
}
200 100
# include <stdio.h>
int main( )
{
int array[ 26 ], i ; 65 A
for ( i = 0 ; i <= 25 ; i++ ) 66 B
{ .
array[ i ] = 'A' + i ; .
printf ( "%d %c\n", array[ i ], .
array[ i ] ) ; .
} .
return 0 ; 90 Z
}
# include <stdio.h>
int main( )
{
int sub[ 50 ], i ; 49 49
for ( i = 0 ; i <= 48 ; i++ ) ;
{
sub[ i ] = i ;
printf ( “%d %d\n",i, sub[ i ] ) ;
}
return 0 ;
}
# include <stdio.h>
int main( ) {
int size ;
scanf ( "%d", &size ) ;
int arr[ size];
for ( i = 1 ; i <= size ; i++ ) {
scanf ( "%d", &arr[ i ] ) ;
printf ( "%d\n", arr[ i ] ) ;
}
return 0 ;
}

‘i’ undeclared
# include <stdio.h>
int main( )
{
int array[ 6 ] = { 1, 2, 3, 4, 5, 6 } ;
int i ;
for ( i = 0 ; i <= 25 ; i++ )
printf ( "%d\n", array[ i ] ) ;
1
return 0 ;
2
}
3
4
5
6
634427648
2031456649
Array bounds
exceeded
# include <stdio.h>
int main( )
{
int n[ 3 ][ 3 ] = {
2, 4, 3,
6, 8, 5,
3, 5, 1
};
printf ( " %d %d\n", n[ 2 ][ 0 ], n[ 2 ][ 2 ] ) ;return 0 ;
}

3 1
# include <stdio.h>
int main( )
{
int sub[ 50 ], i ;
for ( i = 0 ; i <= 50 ; i++ )
{
sub[ i ] = i ;
1
printf ( "%d\n" , sub[ i ] ) ;
2
}
3
return 0 ;
4
}
5
6
.
.
50
Terminated:
Array bounds
# include <stdio.h>
int main( )
{
int three[ 3 ][ ] = {
2, 4, 3,
6, 8, 2,
2, 3, 1
};
printf ( "%d\n", three[ 1 ][ 1 ] ) ;
return 0 ;
}

Error: while declaring two dimensional array mentioning the column


dimension is necessary
# include <stdio.h>
void main(){
int a=15, b=10,c,d;
c=++b-a;

d=b+++a;
printf(“%d %d %d %d”,a,b,c,d);
}

15 12 -4 26
# include <stdio.h>
int main()
{
int x = 10;
{
int x = 0;
printf("%d",x);
}
return 0;
}

0
#include <stdio.h>
void main()
{
int i = 2,j=0;
{
int i = 4, j = 5;
printf("%d %d", i, j);
}
printf("%d %d", i, j);
}

4 52 0
#include <stdio.h>
void main()
{
int i = 2;
{
int i = 4, j = 5;
printf("%d %d", i, j);
}
printf("%d %d", i, j);
}

error: ‘j’ undeclared (first use in this function)


In C, you delimit a block of code by {} . The opening and closing curly braces
indicate the beginning and the end of a block, respectively.

{
/*OUTER BLOCK*/

//contents of the outer block just before the start of this block
//CAN be accessed here

/*INNER BLOCK*/

//contents of the inner block are NOT accessible here


}
#include <stdio.h>
void main()
{
int j; for(j = 1; j <= 10; j = j-1)
printf("%d",j);
}

infinite loop

You might also like