SlideShare a Scribd company logo
Principles of Programming
Lecture 6: Arrays
 In this chapter, you will learn about
 Introduction to Array
 Array declaration
 Array initialization
 Assigning values to array elements
 Reading values from array elements
 Relationship with pointers
 Passing array to function
 2 Dimensional arrays
1
NI S1 2009/10
Principles of Programming
Introduction to Array
 In C, a group of items of the same type can be set up
using Array
 An array is a group of consecutive memory locations
related by the fact that they all have the same name
and the same type.
 The compiler must reserve storage (space) for each
element/item of a declared array.
 The size of an array is static (fixed) throughout
program execution.
 To refer to a particular location or element in the
array, we specify the name of the array and its index
(the position number of the particular element in the
array).
2
Principles of Programming
3
-10
99
-8
100
27
10
1976
-2020
1
Let say we have an array called a.
a[0]
a[1]
a[2]
a[3]
a[4]
a[5]
a[6]
a[7]
a[8]
Name of the array
The position number within
the square brackets is formally
called a subscript. A subscript
can be an integer or an integer
expression. For example if
x = 1 and y = 2, then a[x+y]
is equal to a[3].
Notice that the position
starts from 0.
Principles of Programming
Array Declaration
 Array declaration is made by specifying the data type,
it’s name and the number of space (size) so that the
computer may reserve the appropriate amount of
memory.
 General syntax:
data_type array_name[size];
 Examples:
 int my_array[100];
 char name[20];
 double bigval[5*200];
 int a[27], b[10], c[76];
4
Principles of Programming
Array Initialization
 There are 2 ways to initialize an array: during compilation
and during execution.
 During compilation:
 int arr[ ] = {1, 2, 3, 4, 5};
 Unsized array : We can define how many elements that we
want since the array size is not given.
 int arr[3] = {90, 21, 22};
 We can define only 3 elements since the array size is already
given.
 int arr[5] = {2,4};
 Initialize the first two elements to the value of 2 and 4
respectively, while the other elements are initialized to zero.
 int arr[5] = {0};
 Initialize all array elements to zero.
5
Principles of Programming
Array Initialization cont…
 During execution:
 Using loop to initialize all elements to zero
int arr[3], index;
for (index = 0; index < 3; index++)
arr[index] = 0;
 Using loop and asking the user to specify the value
for each element.
int arr[3], index;
for (index = 0; index < 3; index++)
{
printf (“Enter number:n”);
scanf(“%d”,&arr[index]);
}
6
Principles of Programming
Assigning value to array element
 We can assign a value to a specific array element by using
its index number.
 Example: let’s say we have an array that represent the
number of inhabitant in 5 unit apartments.
int apartment[5]={3,2,6,4,5};
 The above initialization indicates that there are 3 people
living in apartment 0, 2 people living in apartment 1 and
so on.
 Let say that we have a new born in apartment 3, so we
need to change the number of inhabitant living in
apartment three.
apartment[3] = apartment[3] + 1;
 Now, we have the following values in our array:
7
3 2 6 5 5
[0] [1] [2] [3] [4]
apartment
Principles of Programming
Reading values from array elements
 We can read a value from a specific array element by referring to
the index.
 For example, let’s say we want to know how many people leaving
in apartment 3, we could simple do this:
int apartment[5] = {3,2,6,4,5};
int no_of_people;
no_of_people = apartment[3];
printf(“Apartment 3 has %d people”,no_of_people);
 The above C code will produce the following output:
8
Hint!!! Remember that array’s index starts at 0
Apartment 3 has 4 people
Press any key to continue
Principles of Programming
Example 1: finding total inhabitants
#include <stdio.h>
#define size 5
int main(void)
{
int apartment[size] = {3,2,6,4,5};
int index, total = 0;
for (index = 0; index < size; index++)
{
total = total + apartment[index];
}
printf("There are total of %d inhabitants",total);
return(0);
}
9
There are total of 20 inhabitants
Press any key to continue
Principles of Programming
Example 2: list down number of inhabitants in each apartment
#include <stdio.h>
int main(void)
{
int apartment[5] = {3,2,6,4,5};
int index, total = 0;
printf("%-7s %-15sn","Apt No", "No of people");
for (index = 0; index < 5; index++)
{
printf("%4d %10dn",index,
apartment[index]);
}
return(0);
}
10
Apt No No of people
0 3
1 2
2 6
3 4
4 5
Press any key to continue
Principles of Programming
Passing Array to a Function
 When we pass an array to a function, we are actually
passing the reference (address) of the first element in
the array to the function. Therefore, any changes to
the array inside the function will also change the
actual array inside the calling function.
 When we want to pass an array to a function, we
need to know these 3 things.
 How to write the function prototype?
 How to do function call?
 How does the function header would look like?
11
Principles of Programming
Passing Array to a Function
 Assume that we have the following array declaration.
float marks[10] = {0.0};
 Say for example we want to write a function, called get_marks, which will
read marks from the user and store the marks inside the array.
 Function prototype:
/* data type with square bracket */
void get_marks(float [ ]);
 Function call:
get_marks(marks); /* just pass the array name */
 Function header:
void get_marks(float marks[ ])
12
Principles of Programming
Example: passing array to a function
13
#include <stdio.h>
#define size
void get_marks(float [ ]);
float calc_average(float [ ]);
int main(void)
{
float marks[size] = {0.0}; /*initializing the array
get_marks(marks); /* function call */
printf(“Average for marks given is %.2f”, calc_average(marks));
return(0);
}
void get_marks(float marks[ ]) /* reading the marks from the users */
{
int i;
for (i = 0; i < size; i++)
{
printf("Marks for student %d:",i + 1);
scanf("%f",&marks[i]);
}
}
float calc_average(float marks[ ])
{
float total = 0.0;
int i;
for (i = 0; i < size; i++)
{
total = total + marks[i];
}
return (total / size);
}
Marks for student 1: 56
Marks for student 2: 96
Marks for student 3: 78
Marks for student 4: 35
Marks for student 5: 66
Average for marks given is 66.2
Press any key to continue
Example: Passing Array to a Function
Principles of Programming
2-Dimensional Array
 It is possible to create an array which has more than
one dimension.
 For example:
 2D array: int array[4][2];
 3D array: int array[4][2][10];
 Graphical representation of a 2D array:
14
int myarray[4][2] = {1,2,3,4,5,6,7,8};
1 2
3 4
5 6
7 8
This array has 4 rows and 2 columns.
Col 1 Col2
Row 1
Row 2
Row 3
Row 4
Principles of Programming
2-Dimensional Array cont…
 Variable initialization can also be done this way:
int myarray[4][2] = {{1,2},{3,4},{5,6},{7,8}};
 This method is less confusing since we can see the rows and columns division
more clearly.
 To initialize a 2D array during execution, we need to use a nested for loop:
int row, column
for (row = 0; row < 4; row++)
{
for (column = 0; column < 2; column++)
{
myarray[row][column] = row+column;
}
}
 Although it is possible to create a multi-dimensional array, arrays above 2-
dimensions are rarely used.
15
Principles of Programming
Passing a 2D array to a function
 When a 2D (or higher dimensional) array is passed to
a function, the size of the second (or subsequent)
subscript needs to be specified.
 For example, if we have:
int twoD[4][5];
 Then the function header which would take twoD as an
argument should be declared like this:
void Process2D(int twoD[ ][5])
 An array is stored consecutively in memory regardless
of the number of dimensions. Therefore, specifying
the subscripts in the function parameter will help the
compiler to know the boundary of the different
dimensions.
16
Principles of Programming
Summary
 In this chapter, we have looked at:
 Array declaration and initialization
 Reading and writing from/to array
elements
 Passing array to function
 2 dimensional array
17
Principles of Programming
Exercise
Assume the following array declaration
float number[5] = {2.3, 4.2, 5.0, 7.9, 6.2};
What will be the output of the following statement?
a)printf(“%f”, number[2+2] );
b)printf(“%f”, number[2]+2 );
c)printf(“%f”, number[1*2] );
d)printf(“%f”, number[1]*2 );
18
Principles of Programming
Exercise
Assume the following array declaration
int result[5] = {56, 69, 89};
int i = 2;
What will be the output of the following statement?
a)printf(“%d”, result[1]);
b)printf(“%d”, result[4]);
c)printf(“%d”, result[0] + result[1]);
d)printf(“%d %d”, i, result[i]);
19
Principles of Programming
Exercise
Assume the following array declaration
int result[3*2];
a) Write C statements that would read the values for the array
element from the user.
b) Write C statements that would list down all the values in
the array.
c) Write C statements that would sum up all the values in the
array.
Rewrite the above task as separate function!!
20

More Related Content

PPT
Basics of Data structure using C describing basics concepts
shanthidl1
 
PPTX
Ch-11-Arrays.ppt-1.pptx eurhrbdhdbdhrhdhdh
zakiking612
 
PDF
arraysfor engineering students sdf ppt on arrays
ruvirgandhi123
 
PPTX
ARRAY OF STRUCTURESengingeeringtech.pptx
ricknova674
 
PPTX
Unit 3
GOWSIKRAJAP
 
PPT
358 33 powerpoint-slides_5-arrays_chapter-5
sumitbardhan
 
PDF
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
Basics of Data structure using C describing basics concepts
shanthidl1
 
Ch-11-Arrays.ppt-1.pptx eurhrbdhdbdhrhdhdh
zakiking612
 
arraysfor engineering students sdf ppt on arrays
ruvirgandhi123
 
ARRAY OF STRUCTURESengingeeringtech.pptx
ricknova674
 
Unit 3
GOWSIKRAJAP
 
358 33 powerpoint-slides_5-arrays_chapter-5
sumitbardhan
 
Programming Fundamentals Arrays and Strings
imtiazalijoono
 

Similar to Arrays in c programing. practicals and .ppt (20)

PDF
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
PPTX
Array and functions
Aneesh Pavan Prodduturu
 
PPTX
Arrays.pptx
saimasiddique11
 
PPTX
Arrays
shillpi29
 
PPTX
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
AbhimanyuChaure
 
PPTX
Arrays
RaziyasultanaShaik
 
PPTX
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
PPT
Chapter 10.ppt
MithuBose3
 
PDF
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
PDF
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
PPS
C programming session 05
Vivek Singh
 
PDF
Array&amp;string
chanchal ghosh
 
PDF
C_Program_Yr1[1].pdf for computer science
ibrahimsoryjalloh91
 
PPTX
PASSING ONE DIMENSIONAL ARRAY AS ARGUMENT PPT.pptx
Arjunkrish9
 
PPTX
Array
HarshKumar943076
 
PDF
11 1. multi-dimensional array eng
웅식 전
 
PPTX
Unit 3
GOWSIKRAJAP
 
PPT
Arrays
Saranya saran
 
PPTX
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
PPT
array.ppt
DeveshDewangan5
 
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
Array and functions
Aneesh Pavan Prodduturu
 
Arrays.pptx
saimasiddique11
 
Arrays
shillpi29
 
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
AbhimanyuChaure
 
Module_3_Arrays - Updated.pptx............
ChiragKankani
 
Chapter 10.ppt
MithuBose3
 
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
C programming session 05
Vivek Singh
 
Array&amp;string
chanchal ghosh
 
C_Program_Yr1[1].pdf for computer science
ibrahimsoryjalloh91
 
PASSING ONE DIMENSIONAL ARRAY AS ARGUMENT PPT.pptx
Arjunkrish9
 
11 1. multi-dimensional array eng
웅식 전
 
Unit 3
GOWSIKRAJAP
 
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
array.ppt
DeveshDewangan5
 
Ad

More from Carlos701746 (20)

PPTX
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
Carlos701746
 
PPTX
Draw the flowchart of the above algorithm.pptx
Carlos701746
 
PPTX
BUSINESS ETHICS IN COMPUTING FUNDAMENTALS .pptx
Carlos701746
 
PPT
Professional Ethics Overview IN computing.ppt
Carlos701746
 
PPTX
installingoperatingsy XP Installing Operating System.pptx
Carlos701746
 
PPT
Topic 1 B C programming exercises one.ppt
Carlos701746
 
PPT
Recursion C programming exercises_ Recursion - w3resource.ppt
Carlos701746
 
PPTX
Transaction processing system in BICTPS.pptx
Carlos701746
 
PPTX
MANAGEMENT INFORMATION SYSTEMS FOR MANAGEMENT DECISION MAKING.pptx
Carlos701746
 
PPTX
USE COMPUTER FUNDAMETALS TO IDENTIFY TYPES AND FUNCTIONS OF A COMPUTER SOFTWA...
Carlos701746
 
PPTX
Updated_Lighting_Device_Control_System.pptx
Carlos701746
 
PPTX
Architecture Software Interface for students.pptx
Carlos701746
 
PDF
KA 5 - Lecture 1 - Parallel Processing.pdf
Carlos701746
 
PPTX
PPt Sets and Venn diagrams in discrete maths.pptx
Carlos701746
 
PPTX
Part Four The CPU architecture in .pptx
Carlos701746
 
PDF
OIT 116 LOOPS AND CONDITION STATEMENTS.pdf
Carlos701746
 
PPT
OIT 116 - Lecture 3_2 Arrays, Pointers and Strings (1) (1).ppt
Carlos701746
 
PPTX
IT Ethical Practices and Compliance.pptx
Carlos701746
 
PPTX
Network_Protocals in IT fundamentals .pptx
Carlos701746
 
PPTX
ARTHEMATIC OPERATIONS IN C PROGRAMING.pptx
Carlos701746
 
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
Carlos701746
 
Draw the flowchart of the above algorithm.pptx
Carlos701746
 
BUSINESS ETHICS IN COMPUTING FUNDAMENTALS .pptx
Carlos701746
 
Professional Ethics Overview IN computing.ppt
Carlos701746
 
installingoperatingsy XP Installing Operating System.pptx
Carlos701746
 
Topic 1 B C programming exercises one.ppt
Carlos701746
 
Recursion C programming exercises_ Recursion - w3resource.ppt
Carlos701746
 
Transaction processing system in BICTPS.pptx
Carlos701746
 
MANAGEMENT INFORMATION SYSTEMS FOR MANAGEMENT DECISION MAKING.pptx
Carlos701746
 
USE COMPUTER FUNDAMETALS TO IDENTIFY TYPES AND FUNCTIONS OF A COMPUTER SOFTWA...
Carlos701746
 
Updated_Lighting_Device_Control_System.pptx
Carlos701746
 
Architecture Software Interface for students.pptx
Carlos701746
 
KA 5 - Lecture 1 - Parallel Processing.pdf
Carlos701746
 
PPt Sets and Venn diagrams in discrete maths.pptx
Carlos701746
 
Part Four The CPU architecture in .pptx
Carlos701746
 
OIT 116 LOOPS AND CONDITION STATEMENTS.pdf
Carlos701746
 
OIT 116 - Lecture 3_2 Arrays, Pointers and Strings (1) (1).ppt
Carlos701746
 
IT Ethical Practices and Compliance.pptx
Carlos701746
 
Network_Protocals in IT fundamentals .pptx
Carlos701746
 
ARTHEMATIC OPERATIONS IN C PROGRAMING.pptx
Carlos701746
 
Ad

Recently uploaded (20)

PPTX
Economic Sector Performance Recovery.pptx
yulisbaso2020
 
PDF
Technical Writing Module-I Complete Notes.pdf
VedprakashArya13
 
PDF
Company Profile 2023 PT. ZEKON INDONESIA.pdf
hendranofriadi26
 
PDF
Data_Cleaning_Infographic_Series_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PPTX
Measurement of Afordability for Water Supply and Sanitation in Bangladesh .pptx
akmibrahimbd
 
PPTX
Extract Transformation Load (3) (1).pptx
revathi148366
 
PPTX
Data Security Breach: Immediate Action Plan
varmabhuvan266
 
PPTX
Analysis of Employee_Attrition_Presentation.pptx
AdawuRedeemer
 
PPTX
lecture 13 mind test academy it skills.pptx
ggesjmrasoolpark
 
PPTX
Decoding Physical Presence: Unlocking Business Intelligence with Wi-Fi Analytics
meghahiremath253
 
PDF
Company Presentation pada Perusahaan ADB.pdf
didikfahmi
 
PPTX
1intro to AI.pptx AI components & composition
ssuserb993e5
 
PPTX
artificial intelligence deeplearning-200712115616.pptx
revathi148366
 
PDF
345_IT infrastructure for business management.pdf
LEANHTRAN4
 
PPTX
The whitetiger novel review for collegeassignment.pptx
DhruvPatel754154
 
PDF
The_Future_of_Data_Analytics_by_CA_Suvidha_Chaplot_UPDATED.pdf
CA Suvidha Chaplot
 
PDF
oop_java (1) of ice or cse or eee ic.pdf
sabiquntoufiqlabonno
 
PPTX
Future_of_AI_Presentation for everyone.pptx
boranamanju07
 
PPTX
Pipeline Automatic Leak Detection for Water Distribution Systems
Sione Palu
 
PPTX
Probability systematic sampling methods.pptx
PrakashRajput19
 
Economic Sector Performance Recovery.pptx
yulisbaso2020
 
Technical Writing Module-I Complete Notes.pdf
VedprakashArya13
 
Company Profile 2023 PT. ZEKON INDONESIA.pdf
hendranofriadi26
 
Data_Cleaning_Infographic_Series_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Measurement of Afordability for Water Supply and Sanitation in Bangladesh .pptx
akmibrahimbd
 
Extract Transformation Load (3) (1).pptx
revathi148366
 
Data Security Breach: Immediate Action Plan
varmabhuvan266
 
Analysis of Employee_Attrition_Presentation.pptx
AdawuRedeemer
 
lecture 13 mind test academy it skills.pptx
ggesjmrasoolpark
 
Decoding Physical Presence: Unlocking Business Intelligence with Wi-Fi Analytics
meghahiremath253
 
Company Presentation pada Perusahaan ADB.pdf
didikfahmi
 
1intro to AI.pptx AI components & composition
ssuserb993e5
 
artificial intelligence deeplearning-200712115616.pptx
revathi148366
 
345_IT infrastructure for business management.pdf
LEANHTRAN4
 
The whitetiger novel review for collegeassignment.pptx
DhruvPatel754154
 
The_Future_of_Data_Analytics_by_CA_Suvidha_Chaplot_UPDATED.pdf
CA Suvidha Chaplot
 
oop_java (1) of ice or cse or eee ic.pdf
sabiquntoufiqlabonno
 
Future_of_AI_Presentation for everyone.pptx
boranamanju07
 
Pipeline Automatic Leak Detection for Water Distribution Systems
Sione Palu
 
Probability systematic sampling methods.pptx
PrakashRajput19
 

Arrays in c programing. practicals and .ppt

  • 1. Principles of Programming Lecture 6: Arrays  In this chapter, you will learn about  Introduction to Array  Array declaration  Array initialization  Assigning values to array elements  Reading values from array elements  Relationship with pointers  Passing array to function  2 Dimensional arrays 1 NI S1 2009/10
  • 2. Principles of Programming Introduction to Array  In C, a group of items of the same type can be set up using Array  An array is a group of consecutive memory locations related by the fact that they all have the same name and the same type.  The compiler must reserve storage (space) for each element/item of a declared array.  The size of an array is static (fixed) throughout program execution.  To refer to a particular location or element in the array, we specify the name of the array and its index (the position number of the particular element in the array). 2
  • 3. Principles of Programming 3 -10 99 -8 100 27 10 1976 -2020 1 Let say we have an array called a. a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] Name of the array The position number within the square brackets is formally called a subscript. A subscript can be an integer or an integer expression. For example if x = 1 and y = 2, then a[x+y] is equal to a[3]. Notice that the position starts from 0.
  • 4. Principles of Programming Array Declaration  Array declaration is made by specifying the data type, it’s name and the number of space (size) so that the computer may reserve the appropriate amount of memory.  General syntax: data_type array_name[size];  Examples:  int my_array[100];  char name[20];  double bigval[5*200];  int a[27], b[10], c[76]; 4
  • 5. Principles of Programming Array Initialization  There are 2 ways to initialize an array: during compilation and during execution.  During compilation:  int arr[ ] = {1, 2, 3, 4, 5};  Unsized array : We can define how many elements that we want since the array size is not given.  int arr[3] = {90, 21, 22};  We can define only 3 elements since the array size is already given.  int arr[5] = {2,4};  Initialize the first two elements to the value of 2 and 4 respectively, while the other elements are initialized to zero.  int arr[5] = {0};  Initialize all array elements to zero. 5
  • 6. Principles of Programming Array Initialization cont…  During execution:  Using loop to initialize all elements to zero int arr[3], index; for (index = 0; index < 3; index++) arr[index] = 0;  Using loop and asking the user to specify the value for each element. int arr[3], index; for (index = 0; index < 3; index++) { printf (“Enter number:n”); scanf(“%d”,&arr[index]); } 6
  • 7. Principles of Programming Assigning value to array element  We can assign a value to a specific array element by using its index number.  Example: let’s say we have an array that represent the number of inhabitant in 5 unit apartments. int apartment[5]={3,2,6,4,5};  The above initialization indicates that there are 3 people living in apartment 0, 2 people living in apartment 1 and so on.  Let say that we have a new born in apartment 3, so we need to change the number of inhabitant living in apartment three. apartment[3] = apartment[3] + 1;  Now, we have the following values in our array: 7 3 2 6 5 5 [0] [1] [2] [3] [4] apartment
  • 8. Principles of Programming Reading values from array elements  We can read a value from a specific array element by referring to the index.  For example, let’s say we want to know how many people leaving in apartment 3, we could simple do this: int apartment[5] = {3,2,6,4,5}; int no_of_people; no_of_people = apartment[3]; printf(“Apartment 3 has %d people”,no_of_people);  The above C code will produce the following output: 8 Hint!!! Remember that array’s index starts at 0 Apartment 3 has 4 people Press any key to continue
  • 9. Principles of Programming Example 1: finding total inhabitants #include <stdio.h> #define size 5 int main(void) { int apartment[size] = {3,2,6,4,5}; int index, total = 0; for (index = 0; index < size; index++) { total = total + apartment[index]; } printf("There are total of %d inhabitants",total); return(0); } 9 There are total of 20 inhabitants Press any key to continue
  • 10. Principles of Programming Example 2: list down number of inhabitants in each apartment #include <stdio.h> int main(void) { int apartment[5] = {3,2,6,4,5}; int index, total = 0; printf("%-7s %-15sn","Apt No", "No of people"); for (index = 0; index < 5; index++) { printf("%4d %10dn",index, apartment[index]); } return(0); } 10 Apt No No of people 0 3 1 2 2 6 3 4 4 5 Press any key to continue
  • 11. Principles of Programming Passing Array to a Function  When we pass an array to a function, we are actually passing the reference (address) of the first element in the array to the function. Therefore, any changes to the array inside the function will also change the actual array inside the calling function.  When we want to pass an array to a function, we need to know these 3 things.  How to write the function prototype?  How to do function call?  How does the function header would look like? 11
  • 12. Principles of Programming Passing Array to a Function  Assume that we have the following array declaration. float marks[10] = {0.0};  Say for example we want to write a function, called get_marks, which will read marks from the user and store the marks inside the array.  Function prototype: /* data type with square bracket */ void get_marks(float [ ]);  Function call: get_marks(marks); /* just pass the array name */  Function header: void get_marks(float marks[ ]) 12
  • 13. Principles of Programming Example: passing array to a function 13 #include <stdio.h> #define size void get_marks(float [ ]); float calc_average(float [ ]); int main(void) { float marks[size] = {0.0}; /*initializing the array get_marks(marks); /* function call */ printf(“Average for marks given is %.2f”, calc_average(marks)); return(0); } void get_marks(float marks[ ]) /* reading the marks from the users */ { int i; for (i = 0; i < size; i++) { printf("Marks for student %d:",i + 1); scanf("%f",&marks[i]); } } float calc_average(float marks[ ]) { float total = 0.0; int i; for (i = 0; i < size; i++) { total = total + marks[i]; } return (total / size); } Marks for student 1: 56 Marks for student 2: 96 Marks for student 3: 78 Marks for student 4: 35 Marks for student 5: 66 Average for marks given is 66.2 Press any key to continue Example: Passing Array to a Function
  • 14. Principles of Programming 2-Dimensional Array  It is possible to create an array which has more than one dimension.  For example:  2D array: int array[4][2];  3D array: int array[4][2][10];  Graphical representation of a 2D array: 14 int myarray[4][2] = {1,2,3,4,5,6,7,8}; 1 2 3 4 5 6 7 8 This array has 4 rows and 2 columns. Col 1 Col2 Row 1 Row 2 Row 3 Row 4
  • 15. Principles of Programming 2-Dimensional Array cont…  Variable initialization can also be done this way: int myarray[4][2] = {{1,2},{3,4},{5,6},{7,8}};  This method is less confusing since we can see the rows and columns division more clearly.  To initialize a 2D array during execution, we need to use a nested for loop: int row, column for (row = 0; row < 4; row++) { for (column = 0; column < 2; column++) { myarray[row][column] = row+column; } }  Although it is possible to create a multi-dimensional array, arrays above 2- dimensions are rarely used. 15
  • 16. Principles of Programming Passing a 2D array to a function  When a 2D (or higher dimensional) array is passed to a function, the size of the second (or subsequent) subscript needs to be specified.  For example, if we have: int twoD[4][5];  Then the function header which would take twoD as an argument should be declared like this: void Process2D(int twoD[ ][5])  An array is stored consecutively in memory regardless of the number of dimensions. Therefore, specifying the subscripts in the function parameter will help the compiler to know the boundary of the different dimensions. 16
  • 17. Principles of Programming Summary  In this chapter, we have looked at:  Array declaration and initialization  Reading and writing from/to array elements  Passing array to function  2 dimensional array 17
  • 18. Principles of Programming Exercise Assume the following array declaration float number[5] = {2.3, 4.2, 5.0, 7.9, 6.2}; What will be the output of the following statement? a)printf(“%f”, number[2+2] ); b)printf(“%f”, number[2]+2 ); c)printf(“%f”, number[1*2] ); d)printf(“%f”, number[1]*2 ); 18
  • 19. Principles of Programming Exercise Assume the following array declaration int result[5] = {56, 69, 89}; int i = 2; What will be the output of the following statement? a)printf(“%d”, result[1]); b)printf(“%d”, result[4]); c)printf(“%d”, result[0] + result[1]); d)printf(“%d %d”, i, result[i]); 19
  • 20. Principles of Programming Exercise Assume the following array declaration int result[3*2]; a) Write C statements that would read the values for the array element from the user. b) Write C statements that would list down all the values in the array. c) Write C statements that would sum up all the values in the array. Rewrite the above task as separate function!! 20