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

Similar documents
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)

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

Programming for Engineers Arrays

Fundamentals of Programming

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

Arrays, Strings, & Pointers

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

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

ONE DIMENSIONAL ARRAYS

Fundamental of Programming (C)

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Write a C program using arrays and structure

Why arrays? To group distinct variables of the same type under a single name.

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

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

Lecture 04 FUNCTIONS AND ARRAYS

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Array Initialization

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

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

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

Strings. Chuan-Ming Liu. Computer Science & Information Engineering National Taipei University of Technology Taiwan

Computers Programming Course 11. Iulian Năstac

Arrays and Pointers (part 2) Be extra careful with pointers!

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

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

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

Chapter 8 Character Arrays and Strings

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

Chapter 8: Character & String. In this chapter, you ll learn about;

Computer Science & Engineering 150A Problem Solving Using Computers

UNIT-I Input/ Output functions and other library functions

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

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array

Arrays and Pointers (part 2) Be extra careful with pointers!

C Programming. The C Preprocessor and Some Advanced Topics. Learn More about #define. Define a macro name Create function-like macros.

Computer Programming Lecture 14 Arrays (Part 2)

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

Special PRG Lecture No. 2. Professor David Brailsford Special PRG Lecture: Arrays

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

CGS 3460 Summer 07 Midterm Exam

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

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

Module 6: Array in C

C Arrays Pearson Education, Inc. All rights reserved.


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

Arrays and Applications

Strings. Daily Puzzle

Eastern Mediterranean University School of Computing and Technology Information Technology Lecture7 Strings and Characters

type arrayname [ size type arrayname [ size ] = { item ,, item size 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.

Lecture 9 - C Functions

UNIT III ARRAYS AND STRINGS

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

8. Characters, Strings and Files

Procedural Programming

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

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

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

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

Structured programming. Exercises 3

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Fundamental of Programming (C)

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

Computers Programming Course 10. Iulian Năstac

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

Programming Language A

Government Polytechnic Muzaffarpur.

Fundamentals of Computer Programming Using C

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

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

Pointers, Arrays, and Strings. CS449 Spring 2016

C Programming. Unit 9. Manipulating Strings File Processing.

Programming Logic and Design Sixth Edition

UIC. C Programming Primer. Bharathidasan University

C: How to Program. Week /Apr/23

Arrays. Week 4. Assylbek Jumagaliyev

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

Strings and Arrays. Hendrik Speleers

Introduction to string

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING


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

MODULE 3: Arrays, Functions and Strings

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

Content. In this chapter, you will learn:

Programming Language B

Euclid s algorithm, 133

Chapter 10. Arrays and Strings

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

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

Arrays. Systems Programming Concepts

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Programming and Data Structures

Transcription:

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

Lecture 10: Arrays Readings: Chapter 9

Introduction Group of same type of variables that have same name Each item in the group is called an element of the array Each element is distinguished from another by an index All elements are stored contiguously in memory The elements of the array can be of any valid typeintegers, characters, floating-point types or user-defined types Bhaskar Shrestha 3

Declaring an Array Declared as other variables, with the array size (total no of elements) enclosed in square brackets Example int x[100]; this creates an integer array named x with 100 elements char text[80]; this creates a character array named text with 80 elements The size of the array specified must be a constant Bhaskar Shrestha 4

Arrays Each array elements are distinguished with an index The index of first element is 0, the second element has an index of 1 and so on. The last element has an index of arraysize-1 Example int c[12]; this creates an array named c from c[0] to c[11] Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] -45 Position number of the element within array c Bhaskar Shrestha 5 6 0 72 1543-89 0 62-3 1 6453 78

Arrays in Memory The amount of storage required to hold an array is directly related to its type and size total size of array in bytes = sizeof(base type) length of array All arrays consist of contiguous memory locations the lowest address corresponds to the first element the highest address to the last element Element a[0] a[1] a[3] a[4] a[5] a[6] a[7] Address 1000 1002 1004 1006 1008 1010 1012 A seven-element integer array beginning at location 1000 Bhaskar Shrestha 6

Manipulating Arrays Single operations that involve entire arrays are not permitted in C Each array must be manipulated on an element-by-element basis To access an element, specify the index of the element after array name enclosed in square brackets Index must be an integral expression Array elements are like normal variables c[0] = 3; printf( "%d", c[ 0 ] ); Perform operations in subscript. If x equals 3 c[ 5-2 ] == c[ 3 ] == c[ x ] Bhaskar Shrestha 7

Array Manipulation Example #define NUM 100 int grade[num]; int i, avg, sum = 0; printf("input scores:\n"); for (i=0; i<num; i++) scanf("%d", &grade[i]); for (i=0; i<num; i++) sum = sum + grade[i]; avg = sum/ NUM; printf("average=%d\n", avg); Bhaskar Shrestha 8

/* Given the price and stock of 5 different bulbs, calculate the total stock value */ int i, stock[5]; float price[5]; float total=0; for (i=0; i < 5; i++) { printf("enter stock of bulb %d: ", i+1); scanf("%d", &stock[i]); printf("enter price of bulb %d: ", i+1); scanf("%f", &price[i]); total += stock[i]*price[i]; } printf("the total stock value is %f\n", total); Bhaskar Shrestha 9

Array Bound Checking Array Bounds (index) are not verified neither at compile-time nor at run-time Index must be within 0 and arraysize-1 If not others data may be overwritten int a=100,b[5],c=200; int i; for (i=0; i < 6; i++) b[i] = i; printf("a=%d, c=%d\n", a, c); Bhaskar Shrestha 10

Initializing Arrays Each array element can be initialized, when an array is declared The initial values must appear in the order in which they will be assigned to the individual array elements, enclosed in braces and separated by commas Example int digits[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; static float x[6] = {0, 0.25, 0, 0.50, 0, 0}; char color[3] = {'R', 'E', 'D'}; Bhaskar Shrestha 11

/* The wattage problem */ int i, stock[5]; int watt[5] = {15,25,40,60,100}; float price[5]; float total=0; for (i=0; i < 5; i++) { printf("enter stock of bulb %d: ", watt[i]); scanf("%d", &stock[i]); printf("enter price of bulb %d: ", watt[i]); scanf("%f", &price[i]); total += stock[i]*price[i]; } printf("the total stock value is %f\n", total); Bhaskar Shrestha 12

More on Initialization When a list of initializers is shorter than the number of array elements to be initialized, the remaining elements are initialized to zero int digits[10] = { 3, 3, 3}; the elements digits[3] to digits[9] will have value 0 You can use quoted strings to initialize character-arrays char color[4] = "RED"; here the null character is appended by the compiler The array size can be omitted if you initialize the array elements int digits[] = {1, 2, 3, 4, 5, 6}; the size of digits is 6 char color[] = "RED"; the size of color is 4 Bhaskar Shrestha 13

One-dimensional Arrays and Strings Common use for the one-dimensional array is as a character string A string is a null-terminated character array. (A null is zero) A string contains the characters that make up the string followed by a null When declaring a character array to hold a string, declare it to be one character longer than the largest string that it will hold char str[11] declares an array str that can hold a 10-character string When you use a quoted string constant in your program, you are also creating a null-terminated string "hello there" the null is automatically added by the compiler Bhaskar Shrestha 14

Reading and Writing Strings Reading strings use gets or scanf char text[80]; gets(text), scanf(" %[^\n]", text) Reads characters until newline encountered scanf("%s", text); Reads characters until whitespace encountered the null character is automatically appended Can write beyond end of array, be careful Writing strings use puts or printf puts(text); printf("%s", text); Bhaskar Shrestha 15

Finding the length of a string char text[80]; int len; gets(text); len = 0; while (text[len]!= '\0') len++; printf("the string \"%s\" has %d characters\n", text, len); Bhaskar Shrestha 16

Lowercase to Uppercase Conversion char text[80]; int i; gets(text); for (i=0; text[i]!= '\0'; i++) { if (text[i]>='a' && text[i]<='z') text[i] = text[i]-32; } puts(text); Bhaskar Shrestha 17

Copying Strings char str1[80], str2[80]; int i; gets(str1); for (i=0; str1[i]!= '\0'; i++) { str2[i] = str1[i]; } str2[i] = '\0'; puts(str2); Bhaskar Shrestha 18

Concatenating Strings char s1[80], s2[80]; int i, j, len; gets(s1); gets(s2); for (len=0; s1[len]!= '\0'; len++) ; for (i=0, j=len; s2[i]!= '\0'; i++, j++) s1[j] = s2[i]; s1[j] = '\0'; puts(s1); Bhaskar Shrestha 19

Searching in an Array Specific elements of an array can be searched in one of two ways Linear(Sequential) search Each element is compared to the key one by one Useful for small and unsorted arrays Binary Search Can be used only on sorted arrays First compares the key with the middle element of the array, if not found one-half of the array is searched in the similar way Bhaskar Shrestha 20

/* Linear Search: Searching for key in an array number of size max */ for (i = 0; i < max; i++) { if (key == number[i]) break; } if (i == max) printf("%d was not found\n", key); else printf("\n%d was found at position %d", key, i); Bhaskar Shrestha 21

Sorting an Array The process of arranging the elements such that they are according to some strict order (eg ascending/descending) This can be accomplished using a technique known as bubble sort The rearrangement will begin by scanning the entire array for the smallest number This number will then be interchanged with the first number in the array, thus placing the smallest number at the top of the list Next the remaining max - 1 numbers will be scanned for the smallest, which will be exchanged with the second number The remaining max - 2 numbers will then be scanned for the smallest, which will be interchanged with the third number, and so on, until the entire array has been rearranged Bhaskar Shrestha 22

/* rearrange a list of max numbers */ for (item = 0; item < max 1; item++) /*find the smallest of all remaining elements*/ for (i = item + 1; i < max; i++) if (number[i] < number[item]) { /* interchange the elements */ temp = number[item]; number[item] = number[i]; number[i] = temp; } Bhaskar Shrestha 23

Passing Arrays to Functions Passing Arrays To pass an array argument to a function, specify the name of the array without any brackets float list[100];... avg = average(list,n); The array name is written with an empty square bracket in the formal parameter declaration float average(float x[], int n){} Name of array is address of first element Passing Array Elements Passed by call-by-value Pass subscripted name (i.e., list[3]) to function Bhaskar Shrestha 24

/* function prototype */ float average(float x[], int n); int main() { int n; float avg; float list[100];... avg = average(list,n);... } /* function definition */ float average(float x[], int n) {... } Bhaskar Shrestha 25

Arrays are always passed by reference Arrays are passed by reference Name of array is treated as the address of the first element in the function Hence it actually becomes a pointer to the first element of the array in the function Function knows where the array is stored Can modify original array elements passed Bhaskar Shrestha 26

void modify(int b, int c[]); main() { int b = 2; int i, c[] = { 10, 20, 30 }; modify(b,c); printf("b = %d\n", b); for (i = 0; i < 3; i++) printf("c[%d] = %d\n", i, c[i]); } void modify(int b, int c[]) { int i; b = -999; for (i = 0; i < 3; i++) c[i] = -9; } Bhaskar Shrestha 27

String Manipulation Library Functions The standard C library defines a wide range of functions that manipulate strings strcpy(s1,s2): Copies s2 into s1 strcat(s1,s2): Concatenates s2 onto the end of s1 strlen(s1): Returns number of characters in s1 excluding the terminating null character strcmp(s1,s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s1 strchr(s1,ch): Returns a pointer to the first occurrence of the character ch in s1 strstr(s1,s2): Returns a pointer to the first occurrence of s2 in s1 All string functions use the standard header <string.h> Bhaskar Shrestha 28

char name[40], first[40]; printf("enter a name: "); gets(name); strcpy(first, name); while (strcmp(name,"end")!= 0) { if (strcmp(first,name) > 0)) strcpy(first, name); printf("enter a name: END to stop"); gets(name); } printf("the first is %s\n", first); Bhaskar Shrestha 29

Multi-dimensional Arrays Recall: An array is a sequence of data items that are of the same type, that can be indexed, and that are stored contiguously Each element of an array is like a single item of a particular type But an array itself is an item of a particular type So, an array element could be another array An array-of-arrays is called multi-dimensional arrays whose elements are themselves arrays No of subscript determines the dimension of the array Bhaskar Shrestha 30

Two-dimensional Arrays A two-dimensional array is an array of one-dimensional arrays Example: int a[3][4]; An array of 3 elements, in which every element is an array of 4 ints Accessing Elements a[1] This gives the second element, i.e., second array (address of first element of second array) a[1][2] This gives the third integer within the second array Bhaskar Shrestha 31

Two-dimensional Arrays Think, two-dimensional arrays as tables/matrices arranged in rows and columns Use first subscript to specify row no and the second subscript to specify column no Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[0][0] a[1][0] a[2][0] a[0][1] a[1][1] a[2][1] a[0][2] a[1][2] a[2][2] a[0][3] a[1][3] a[2][3] Array Column subscript name Row subscript A table with 3 rows and 4 columns Bhaskar Shrestha 32

int a[3][4]; int i, j; Example for (i = 0; i < 3; ++i) for (j = 0; j < 4; ++j) a[i][j] = i+j; for (i =0; i < 3; ++i) { for (j = 0; j < 4; ++j) printf("a[%d][%d] = %d ", i, j, a[i][j]); printf("\n"); } printf("%d\n", a[2][1]/2); printf("%d\n", a[1][1] * (a[0][0]+2)); printf("%d\n", a[3][1]/2); /* ERROR:? */ Bhaskar Shrestha 33

Initialization List the values separated by commas and enclosed in braces int a[2][3] = { 1, 2, 3, 4, 5, 6}; The values will be assigned in the order they appear Initializers can be grouped with braces int a[2][3] = { {1, 2, 3}, {4, 5, 6}}; If not enough, unspecified elements set to zero int a[2][3] = { {1, 2}, {3, 4}}; You can leave the size for first subscript int a[][3] = { {1, 2}, {3, 4}}; 1 4 1 3 2 5 2 4 3 6 0 0 Bhaskar Shrestha 34

Passing Multidimensional Arrays to Function Specify the array variable name, while passing it to a function only the address of the first element is actually passed The parameter receiving the array must define the size of all dimension, except the first one Any changes to array elements within the function affects the original array elements int a[3][4]; func(a); Function Call void func(int x[][4]) { } Multidimensional array in parameter Bhaskar Shrestha 35

#define MAXROWS 10 #define MAXCOLS 20 void ReadTable(int t[][maxcols], int r, int c); void PrintTable(int t[][maxcols], int r, int c); int SumOfOddElements(int t[][maxcols], int r, int c); int SumOfEvenElements(int t[][maxcols], int r, int c); main() { int table[maxrows][maxcols]; int nrows, ncols; int oddsum, evensum; printf("enter no of rows and columns: "); scanf("%d %d", &nrows, &ncols); ReadTable(table, nrows, ncols); oddsum = SumOfOddElements(table, nrows, ncols); evensum = SumOfEvenElements(table, nrows, ncols); Bhaskar Shrestha 36

PrintTable(table, nrows, ncols); printf("odd sum = %d, Even sum = %d\n", oddsum, evensum); } void ReadTable(int t[][maxcols], int r, int c) { int i, j; for (i = 0; i < r; i++) { printf("enter elements for row %d\n", i+1); for (j = 0; j < c; j++) { printf("column %d: ", j+1); scanf("%d", &t[i][j]); } } } Bhaskar Shrestha 37

void PrintTable(int t[][maxcols], int r, int c) { int i, j; for (i = 0; i < r; i++) { for (j = 0; j < c; j++) printf("%5d", t[i][j]); printf("\n"); } } int SumOfOddElements(int t[][maxcols], int r, int c) { int i, j; int sum = 0; for (i = 0; i < r; i++) for (j = 0; j < c; j++) if (t[i][j]%2!= 0) sum += t[i][j]; return sum; } Bhaskar Shrestha 38

Multidimensional Arrays in Memory Each array within a multidimensional array stored sequentially in memory as with one-dimensional array For two-dimensional array, all elements in first row is stored, then the elements of second row and so on a[0] a[1] a[2] a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] Bhaskar Shrestha 39

Array of Strings You can create array of strings using a two-dimensional character array char months[12][10]; Left dimension determines the number of strings, and right dimension specifies the maximum length of each string Now you can use the array months to store 12 strings each of which can have a maximum of 10 characters (including the null) To access an individual string, you specify only the left subscript puts(months[2]); prints the third month Bhaskar Shrestha 40

Bhaskar Shrestha 41 Example \0 r e b m e c e D \0 r e b m e v o N \0 r e b o t c O \0 r e b m e t p e S \0 t s u g u A \0 y l u J \0 e n u J \0 y a M \0 l i r p A \0 h c r a M \0 y r a u r b e F \0 y r a u n a J char months[12][10] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December }; printf("%s\n", months[5]); months[0] months[1] months[2] months[3] months[4] months[5] months[6] months[7] months[8] months[9] months[10] months[11]