Module 6: Array in C

Similar documents
Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

How to declare an array in C?

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

ONE DIMENSIONAL ARRAYS

Multi-Dimensional arrays

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Write a C program using arrays and structure

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array

Government Polytechnic Muzaffarpur.

Unit IV & V Previous Papers 1 mark Answers

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Programming for Electrical and Computer Engineers. Pointers and Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Programming for Engineers Arrays

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

'C' Programming Language

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

First of all, it is a variable, just like other variables you studied

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

Introduction to Scientific Computing and Problem Solving

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

IV Unit Second Part STRUCTURES

Classification s of Data Structures

Arrays and Pointers (part 1)

Principles of Programming. Chapter 6: Arrays

Procedural Programming

Lesson 7. Reading and Writing a.k.a. Input and Output

Arrays and Pointers. CSE 2031 Fall November 11, 2013

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

Week 8: Arrays and File I/O. BJ Furman 21OCT2009

by Pearson Education, Inc. All Rights Reserved.

[0569] p 0318 garbage

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Chapter 7 Array. Array. C++, How to Program

Arrays in C. By Mrs. Manisha Kuveskar.

QUIZ: loops. Write a program that prints the integers from -7 to 15 (inclusive) using: for loop while loop do...while loop

Unit 3. Operators. School of Science and Technology INTRODUCTION

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

UNIT-I Fundamental Notations

Arrays in C. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Review of the C Programming Language for Principles of Operating Systems

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

More Arrays. Last updated 2/6/19

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

C Programming Lecture V

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Arrays and Pointers (part 1)

JME Language Reference Manual

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Array Initialization

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Computer Programming Unit 3

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

EC312 Chapter 4: Arrays and Strings

Arrays in C C Programming and Software Tools. N.C. State Department of Computer Science

ARRAYS(II Unit Part II)

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

Module 4: Decision-making and forming loops

C++ ARRAYS POINTERS POINTER ARITHMETIC. Problem Solving with Computers-I

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

CSC 270 Survey of Programming Languages. What is a Pointer?

Basics of Programming

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Problem Solving and 'C' Programming

Example: Structure, Union. Syntax. of Structure: struct book { char title[100]; char author[50] ]; float price; }; void main( )

type arrayname [ size type arrayname [ size ] = { item ,, item size size

Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Objectives of This Chapter

Computer Science & Engineering 150A Problem Solving Using Computers

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Lecture 3 Tao Wang 1

Computer Programming : C++

Engineering program development 6. Edited by Péter Vass

Transcription:

1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of an array 2. To study different types of arrays 3. To declare and initialize an array. 4. To know how to use array elements in multidimensional array.

2 1. Introduction As discussed in the previous modules, variables are used to hold data in memory. If a large number of data is to be stored, it would be tedious task to assign separate variable name and declare in the program. For example, processing the marks of 50 students in a class would require 50 different variable names. This task is impractical and tedious. In such scenario, C programming provides a facility of array. In real world, the examples are: to store a list of numbers or characters, to store student or employee names or to store marks of many students. An array is a systematic arrangement of similar objects, usually in rows and columns. An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Many applications require processing of multiple data items having common characteristics. In such situation, it is always convenient to place a data item into an array. All the data items will share the same name. Instead of declaring individual variables, such as x0 x1,..., and x49, you declare one array variable such as numbers and use x[0],x[1], and..., x[49] to represent individual variables. A specific element in an array is accessed by an index. The array, pointer, structure, and union are derived data type in C. 1. Storing a string that contains series of characters. Like storing a name in memory. 2. Storing multiple strings. Like storing multiple names. C programming language provides the concept of arrays to help you with these scenarios. We have seen the Constants in C in the module 3. In this hierarchy there are two sub branches of C constant as shown in figure-1. 1) Primary constant. 2) Secondary constant. Note that here the array is shown in Secondary constants in the classification.

3 Figure-1: Primary and secondary constants In this module, we shall discuss the method of declaring the array, array notations, aray initialization, array accessing and their processing. 2. Basics of arrays In C language, it is possible to assign a single name to whole group of similar data. Let us consider an example of group of students whose marks are to be recorded. Let us assign a common name say x to all the data. Each element in the array can be assessed by its position within the list of items as shown in figure-2. x 55 x 1 =55 x[1]=55 95 x 2 =95 x[2]=95 64 x 3 =64 x[3]=64 79 x 4 =79 x[4]=79 63 x 5 =63 x[5]=63 Fig.-2 :(a) List of items, (b) List items with subscripted variable (c) Array representation In mathematics, a subscript is a number written to the right of variable name, slightly below the line, usually small in font. Subscript indicates the position of a particular element with respect to

4 the rest of elements. As it is impossible to display subscripted numbers on the standard computer, the numbers are enclosed in parentheses. A subscript is also known as index. In C language subscript starts at 0 rather than 1 and cannot be negative. In short, Array is a collection of variables belongings to the same data type. The group of data of same data type can store in an array. An array is a collection of same type of elements which are sheltered under a common name. An array can be visualized as a row in a table, whose each successive block can be thought of as memory bytes containing one element. Look at the figure below: An Array of five elements Element 1 Element 2 Element 3 Element 4 Element 5 Figure-3: Array of five elements An array has following properties Type- data type of array elements Location- location of first element of the array Length- number of data elements in the array. Size- length of the array times the size of an element. These arrays are also called as linear or one-dimensional array. The number of 8 bits- bytes that each element occupies depends on the type of array. If type of array is char then it means the array stores character elements. Since each character occupies one byte so elements of a character array occupy one byte each. Array belongs to any of the data types. Array size must be a constant value. Always, continuous (adjacent) memory locations are used to store array elements in memory.

5 It is a best practice to initialize an array to zero or null while declaring if we don t assign any values to array. 3. Types of C arrays: Arrays are classified according to the number of subscripts present in the list. Based on this there are 2 types of C arrays. These are, 1. One dimensional array 2. Multi dimensional array Figure-4: Types of array One dimensional array is used to represent and store data in a linear form. It has only one subscript in the variable name. It is also called as single dimensional or linear array. Many cases arrays having more than one subscript variable is used, which is known as multi-dimensional array. Such multi-dimensional array is also known as matrix. Let us now see how arrays are declared.

6 4. Declaring Arrays: Arrays must be declared before it is used in C program like normal variables. The array declaration is nothing but defining the type of the array ( e.g. int, float, char etc.), name of the array, number of subscripts (i.e. whether one or multi-dimensional) and total number of memory locations to be allocated (i.e. maximum value of each subscript.. 1. One dimensional array The general syntax of one dimensional array is shown below: Syntax: <data type-of-array> <name-of-array> [<number of elements in array>]; Data type-of-array: It is the type of elements that an array stores. If array stores character elements then type of array is char. If array stores integer elements then type of array is int. Besides these native types, if type of elements in array is structure objects then type of array becomes the structure. Name-of-array: This is the name that is given to array. It can be any string but it is usually suggested that some standard should be followed while naming arrays. At least the name should be in context with what is being stored in the array. [Number of elements]: This value in subscripts [] indicates the number of elements the array stores. For example : int a[10]; a [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] Figure-5: One dimensional array

7 Other similar declarations are: int rollno[100]; char name[20] float distance[5]; double average[]; 2. Multi dimensional array Although arrays with more than two dimensions are not commonly used, C language allow any size array to be declared. Please note that the exact limit is determined by the compiler. The general form of the multi-dimensional array is: Syntax: data_type array_name[array_size]... [array_size] Col1 Col2 Col3 Col4 Col5 Row1 a[0][0] a[0][1] a[0][2] a[0][3] a[0][4] Row2 a[1][0] a[1][1] a[1][2] a[1][3] a[1][4] Figure-6: Two dimensional array Some typical examples are: int a[3][3]; int table[2][3][4] float graph[5][5][5];

8 Let us consider the array table, which is a three dimensional array declared to contain 24 integers. The table may include data in 3-dimensions. Similarly, arrays with four, five, six dimensions and so on can be declared. 5. Initializing an array: Arrays can be initialized like ordinary variables either inside or outside the function. Arrays declared inside the function are local arrays and arrays declared outside the function are global arrays. Global arrays can be initialized when they are declared. Figure-7 shows methods of initializing arrays. Run time Initialization Initializing Array Size specifications Compile time initialization Without Size specifications Figure-7: Methods of array initialization Let us understand these methods of initialization starting with compilation time initialization of an array. Example-1: Array size specified int a[5] = { 4,1,5,8,2}; In this example, the size of array is specified as 5 in the initialization/declaration statement. Compiler will assign these 5 values to an array a.

9 Example-2: Array size unspecified int a[] = { 4,1,5,8,2}; In this example, the size of an array is not specified in the initialization/ declaration statement. Here, compiler counts the number of elements written inside the pair of braces and determines the size of array. After counting the number of elements in an array, the size of any array is considered to be 5 during the execution of the program. Such method of initialization is known as compilation time initialization. For example In the above example an array of five integers is declared. Note that since we are initializing at the time of declaration so there is no need to mention any value in the subscripts []. The size will automatically be calculated from the number of values. In this case, the size will be 5. An array can be initialized at run-time as shown in the following example. Here each element is initialized separately. #include <stdio.h> int main() { int a[5]; int i = 0; for(i=0;i<sizeof(a);i++) { a[i] = i; // Initializing each element separately } Return 0; }

10 In this example, the array is initialized after compilation and during the run-time. Here each element is initialized separately. One can use printf statement to inform user that new array element is to be entered. This will help user to have a prompt before data entry. Initializing array with a string (Method 1): Strings in C language are nothing but a series of characters followed by a null byte. So to store a string, we need an array of characters followed by a null byte. This makes the initialization of strings a bit different. Let us take a look : Since strings are nothing but a series of characters so the array containing a string will be containing characters char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a \0 (null) byte. The null byte is required as a terminating byte when string is read as a whole. Initializing array with a string (Method 2): char arr[] = "code"; Here we neither require to explicitly wrap single quotes around each character nor write a null character. The double quotes do the trick for us. For example : int a[2][3]={{2,4,6}, {-5,8,9}}; OR

11 int c[][]={{2,4,6}, {-5,8,9}}; OR int c[2][3]={ 2,4,6, -5,8,9}; After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at run -time. Two dimensional arrays can be initialized in the same manner like one dimensional array. While specifying the values during initialization it is written row wise. Brace pairs are used to separate the values of one row to next. For example: int a[2][3] = { {1, 2, 3}, {3, 4, 5} }; Note that, special care be taken for defining the multi-dimensional array. 6. Processing an array The first step in processing any array or an array element is to know the method to access individual array elements. Accessing array elements In C programming, arrays can be accessed and treated like variables in C. For example: scanf("%d",&a[3]); This statement is used to obtain the 4 the element of array a[]. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. scanf("%d",&a[i]);

12 This statement is used to get the (i+1)th the element of array a[] from the keyboard. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. printf("%d",a[1]); This statement is used to print the 2 nd element of array a[]. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. printf("%d",a[i]); This statement is used to print (i+1)th lement of array a[]. Here, the assumption is that the array is initialized from the 0 th element which is the first element of an array. Accessing Two-Dimensional Array Elements: Two dimensional array may be initialized and accessed just similar to one dimensiona l array. Following example demonstrates how to declare and initialize an array, printing an array with the help of two for loops.

13 Arithmetic Operations on Array: In this matrix format the arithmetic operation like addition can be performed where the matrix1 and matrix2 are being added together. In the matrix 1, there is 2 row and 2 column in which A11 defines the place of row1 and column1. Similarly for all other elements can also be designated and accessed like a11, a12, a21 and a22. This example shows how the values accessed and processed in the multi-dimensional arrays. Similar method may be adopted for subtraction of matrices. Let us consider a simple example to demonstrate arithmetic operations on two dimensional array: Array1[2][2]={{1,2},{3,4}} Array2[2][2]={{4,5},{2,4}} Here we see the example for addition of 2 by 2 matrices, here 1 is added with 4, 2 is added with 5 and so on.

14 Program for addition of two Matrices: #include <stdio.h> int main() { int a, b, i, j, M1[5][5], M2[5][5], sum[5][5]; printf("enter the number of rows and columns of matrix:\n"); scanf("%d%d", &a, &b); printf("enter the elements of matrix M1:\n"); for (i = 0; i < a; i++) for (j = 0; j < n; j++) scanf("%d", &M1[i][j]); printf("enter the elements of matrix M2:\n"); for (i = 0; i < a; i++) for (j = 0 ; j < b; j++) scanf("%d", &M2[i][j]); printf("sum of entered matrices:\n"); for (i = 0; i < a; i++) { for (j = 0 ; j < n; j++) { sum[i][j] = M1[i][j] + M2[i][j]; printf("%d\t", sum[i][j]); } printf("\n"); } return 0; } The result of the above program is shown here.

15 7. Summary An array is a systematic arrangement of similar objects, usually in rows and columns. An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Arrays are classified according to the number of subscripts present in the list. Based on this there are 2 types of C arrays. These are, 1. One dimensional array 2. Multi dimensional array One dimensional array is used to represent and store data in a linear form. It has only one subscript in the variable name. It is also called as single dimensional or linear array. Many cases arrays having more than one subscript variable is used, which is known as multi-dimensional array. Arrays can be initialized like ordinary variables either inside or outside the function. Arrays declared inside the function are local arrays and arrays declared outside the function are global arrays. Different arithmetic operations can be performed on arrays.

16