SlideShare una empresa de Scribd logo
1 de 6
Descargar para leer sin conexión
Arrays & its Types Intro to Programming
MUHAMMAD HAMMAD WASEEM 1
What are Arrays
For understanding the arrays properly, let us consider the following program:
main( )
{
int x ;
x = 5 ;
x = 10 ;
printf ( "nx = %d", x ) ;
}
No doubt, this program will print the value of x as 10. Why so? Because when a value 10 is assigned
to x, the earlier value of x, i.e. 5, is lost. Thus, ordinary variables (the ones which we have used so far)
are capable of holding only one value at a time (as in the above example). However, there are
situations in which we would want to store more than one value at a time in a single variable.
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.
Obviously, the second alternative is better. A simple reason for this is, it would be much easier to
handle one variable than handling 100 different variables. Moreover, there are certain logics that
cannot be dealt with, without the use of an array. Now a formal definition of an 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’. 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 }
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.
An array is a collection of similar elements which 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. Remember that 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.
A Simple Program Using Array
Let us try to write a program to find average marks obtained by a class of 30 students in a test.
main( )
{
int avg, sum = 0 ;
Arrays & its Types Intro to Programming
MUHAMMAD HAMMAD WASEEM 2
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. 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.
Accessing Elements of an Array
Once an array is declared, let’s see how 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
Arrays & its Types Intro to Programming
MUHAMMAD HAMMAD WASEEM 3
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, just as we have used it earlier on other variables (&rate, for example). In so doing, we are
passing the address of this particular array element to the scanf( ) function, rather than its value; which
is what scanf( ) requires.
Reading Data from an Array
The balance of the program reads the data back out of the array and uses it to calculate the
average. The for loop is much the same, but now the body of the loop causes each student’s marks to
be added to a running total stored in a variable called sum. When all the marks have been added up,
the result is divided by 30, the number of students, to get the average.
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ;
avg = sum / 30 ;
printf ( "nAverage marks = %d", avg ) ;
To fix our ideas, let us revise whatever we have learnt about arrays:
a) An array is a collection of similar elements.
b) The first element in the array is numbered 0, so the last element is 1 less than the size of
the array.
c) An array is also known as a subscripted variable.
d) Before using an array its type and dimension must be declared.
e) However big an array its elements are always stored in contiguous memory locations. This is
a very important point which we would discuss in more detail later on.
Array Initialization
So far we have used arrays that did not have any values in them to begin with. We managed to
store values in them during program execution. Let us now see how to initialize an array while
declaring it. Following are a few examples that demonstrate this.
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
Note the following points carefully:
a) Till the array elements are not given any specific values, they are supposed to contain
garbage values.
b) If the array is initialized where it is declared, mentioning the dimension of the array is
optional as in the 2nd example above.
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. And since the array is not being initialized, all eight values
Arrays & its Types Intro to Programming
MUHAMMAD HAMMAD WASEEM 4
present in it would be garbage values. Whatever be the initial values, all the array elements would
always be present in contiguous memory locations. This arrangement of array elements in memory is
shown below.
Passing Array Elements to a Function
Array elements can be passed to a function by calling the function by value, or by reference. In the
call by value we pass values of array elements to the function, whereas in the call by reference we pass
addresses of array elements to the function. These two calls are illustrated below:
/* Demonstration of call by value */
main( )
{
int i ;
int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
display ( marks[i] ) ;
}
display ( int m )
{
printf ( "%d ", m ) ;
}
And here’s the output...
55 65 75 56 78 78 90
Here, we are passing an individual array element at a time to the function display( ) and getting it
printed in the function display( ). Note that since at a time only one element is being passed, this
element is collected in an ordinary integer variable m, in the function display( ).
/* Demonstration of call by reference */
main( )
{
int i ; int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ;
for ( i = 0 ; i <= 6 ; i++ )
disp ( &marks[i] ) ;
}
disp ( int *n )
{
printf ( "%d ", *n ) ;
}
And here’s the output...
55 65 75 56 78 78 90
Here, we are passing addresses of individual array elements to the function display( ). Hence, the
variable in which this address is collected (n) is declared as a pointer variable. And since n contains the
Arrays & its Types Intro to Programming
MUHAMMAD HAMMAD WASEEM 5
address of array element, to print out the array element we are using the ‘value at address’ operator
(*).
Passing an Entire Array to a Function
In the previous section we saw two programs—one in which we passed individual elements of an
array to a function, and another in which we passed addresses of individual elements to a function. Let
us now see how to pass an entire array to a function rather than its individual elements. Consider the
following example:
/* Demonstration of passing an entire array to a function */
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
dislpay ( &num[0], 6 ) ;
}
display ( int *j, int n )
{
int i ;
for ( i = 0 ; i <= n - 1 ; i++ )
{
printf ( "nelement = %d", *j ) ;
j++ ; /* increment pointer to point to next element */
}
}
Here, the display( ) function is used to print out the array elements. Note that the address of the
zeroth element is being passed to the display( ) function. The for loop is same as the one used in the
earlier program to access the array elements using pointers. Thus, just passing the address of the
zeroth element of the array to a function is as good as passing the entire array to the function. It is also
necessary to pass the total number of elements in the array, otherwise the display( ) function would
not know when to terminate the for loop. Note that the address of the zeroth element (many a times
called the base address) can also be passed by just passing the name of the array. Thus, the following
two function calls are same:
display ( &num[0], 6 ) ;
display ( num, 6 ) ;
Two Dimensional Arrays
So far we have explored arrays with only one dimension. It is also possible for arrays to have two or
more dimensions. The two-dimensional array is also called a matrix.
Here is a sample 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++ )
Arrays & its Types Intro to Programming
MUHAMMAD HAMMAD WASEEM 6
{
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.
In stud[i][0] and stud[i][1] the first subscript of the variable stud, is row number which changes for
every student. The second subscript tells which of the two columns are we talking about—the zeroth
column which contains the roll no. or the first column which contains the marks. Remember the
counting of rows and columns begin with zero. The complete array arrangement is shown below.
Thus, 1234 is stored in stud[0][0], 56 is stored in stud[0][1] and so on. The above arrangement
highlights the fact that a two- dimensional array is nothing but a collection of a number of one-
dimensional arrays placed one below the other.
In our sample program the array elements have been stored row wise and accessed row wise.
However, you can access the array elements column wise as well. Traditionally, the array elements are
being stored and accessed row wise; therefore we would also stick to the same strategy.
Initializing a 2-Dimensional Array
How do we initialize a two-dimensional array? As simple as this...
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.

Más contenido relacionado

La actualidad más candente

[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of PrecedenceMuhammad Hammad Waseem
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)SURBHI SAROHA
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)SURBHI SAROHA
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4Saranya saran
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and stringsRai University
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
C standard library functions
C standard library functionsC standard library functions
C standard library functionsVaishnavee Sharma
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2Amit Kapoor
 

La actualidad más candente (20)

[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
Diploma ii cfpc u-4 function, storage class and array and strings
Diploma ii  cfpc u-4 function, storage class and array and stringsDiploma ii  cfpc u-4 function, storage class and array and strings
Diploma ii cfpc u-4 function, storage class and array and strings
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
Arrays
ArraysArrays
Arrays
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 

Similar a [ITP - Lecture 15] Arrays & its Types

Similar a [ITP - Lecture 15] Arrays & its Types (20)

Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 
Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Array assignment
Array assignmentArray assignment
Array assignment
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
Module7
Module7Module7
Module7
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Arrays
ArraysArrays
Arrays
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 

Más de Muhammad Hammad Waseem

[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++Muhammad Hammad Waseem
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)Muhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of ProgrammingMuhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming LanguagesMuhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnTypeMuhammad Hammad Waseem
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their AccessingMuhammad Hammad Waseem
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)Muhammad Hammad Waseem
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOPMuhammad Hammad Waseem
 

Más de Muhammad Hammad Waseem (20)

[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms
 
[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP
 
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
 

Último

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Último (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 

[ITP - Lecture 15] Arrays & its Types

  • 1. Arrays & its Types Intro to Programming MUHAMMAD HAMMAD WASEEM 1 What are Arrays For understanding the arrays properly, let us consider the following program: main( ) { int x ; x = 5 ; x = 10 ; printf ( "nx = %d", x ) ; } No doubt, this program will print the value of x as 10. Why so? Because when a value 10 is assigned to x, the earlier value of x, i.e. 5, is lost. Thus, ordinary variables (the ones which we have used so far) are capable of holding only one value at a time (as in the above example). However, there are situations in which we would want to store more than one value at a time in a single variable. 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. Obviously, the second alternative is better. A simple reason for this is, it would be much easier to handle one variable than handling 100 different variables. Moreover, there are certain logics that cannot be dealt with, without the use of an array. Now a formal definition of an 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’. 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 } 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. An array is a collection of similar elements which 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. Remember that 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. A Simple Program Using Array Let us try to write a program to find average marks obtained by a class of 30 students in a test. main( ) { int avg, sum = 0 ;
  • 2. Arrays & its Types Intro to Programming MUHAMMAD HAMMAD WASEEM 2 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. 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. Accessing Elements of an Array Once an array is declared, let’s see how 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
  • 3. Arrays & its Types Intro to Programming MUHAMMAD HAMMAD WASEEM 3 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, just as we have used it earlier on other variables (&rate, for example). In so doing, we are passing the address of this particular array element to the scanf( ) function, rather than its value; which is what scanf( ) requires. Reading Data from an Array The balance of the program reads the data back out of the array and uses it to calculate the average. The for loop is much the same, but now the body of the loop causes each student’s marks to be added to a running total stored in a variable called sum. When all the marks have been added up, the result is divided by 30, the number of students, to get the average. for ( i = 0 ; i <= 29 ; i++ ) sum = sum + marks[i] ; avg = sum / 30 ; printf ( "nAverage marks = %d", avg ) ; To fix our ideas, let us revise whatever we have learnt about arrays: a) An array is a collection of similar elements. b) The first element in the array is numbered 0, so the last element is 1 less than the size of the array. c) An array is also known as a subscripted variable. d) Before using an array its type and dimension must be declared. e) However big an array its elements are always stored in contiguous memory locations. This is a very important point which we would discuss in more detail later on. Array Initialization So far we have used arrays that did not have any values in them to begin with. We managed to store values in them during program execution. Let us now see how to initialize an array while declaring it. Following are a few examples that demonstrate this. int num[6] = { 2, 4, 12, 5, 45, 5 } ; int n[ ] = { 2, 4, 12, 5, 45, 5 } ; float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ; Note the following points carefully: a) Till the array elements are not given any specific values, they are supposed to contain garbage values. b) If the array is initialized where it is declared, mentioning the dimension of the array is optional as in the 2nd example above. 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. And since the array is not being initialized, all eight values
  • 4. Arrays & its Types Intro to Programming MUHAMMAD HAMMAD WASEEM 4 present in it would be garbage values. Whatever be the initial values, all the array elements would always be present in contiguous memory locations. This arrangement of array elements in memory is shown below. Passing Array Elements to a Function Array elements can be passed to a function by calling the function by value, or by reference. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function. These two calls are illustrated below: /* Demonstration of call by value */ main( ) { int i ; int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ; for ( i = 0 ; i <= 6 ; i++ ) display ( marks[i] ) ; } display ( int m ) { printf ( "%d ", m ) ; } And here’s the output... 55 65 75 56 78 78 90 Here, we are passing an individual array element at a time to the function display( ) and getting it printed in the function display( ). Note that since at a time only one element is being passed, this element is collected in an ordinary integer variable m, in the function display( ). /* Demonstration of call by reference */ main( ) { int i ; int marks[ ] = { 55, 65, 75, 56, 78, 78, 90 } ; for ( i = 0 ; i <= 6 ; i++ ) disp ( &marks[i] ) ; } disp ( int *n ) { printf ( "%d ", *n ) ; } And here’s the output... 55 65 75 56 78 78 90 Here, we are passing addresses of individual array elements to the function display( ). Hence, the variable in which this address is collected (n) is declared as a pointer variable. And since n contains the
  • 5. Arrays & its Types Intro to Programming MUHAMMAD HAMMAD WASEEM 5 address of array element, to print out the array element we are using the ‘value at address’ operator (*). Passing an Entire Array to a Function In the previous section we saw two programs—one in which we passed individual elements of an array to a function, and another in which we passed addresses of individual elements to a function. Let us now see how to pass an entire array to a function rather than its individual elements. Consider the following example: /* Demonstration of passing an entire array to a function */ main( ) { int num[ ] = { 24, 34, 12, 44, 56, 17 } ; dislpay ( &num[0], 6 ) ; } display ( int *j, int n ) { int i ; for ( i = 0 ; i <= n - 1 ; i++ ) { printf ( "nelement = %d", *j ) ; j++ ; /* increment pointer to point to next element */ } } Here, the display( ) function is used to print out the array elements. Note that the address of the zeroth element is being passed to the display( ) function. The for loop is same as the one used in the earlier program to access the array elements using pointers. Thus, just passing the address of the zeroth element of the array to a function is as good as passing the entire array to the function. It is also necessary to pass the total number of elements in the array, otherwise the display( ) function would not know when to terminate the for loop. Note that the address of the zeroth element (many a times called the base address) can also be passed by just passing the name of the array. Thus, the following two function calls are same: display ( &num[0], 6 ) ; display ( num, 6 ) ; Two Dimensional Arrays So far we have explored arrays with only one dimension. It is also possible for arrays to have two or more dimensions. The two-dimensional array is also called a matrix. Here is a sample 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++ )
  • 6. Arrays & its Types Intro to Programming MUHAMMAD HAMMAD WASEEM 6 { 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. In stud[i][0] and stud[i][1] the first subscript of the variable stud, is row number which changes for every student. The second subscript tells which of the two columns are we talking about—the zeroth column which contains the roll no. or the first column which contains the marks. Remember the counting of rows and columns begin with zero. The complete array arrangement is shown below. Thus, 1234 is stored in stud[0][0], 56 is stored in stud[0][1] and so on. The above arrangement highlights the fact that a two- dimensional array is nothing but a collection of a number of one- dimensional arrays placed one below the other. In our sample program the array elements have been stored row wise and accessed row wise. However, you can access the array elements column wise as well. Traditionally, the array elements are being stored and accessed row wise; therefore we would also stick to the same strategy. Initializing a 2-Dimensional Array How do we initialize a two-dimensional array? As simple as this... 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.