0% found this document useful (0 votes)
19 views36 pages

C Chapter 06

The document provides a comprehensive overview of C arrays, detailing their characteristics, types, and usage, including both one-dimensional and two-dimensional arrays. It explains how to declare, initialize, and access array elements, as well as the memory allocation and indexing principles. Additionally, it includes examples of array manipulation, such as finding the smallest element and performing operations like transposing a matrix.

Uploaded by

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

C Chapter 06

The document provides a comprehensive overview of C arrays, detailing their characteristics, types, and usage, including both one-dimensional and two-dimensional arrays. It explains how to declare, initialize, and access array elements, as well as the memory allocation and indexing principles. Additionally, it includes examples of array manipulation, such as finding the smallest element and performing operations like transposing a matrix.

Uploaded by

basarenkov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

C arrays

1
• It is derived data type.
• An array is a very popular and useful data
structure used to store data elements in
successive memory locations.
• It is known as “Composite data structure” as
more than one element is stored in a sequence.
• It permits only homogenous data.
• An array can be declared of any standard or
custom data type.
• The array of character(strings) type works
somewhat differently from an array of
integers, floating numbers.
• Array elements can be accessed by its position
in the array called as index.
• Values in an array are identified using array
name with subscripts.
• It is also known as subscripted variable.
• The array can be done as under
int a[5] = {1, 2, 3, 4, 5};

Calling array elements


a[0] Refers to 1st element i.e. 1
a[1] Refers to 2nd element i.e. 2
a[2] Refers to 3rd element i.e. 3
a[3] Refers to 4th element i.e. 4
a[4] Refers to 5th element i.e. 5
Size: Number of elements or capacity to store elements in an array is called its size. It is always mentioned in
brackets “[ ]”.

Type : Type refers to data type. It decides which type of element is stored in the array. It also instructs the
compiler to reserve memory according to data type.

Base : The address of the first element(0th) is a base address. The array name itself stores address of the
first element.

Index : The array name is used to refer to the array element. For example, num[x], num is array name and x
is index. The value of x begins from 0 to onwards depending on the size of the array. The index value is
always an integer value.

Range : Index of an array i.e. value of x varies from lower bound to upper bound while writing or reading
elements from an array. For example in num[100] the range of index is 0 to 99.

Word : It indicates the space required for an element. In each memory location, computer can store a data
piece. The space occupation varies from machine to machine. If the size of element is more than word (one
byte) then it occupies two successive memory locations. The variable of data type int, float, long need more
than one byte in memory.
1. The Declaration int a[5] is the creation of five variables of integer types
in memory. Instead of declaring five variables for five values, the
programmer.

2. All the elements of an array share the same name, and they are
distinguished from one another with the help of the element number.
3. The element number in an array plays a major role for calling each
element.
4. Any particular element of an array can be modified separately without
disturbing the other elements.
int a[5] = {1, 2, 3, 4, 5}
5. Any element of an array a[] can be assigned/equated to another
ordinary variable or array variable of its type.
6. An array elements are stored in contiguous memory
0 1 2 3 4
10 20 30 40 50
1000 1002 1004 1006 1008

7. Once the array is declared, its lowest boundary cannot be changed but upper
boundary can be expanded.
8. We know that an array name itself is a pointer. Though it is a pointer, it does not
need ‘*’ operator. The brackets “[]” automatically denote that the variable is a
pointer.
9. All the elements of an array share the same near, and they are distinguished
from one another with the help of the element number.
10. The amount of memory required for an array depends upon the data type and
the number of elements. The total size in bytes for a single dimensional array is
compared as shown below.
Total bytes = sizeof(data type) x size of array
8

6.4 Examples Using Arrays


• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
int n[ 5 ] = { 0 }
• All elements 0
– If too many a syntax error is produced syntax error
– C arrays have no bounds checking
• If size omitted, initializers determine it
int n[ ] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore 5 element array
• Initialization of an array – int a[5]
– Type of array variable is “integer”.
– Its variable name is a.
– 5 is the size of the array.
• The elements of an array are stored in
contiguous memory locations.
Element a[0] a[1] a[2] a[3] a[4]
Value 5 4 6 3 7
Address 2050 2052 2054 2056 2058
 Array index starts with zero
 The last index in an array is num – 1
where num is the no of elements in a array
 int a[9] is an array that stores 9 integers
index 0 1 2 3 4 5 6 7 8

elements

Memory address 100 102 104 106 108 110 112 114 116
• We can initialize the elements of arrays in the same way as
the ordinary variables when they are declared.
type array_name[size] = {list of values};
• For example,
int number[3] = {5,10,15};
float total[5] ={0.0, 15.75, -10.9};
• The size may be omitted. In such cases, the compiler allocates
enough space for all initialized elements.
int counter[] = {1,1,1,1};
• The character array may be initialized in the similar manner
char name[] = {‘v’,’i’,’k’,’a’,’s’,’\0’}; or
char name[] = “vikas”;
• An array can be explicitly initialized at run time.
void main()
{
MyArray[0]= 0
int MyArray[5],i;
MyArray[1]=10
for(i=0;i<5;i++) MyArray[2]=20
{ MyArray[3]=30
MyArray[i] = i * 10; MyArray[4]=40
}

}
• An array can be explicitly declared and initialized at the first time.
int main(int argc, char *argv[]) {
char name[]="TARKAN";
6 T
int i=0;
A
while(i<sizeof(name)) R
{ K
printf("%c\n",name[i]); A
i++; N
}
return 0;
}
Two - Dimensional Arrays
 What is a Two-dimensional array?
Array type Array name
Array dimension = 2
51, 52, 53 Row 1
B= Int b[2][3] = {{51, 52, 53},{54, 55, 56}};
54, 55, 56 Row 2

Two rows First row second row

Col 1 Col 2 Col 3


Three columns

Algebraic notation C notation


Indexes in 2D arrays
 Assume that the two dimensional array called val is
declared and looks like the following:
Val First Col Second Col Third Col Fourth Col

First Row 8 16 9 52

Second Row 3 15 27 6

Third Row 14 25 2 10

 To access the cell containing 6, In C notation ?


we reference val[1][3], that is, row 2, column 4.
16
DECLARATION
 How to declare a multidimensional array?
int b[2][3];

the name of the array to be b


the type of the array elements to be int
the dimension to be 2 (two pairs of brackets [])
the number of elements or size to be 2*3 = 6
INITIALIZATION
 How to initialize a Two-Dimensional array?
 Initialized directly in the declaration statement
 int b[2][3] = {51, 52, 53, 54, 55, 56};

 b[0][0] = 51 b[0][1] = 52 b[0][2] = 53

 Use braces to separate rows in 2-D arrays.


 int c[4][3] = {{1, 2, 3},

{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
 int c[ ][3] = {{1, 2, 3},

{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
Implicitly declares the number of rows to be 4.
Input of Two-Dimensional Arrays

 Data may be input into two-dimensional


arrays using nested for loops interactively
or with data files.
 A nested for loop is used to input elements
in a two dimensional array.
 In this way by increasing the index value of
the array the elements can be entered in a
2d array.
Output of Two-Dimensional Arrays

 The output of two-dimensional arrays should


be in the form of rows and columns for
readability. Nested for loops are used to print
the rows and columns in row and column order.

 By increasing the index value of the array the


elements stored at that index value are printed
on the output screen.
A program to input elements in a two dimensional array and print it.
#include<stdio.h>
An array with 3 rows and 3
#include<conio.h> columns
void main()
{ Display an int right justified in
int a[3][3]; a five character space
int i,j;
printf(“enter the elements in the array:”);
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++) Set elements at
{
scanf(“%d”,&a[i][j]);
locations
}
}
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
printf(“%5d”,a[i][j]);
}
printf(“\n”);
}
• C allows arrays of three or more dimensions.
The exact limit is determined by the compiler.
• The general form of a multi-dimensional array
type array_name[s1][s2][s3]…[sm];
• Where si is the size of ith dimension.
• For exmaple
int MyArray[2][3][4];
0,0 0,1 0, 2 0,3
1,0 1,1 1,2 1,3
0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
Example-1
 Write a program in C that calculates the average exam
grade for a class of 10 students.
 Note That:
 You must only use WHILE loop.
 You must declare an array called as “grd” for the inputs.
 You must declare a variable called as “avr” with data type of
double that includes the average value.
 Display the average value with two decimal places.
 The output is like below for example:
 “The Average of ten grades is 36.45”
Answer for Example-1
int main(int argc, char *argv[]) {
int i=0,grd[10],sum=0;
double avr;
while(i<10)
{
printf("Enter the grade %d=",i+1);
scanf("%d",&grd[i]);
sum+=grd[i];
i++;
}
avr=sum/10.0;
printf("The Average of ten grades is %.2f",avr);
return 0;
}
Example-2
• Write a C program to print the transpose of the given matrix.
• The matrix mat is given as follow:
1 2 3
𝑚𝑎𝑡 =
4 5 6
• The matrix mat is declared in the main function.
• Use a function called as “TRNSPS”
• In the function “TRNSPS”, you must use three variables at
most except for the argument of the function.
• The transpose of the matrix is shown in the function TRNSPS.
• You must use only the FOR loop in function TRNSPS
Answer-2 void TRNSPS(int [][3]);
Prototype of the
Function
int main(int argc, char *argv[]) {
void TRNSPS(int matx[][3]) int mat[][3]={1,2,3,4,5,6};
{
TRNSPS(mat);
int i,j,trnmat[3][2];
for(i=0;i<2;i++)
return 0;
Dclare and initialize
{ } the array mat
for(j=0;j<3;j++)
{
trnmat[j][i]=matx[i][j];
} Body of the
}
function
for(i=0;i<3;i++) TRNSPS
{
for(j=0;j<2;j++)
{
printf("%3d",trnmat[i][j]);
}
printf("\n");
}
}
27
EXAMPLE For Mid-Term Exam
• Write a source code in C to find the smallest element in an
array. Note That:
• Define an array called as “arr” with size of 50 (max).
• The array elements and array size are entered by the user.
• You must use only do-while loop for both inputs and
finding the smallest element.
• Define a function called as “FindingSmall” that finds the
smallest element of a given array and display the smallest
element like :” The smallest element among 49 55 25 36 85
is 25”
• The function has only one parameter or argument.
ANSWER For Mid-Term Exam
void FindingSmall(int []);

int main(int argc, char *argv[]) {


int sz,arr[50],i;
printf("Enter size of the array=");scanf("%d",&sz);
i=0;
do {
printf("Enter The Element=");scanf("%d",&arr[i]);
i++;
}while(i<sz);

FindingSmall(arr);
return 0;
}

void FindingSmall(int Farr[])


{
0 1 2 3 4
int j,small; 56 3 12 5 9
small=Farr[0];
j=1;
do
{
if(Farr[j]<small){ small=Farr[j];}
j++;
}while(Farr[j]!='\0’);

printf("The smallest element among ");j=0;do{printf("%d ",Farr[j]);j++;}while(Farr[j]!='\0');


printf(" is %d",small);
}
The Bubble Sort
 An easy way to arrange data in ascending or
descending order.
 Pseudocode:
Do
Set count variable to 0
For count is set to each subscript in Array from 0 to the next-to-last subscript
If array[count] is greater than array[count+1]
swap them
set swap flag to true
end if
End for
While any elements have been swapped.

30
Question-1

• Write a source code in C to sort the array in ascending order


• You must use only FOR loop.
• You must use only one array variable
• The array arr is given as the following: arr=[8 7 4 1];
Answer for Question-1
int main(int argc, char *argv[]) { Set the initial value of the array
int temp, i, j a[4]={3,7,4,1};
for(i=0;i<4;i++)
{ printf("%5d",a[i]);
Display the values of the array
}
for(i=0;i<4;i++)
{
for(j=i+1;j<4;j++)
Sorting the values of the array
{ in ascending order
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
} Display the values of the array
} in ascending order
for(i=0;i<4;i++)
{ printf("%4d",a[i]); } 32

return 0;
Question-2
• Write a C program to give the length of the text from the keyboard.
• Declare an array called as txt that is set the size as 50.
• Use a function called as findlen that calculates the length of
the given text.
• You must use do-while loop in the function findlen.
• The function has only one parameter and only one variable
must be used in the function.
• You must use only one variable in the function main()
• In the main program, the output is like below:
Answer for Question-2
int findlen(char []);
int main(int argc, char *argv[]) { Declaration an array
char txt[50];
scanf("%s",txt);
Input the values of the array

printf("\n\nThe length of %s= %d ",txt,findlen(txt));


return 0;
}
Find the length of the input
array
int findlen(char arr[])
{
int j;
j=0;
do
{
j++;
}
while(arr[j]!='\0');
return j; 34

}
Question-3
 Write a C program to sort elements of the array in
descending order.
 Note That:
 Declare an array called as “arr” with 100.
 Read the elements of the array from the user using the Do-While
loop.
 Declare and initialize a sentinel value called as “senval” with “-99”
with global.
 You must NOT declare the variables more than four variables
except for “senval”.
 If the user wish to exit the loop, the user has to input the sentinel
value you defined before.
 You must only use For loop for both of sorting the elements of the
array and display the sorted array in descending order .
 The output is like below for example:
Answer for Question-3

You might also like