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

Similar documents
Module 6: Array in C

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

ARRAYS(II Unit Part II)

Write a C program using arrays and structure

Government Polytechnic Muzaffarpur.

Classification s of Data Structures

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

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

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

ONE DIMENSIONAL ARRAYS

Computers Programming Course 10. Iulian Năstac

Multi-Dimensional arrays

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

PDS Class Test 2. Room Sections No of students

'C' Programming Language

Computers Programming Course 11. Iulian Năstac

Subject: Fundamental of Computer Programming 2068

Arrays and Strings. Arash Rafiey. September 12, 2017

IV Unit Second Part STRUCTURES

Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection

Computer Programming Unit 3

Computers Programming Course 12. Iulian Năstac

Q 1. Attempt any TEN of the following:

Multiple Choice Questions ( 1 mark)

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

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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.

Introduction to Scientific Computing and Problem Solving

APSC 160 Review. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi Borrowing many questions from Ed Knorr

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C

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

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

UNIT - V STRUCTURES AND UNIONS

APSC 160 Review Part 2

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

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

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

Unit IV & V Previous Papers 1 mark Answers

Arrays in C. By Mrs. Manisha Kuveskar.

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.

Array Initialization

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

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

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

Lab 3. Pointers Programming Lab (Using C) XU Silei

MODULE 3: Arrays, Functions and Strings

Content. In this chapter, you will learn:

Arrays and Pointers (part 1)

Unit 3 Decision making, Looping and Arrays

Computer Science & Engineering 150A Problem Solving Using Computers

Fundamentals of Programming

How to declare an array in C?

Arrays. C Types. Derived. Function Array Pointer Structure Union Enumerated. EE 1910 Winter 2017/18

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

Arrays. Dr. Madhumita Sengupta. Assistant Professor IIIT Kalyani

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Arrays and Pointers (part 1)

Outline. Computer Memory Structure Addressing Concept Introduction to Pointer Pointer Manipulation Summary

Contents ARRAYS. Introduction:

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

Dynamic memory allocation

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

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

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Chapter 3: Arrays and More C Functionality

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

Unit 7. Functions. Need of User Defined Functions

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

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

Chapter 8 Character Arrays and Strings

Single Dimension Arrays

{C} Programming. Part 1/2 Basics Variables, Conditions, Loops, Arrays, Pointer basics

Fundamental of Programming (C)

Functions. Arash Rafiey. September 26, 2017

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

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

UNIT-I Fundamental Notations

Model Viva Questions for Programming in C lab

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

DECLARAING AND INITIALIZING POINTERS

Fundamental of Programming (C)

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

ESC101N: Fundamentals of Computing End-sem st semester

More Arrays. Last updated 2/6/19

Principles of Programming. Chapter 6: Arrays

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

Principles of C and Memory Management

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

In the previous lecture, we learned about how to find the complexity of algorithms and search algorithms on array.

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

String can be represented as a single-dimensional character type array. Declaration of strings

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

UNDERSTANDING THE COMPUTER S MEMORY

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

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.

Pointers. Introduction

MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

Transcription:

Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data belongings to the same data type. Syntax data_type array_name[array_size]; Here size is called index number or subscript. The complete set of values is referred to as any array the individual elements are called elements. Array might be belonging to any of the data types. Array size must be a constant value. Example for C Arrays: int a[5]; char b[10]; // integer array // character array i.e. string An array is collection of items stored at continuous memory locations. In other words adjacent memory locations are used to store the elements. Here, int[5] specifies that we can store five different values of same type. 1

The amount of storage is required for holding the elements that is based up on its size and size. Array elements are stored sequentially in separate locations. The lowest address corresponds to first element and the highest address corresponds to last element. The size and type of arrays cannot be changed after its declaration. An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it. Types of C-Arrays float marks[100]; There are 2 types of C arrays. They are, One dimensional array Two dimensional array One dimensional array: It is used to represent and store data in a linear form. Array having only one subscript variable is called one dimensional array. It is called as single dimensional or linear array. Size indicates the maximum number of elements that can be stored inside the array. The collection of data can be stored under a variable name using only one subscript. Array Declaration: The general form of array declaration is : data_type array_name[array_size]; 2

For example : if we want to represent a set of five numbers 25, 35, 45, 55, 65, by array variable number, then we may declare the variable number as follows example: int a[5]; The computer reserves five storage locations as shown C Array declaration tells to compiler Type of array Name of array Number of dimensions No of elements in each dimensions 3

ARRAY INITIALIZATION OR INITIALIZATION OF AN ARRAY 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 runtime. We should assign set of values to array element before executing the program i.e at compilation time. Compile time initialization of array elements is same as ordinary variable initialization. The general form of initialization of array is, type array-name[size] = list of values ; Here list of values are separated by commas. Example int marks[4]= 67, 87, 56, 77 ; //integer array initialization float area[5]= 23.4, 6.8, 5.5 ; //float array initialization int marks[4]= 67, 87, 56, 77, 59 ; //Compile time error One important thing to remember is that when you will give more initializer(array elements) than declared array size than the compiler will give an error. #include<stdio.h> #include<conio.h> void main( ) int i; int arr[]=2,3,4; //Compile time array initialization for(i=0 ; i<3 ; i++) printf("%d\t",arr[i]); getch(); // Program to find the average of n (n < 10) numbers using arrays 4

#include <stdio.h> int main() int marks[10], i, n, sum = 0, average; printf("enter n: "); scanf("%d", &n); for(i=0; i<n; ++i) printf("enter number%d: ",i+1); scanf("%d", &marks[i]); sum += marks[i]; average = sum/n; printf("average = %d", average); return 0; Array declaration, initialization and accessing Array declaration syntax: data_type arr_name [arr_size]; Array initialization syntax: data_type arr_name [arr_size]=(value1, value2, value3,.); Array accessing syntax: arr_name[index]; Example Integer array example: int age [5]; int age[5]=0, 1, 2, 3, 4; age[0]; /*0 is accessed*/ age[1]; /*1 is accessed*/ age[2]; /*2 is accessed*/ Character array example: char str[10]; char str[10]= H, a, i ; (or) char str[0] = H ; char str[1] = a ; char str[2] = i; 5

ACCESSING ARRAY ELEMENTS An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example double salary = balance[9]; 1. We all know that array elements are randomly accessed using the subscript variable. 2. Array can be accessed using array-name and subscript variable written inside pair of square brackets []. GENERATING A POINTERS TO AN ARRAY When an array is declared, compiler allocates sufficient amount of memory to contain all the elements of the array. Base address i.e address of the first element of the array is also allocated by the compiler. Suppose we declare an array arr, int arr[5]= 1, 2, 3, 4, 5 ; Assuming that the base address of arr is 1000 and each integer requires two bytes, the five elements will be stored as follows: Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000. 6

In short, arr has two purpose - it is the name of an array and it acts as a pointer pointing towards the first element in the array. arr is equal to &arr[0] //by default We can use a pointer to point to an Array, and then we can use that pointer to access the array. We can declare a pointer of type int to point to the array arr. int *p; p = arr; or p = &arr[0]; //both the statements are equivalent. Now we can access every element of array arr using p++ to move from one element to another. In this program, we have a pointer ptr that points to the 0 th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays. #include<stdio.h> int main() int arr[5] = 1, 2, 3, 4, 5 ; int *ptr = arr; prinf("%p\n", ptr); return 0; 7

The pointer *ptr will print all the values stored in the array one by one. We can also use the Base address (a in above case) to act as pointer and print all the values of address. PASSING A SINGLE DIMENSION ARRAYS TO FUNCTIONS Just like variables, array can also be passed to function as an argument. In C programming, a single array element or an entire array can be passed to a function. This can be done for both one-dimensional array and a multi-dimensional array. Array elements can be passed to function by calling function that is called call by value or pass by value. Call by value: if we pass values of variables to the called function then function are called call by value. Single element of an array can be passed in similar manner as passing variable to a function. If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways. 8

Way-1 Formal parameters as a pointer void myfunction(int *param)... Way-2 Formal parameters as a sized array void myfunction(int param[10])... Way-3 Formal parameters as an unsized array void myfunction(int param[ ])... Passing an entire one-dimensional array to a function While passing arrays as arguments to the function, only the name of the array is passed (,i.e, starting address of memory area is passed as argument). C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function. 9

STRING String is sequence of characters that is treated as a single data item. Remember that c- language does not support strings as data type. In c the string is terminated by a null character \0. A String is actually one dimensional array of characters in c- language. Strings can store multiple characters, i.e. alphabets, numbers, symbols, punctuation marks, and whitespace, unlike character data type which stores only a single character. Strings are often enclosed in quotation marks. Since strings can store numbers and other symbols as well, quotation marks help the compiler to distinguish whether the data is number or text. Character constants are enclosed in single quotes. String constants are enclosed in double quotes. The null is the first ASCII character which has value of zero. Each character occupies one byte memory and last character is always \0. \0 is called null character. \0 and zero are not same because ASCII value of \0 is 0 where as ASCII value of is 48. 10

ASCII is indicates the end of the string and %s is control specifier for string. DECLARATION OF STRING Strings can be declaration at the time of declaration The string of array can be declared as follows Syntax Char data type string_variable[size]; INITIALIZATION OF STRING Strings can be initialized at the time of declaration. In c, strings can be initialized in different ways. Char ch [ ]= abcd ; Or Char ch [ 5]= abcd ; Or Char ch [ ]= a, b, c, d, \0 ; Or Char ch [ 5]= a, b, c, d, \0 ; String can be initialized using pointers Char *c= abcd ; DIFFERENT TYPES OF STRING Strcpy(s1, s2 ) : this function is used to copy the one string into another string. Strlen( s1, s2) : this function is used to finds the length of the strings. Strcat( s1,s2) : this function is used to Concatenates string s2 onto the end of string s1. Strcmp( s1,s2) : this function is used to returns an integer result. Strrev(s1,s2): reverses all characters in as string. 11

12

13

TWO DIMENSIONAL ARRAYS C language supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. Both the row's and column's index begin from 0. Two dimensional array is nothing but array of arrays. A two dimensional array has two indexes i.e first index refers to the row, the second index refers to the column. Two-dimensional array is declared as follows, type array-name[row-size][column-size] ; Two dimensional array having more than one subscript that is called multi-dimensional array. Multi dimensional array is called as matrix. Example : int a[3][4]; A two-dimensional array a, which contains three rows and four columns can be shown as follows a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'. 14

INITIALIZING TWO-DIMENSIONAL ARRAYS The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arrays or list of arrays. A way to initialize the two dimensional array at the time of declaration is given below. Syntax: type array-name[row-size][column-size]=set of values; Example int emp[4][3]= 10,20,30,40,50,60,70,80,90,100,110,120; First three elements will be 1 st row, Second three elements will be 2 nd row, Next three elements will be 3 rd row, Last three elements will be 4 th row. Here we divided into 3 because our column size is 3. Above set of values can be written as int emp [4][3]= 10,20,30,40,50,60,70,80,90,100,110,120; or int emp [4][3]= 10,20,30, 40,50,60, 70,80,90, 100,110,120 ; 15

Program for array initialization #include <stdio.h> int main ( ) /* an array with 5 rows and 2 columns*/ int a[5][2] = 0,0, 1,2, 2,4, 3,6,4,8; int i, j; /* output each array element's value */ for ( i = 0; i < 5; i++ ) for ( j = 0; j < 2; j++ ) printf("a[%d][%d] = %d\n", i,j, a[i][j] ); return 0; Output a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8 16

// C program to multiply two square matrices. #include <stdio.h> #define N 4 void multiply(int mat1[ ][N], int mat2[ ][N], int res[ ][N]) int i, j, k; for (i = 0; i < N; i++) for (j = 0; j < N; j++) res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k]*mat2[k][j]; int main( ) int mat1[n][n] = 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4; int mat2[n][n] = 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4; int res[n][n]; // To store result int i, j; multiply(mat1, mat2, res); printf("result matrix is \n"); for (i = 0; i < N; i++) for (j = 0; j < N; j++) printf("%d ", res[i][j]); printf("\n"); return 0; 17

DECLARATION OF TWO DIMENSIONAL ARRAY An Array declaration introduces an identifier and describes its type, object, or function. A declaration is what the compiler needs to accept references to that identifier. We can declare an array in the c language in the following way. data_type array_name[size1][size2]; A simple example to declare two dimensional array is given below. int twodimen[4][3]; Here, 4 is the row number and 3 is the column number Program that accept values in 2-Dimensional 3 by 3 array and displays the sum of all the elements. void main() int arr[3][3], i, j, sum=0; /*Accepts input from the user and stores it in 2-D array*/ for(i=0;i<3;i++) for(j=0;j<3;j++) printf( \nenter the value for A[%d][%d]:,i,j); scanf( %d,&arr[i][j]); /*Calculate sum of elements in 2-D array*/ for(i=0;i<3;i++) for(j=0;j<3;j++) sum=sum+arr[i][j]; 18

/*Display the value of sum*/ printf( \nthe sum of the elements of 2-D array is %d, sum); Output Enter the value for A[0][0]: 1 Enter the value for A[0][1]: 2 Enter the value for A[0][2]: 3 Enter the value for A[1][0]: 4 Enter the value for A[1][1]: 5 Enter the value for A[1][2]: 6 Enter the value for A[2][0]: 7 Enter the value for A[2][1]: 8 Enter the value for A[2][2]: 9 The sum of the elements of 2-D array is 45 INDEXING POINTER pointer can replace indexing in many situations. Arrays are closely related to pointers in C programming but the important difference between them is that, a pointer variable takes different addresses as value whereas, in case of array it is fixed. 19

In C there is a very close connection between pointers and arrays. In fact they are more or less one and the same thing! When you declare an array as: int a[10]; we are in fact declaring a pointer a to the first element in the array. That is, a is exactly the same as &a[0]. The only difference between a and a pointer variable is that the array name is a constant pointer - you cannot change the location it points at. When you write an expression such as a[i] this is converted into a pointer expression that gives the value of the appropriate element. To be more precise, a[i] is exactly equivalent to *(a+i) i.e. the value pointed at by a + i. In the same way *(a+ 1) is the same as a[1] and so on. 1. An array's name is a constant pointer to the first element in the array that is a==&a[0] and *a==a[0]. 2. Array indexing is equivalent to pointer arithmetic - that is a+i=&a[i] and *(a+i)==a[i]. 3. In C programming, name of the array always points to address of the first element of an array. 4. In the above example, arr and &arr[0] points to the address of the first element. 5. &arr[0] is equivalent to arr 6. Since, the addresses of both are the same, the values of arr and &arr[0] are also the same. 7. arr[0] is equivalent to *arr (value of an address of the pointer) Similarly, 8. &arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1). 9. &arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2). 10. &arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3). &arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i). In C, you can declare an array and can use pointer to alter the data of an array. 20

Example: Program to find the sum of six numbers with arrays and pointers Output Enter 6 numbers: 2 3 4 5 3 4 Sum = 21 VARIABLE LENGTH ARRAYS In computer programming, a variable length array is called variable sized, runtime sized. ISO C99 allows variable length arrays these arrays are declared at runtime instead of compile time. Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. Note: size or subscript is a not a expression and it must be constant value. 21

The general form of variable sized array void fun(int n) int arr[n]; //... int main() fun(6); Example program for Variable sized array int main ( ) int m=2; int arr[m][m]; int i,j; for (i=0; i<m; i++) arr[i][j]=0; printf( %d,arr[i][j]); Printf( \n ); return 0; 22