1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

An Array A sequence of elements of a particular type Each element in the array has an index which gives its position in the sequence An array is declared.
O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Kernighan/Ritchie: Kelley/Pohl:
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
1 ICS103 Programming in C Lecture 13: Arrays II. 2 Outline Review on Arrays Using array elements as function arguments  Examples Using arrays as function.
1 ICS103 Programming in C Lecture 13: Arrays II. 2 Outline Review on One-dimensional Arrays Using array elements as function arguments  Examples Using.
O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 ICS103 Programming in C Lecture 12: Arrays I. 2 Outline Motivation for One-dimensional Arrays What is a One-dimensional Array? Declaring One-dimensional.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
Computer programming Lecture 5. Lecture 5: Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character arrays.
1 Functions. 2 Function A program segment that carries out some specific, well-defined task Example  A function to add two numbers  A function to find.
Arrays- Part 2 Spring 2013Programming and Data Structure1.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
1 Pointers and Arrays. 2 When an array is declared,  The compiler allocates sufficient amount of storage to contain all the elements of the array in.
Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify –Array name –Position number Format: arrayname.
CS 161 Introduction to Programming and Problem Solving Chapter 19 Single-Dimensional Arrays Herbert G. Mayer, PSU Status 10/8/2014 Initial content copied.
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1. 1. Introduction to Array 2. Arrays of Data 3. Array Declaration 4. Array Initialization 5. Operations on Array 6. Multidimensional Arrays 7. Index.
ICS103 Programming in C Lecture 11: Arrays I
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Arrays.
ICS103: Programming in C 7: Arrays Muhamed F. Mudawar.
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
1 2-d Arrays. 2 Two Dimensional Arrays We have seen that an array variable can store a list of values Many applications require us to store a table of.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Array in C# Array in C# RIHS Arshad Khan
1-d Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
EKT120 : Computer Programming
Arrays Declarations CSCI N305
Lecture 7 – Arrays (1) PGT 106 : C PROGRAMMING.
Programming and Data Structure
Looping.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, For loop While loop Do while loop
ARRAYS Lecture
Lecture 10 Arrays.
EKT150 : Computer Programming
ICS103 Programming in C Lecture 13: Arrays II
EKT120: Computer Programming
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Initializing variables
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Lecture 14: Problems with Lots of Similar Data
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
ICS103 Programming in C Lecture 12: Arrays I
ARRAYS ..
Intro to Arrays Storing List of Data.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

1 1-d Arrays

2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of data items in indexed form: x 1, x 2, x 3, …, x n Array is a data structure which can represent a collection of data items which have the same data type (float/int/char/…)

3 int a, b, c; scanf(“%d”, &a); scanf(“%d”, &b); scanf(“%d”, &c); printf(“%d ”, c); printf(“%d ”, b); printf(“%d \n”, a); int a, b, c, d; scanf(“%d”, &a); scanf(“%d”, &b); scanf(“%d”, &c); scanf(“%d”, &d); printf(“%d ”, d); printf(“%d ”, c); printf(“%d ”, b); printf(“%d \n”, a); 3 numbers 4 numbers Example: Printing Numbers in Reverse

4 The Problem Suppose we have 10 numbers to handle Or 20 Or 100 Where do we store the numbers ? Use 100 variables ?? How to tackle this problem? Solution:  Use arrays

Printing in Reverse Using Arrays void main() { int n, A[100], i; printf(“How many numbers to read? “); scanf(“%d”, &n); for (i = 0; i < n; ++i) scanf(“%d”, &A[i]); for (i = n -1; i >= 0; --i) printf(“%d ”, A[i]); printf(“\n”); }

6 Using Arrays All the data items constituting the group share the same name int x[10]; Individual elements are accessed by specifying the index x[0]x[1]x[2]x[9] X is a 10-element one dimensional array

7 Declaring Arrays Like variables, the arrays used in a program must be declared before they are used General syntax: type array-name [size];  type specifies the type of element that will be contained in the array (int, float, char, etc.)  size is an integer constant which indicates the maximum number of elements that can be stored inside the array  marks is an array that can store a maximum of 5 integers int marks[5];

8 Examples: int x[10]; char line[80]; float points[150]; char name[35]; If we are not sure of the exact size of the array, we can define an array of a large size int marks[50]; though in a particular run we may only be using, say, 10 elements

9 Accessing Array Elements A particular element of the array can be accessed by specifying two things:  Name of the array  Index (relative position) of the element in the array In C, the index of an array starts from zero Example:  An array is defined as int x[10];  The first element of the array x can be accessed as x[0], fourth element as x[3], tenth element as x[9], etc.

10 Contd. The array index must evaluate to an integer between 0 and n-1 where n is the maximum number of elements possible in the array a[x+2] = 25; b[3*x-y] = a[10-x] + 5; Remember that each array element is a variable in itself, and can be used anywhere a variable can be used (in expressions, assignments, conditions,…)

11 A first example void main() { int i; int data[10]; for (i=0; i<10; i++) data[i]= i; i=0; while (i<10) { printf("Data[%d] = %d\n", i, data[i]); i++; } “data refers to a block of 10 integer variables, data[0], data[1], …, data[9]

12 The result void main() { int i; int data[10]; for (i=0; i<10; i++) data[i]= i; i=0; while (i<10) { printf("Data[%d] = %d\n", i, data[i]); i++; } Data[0] = 0 Data[1] = 1 Data[2] = 2 Data[3] = 3 Data[4] = 4 Data[5] = 5 Data[6] = 6 Data[7] = 7 Data[8] = 8 Data[9] = 9 Array size should be a constant Output

13 How is an array stored in memory? Starting from a given memory location, the successive array elements are allocated space in consecutive memory locations x: starting address of the array in memory k: number of bytes allocated per array element  a[i]  is allocated memory location at address x + i*k Array a

14 Storage void main() { int i; int data[10]; for(i=0; i<10; i++) printf("&Data[%d] = %u\n", i, &data[i]); } &Data[0] = &Data[1] = &Data[2] = &Data[3] = &Data[4] = &Data[5] = &Data[6] = &Data[7] = &Data[8] = &Data[9] = Output

15 Initialization of Arrays General form: type array_name[size] = { list of values }; Examples: int marks[5] = {72, 83, 65, 80, 76}; char name[4] = {‘A’, ‘m’, ‘i’, ‘t’}; The size may be omitted. In such cases the compiler automatically allocates enough space for all initialized elements int flag[ ] = {1, 1, 1, 0}; char name[ ] = {‘A’, ‘m’, ‘i’, ‘t’};

16 How to read the elements of an array? By reading them one element at a time for (j=0; j<25; j++) scanf (“%f”, &a[j]); The ampersand (&) is necessary The elements can be entered all in one line or in different lines

17 Passing Arrays to Function Array element can be passed to functions as ordinary arguments IsFactor (x[i], x[0]) sin (x[5])

18 Passing Entire Array to a Function An array name can be used as an argument to a function  Permits the entire array to be passed to the function  The way it is passed differs from that for ordinary variables Rules:  The array name must appear by itself as argument, without brackets or subscripts  The corresponding formal argument is written in the same manner Declared by writing the array name with a pair of empty brackets

19 Whole Array as Parameters const int ASIZE = 5; float average (int B[ ]) { int i, total=0; for (i=0; i<ASIZE; i++) total = total + B[i]; return ((float) total / (float) ASIZE); } void main ( ) { int x[ASIZE] ; float x_avg; x [] = {10, 20, 30, 40, 50}; x_avg = average (x) ; } Only Array Name/address passed. [ ] mentioned to indicate that is an array. Called only with actual array name

20 Contd. void main() { int n; float list[100], avg; : avg = average (n, list); : } float average (int a, float x[]) { : sum = sum + x[i]; } We don’t need to write the array size. It works with arrays of any size.

21 Arrays used as Output Parameters void VectorSum (int a[ ], int b[ ], int vsum[ ], int length) { int i; for (i=0; i<length; i=i+1) vsum[i] = a[i] + b[i] ; } void PrintVector (int a[ ], int length) { int i; for (i=0; i<length; i++) printf (“%d “, a[i]); } void main () { int x[3] = {1,2,3}, y[3] = {4,5,6}, z[3]; VectorSum (x, y, z, 3) ; PrintVector (z, 3) ; } vector-sum.c

22 Reading into an array void main() { const int MAX_SIZE = 100; int i, size; float marks[MAX_SIZE]; float total=0; scanf("%d",&size); for (i=0; i<size; i++) { scanf("%f",&marks[i]); total = total + marks[i]; } printf("Total = %f \n Avg = %f\n", total, total/size); } Total = Avg = Output

23 A Warning In C, while accessing array elements, array bounds are not checked Example: int marks[5]; : marks[8] = 75;  The above assignment would not necessarily cause an error  Rather, it may result in unpredictable program results

24 How to copy the elements of one array to another? By copying individual elements for (j=0; j<25; j++) a[j] = b[j]; The element assignments will follow the rules of assignment expressions Destination array must have sufficient size

25 Example 1: Find the minimum of a set of 10 numbers void main() { int a[10], i, min; for (i=0; i<10; i++) scanf (“%d”, &a[i]); min = a[0]; for (i=1; i<10; i++) { if (a[i] < min) min = a[i]; } printf (“\n Minimum is %d”, min); }

26 Example 2: Computing cgpa const int nsub = 6; void main() { int grade_pt[nsub], cred[nsub], i, gp_sum=0, cred_sum=0; double gpa; for (i=0; i<nsub; i++) scanf (“%d %d”, &grade_pt[i], &cred[i]); for (i=0; i<nsub; i++) { gp_sum += grade_pt[i] * cred[i]; cred_sum += cred[i]; } gpa = ((float) gp_sum) / cred_sum; printf (“\n Grade point average: is %.2lf”, gpa); } Handling two arrays at the same time

27 Things you cannot do You cannot  use = to assign one array variable to another a = b; /* a and b are arrays */  use == to directly compare array variables if (a = = b) ………..  directly scanf or printf arrays printf (“……”, a);

28 Recall

29 Recall

30

x=a a; Right to left evaluation of the expression. First update (rightmost) a to 11. Leftmost a =>11 x=0 a=12 31

Revisit loops 32

33 SUM = …+ N 2

34 SUM = …+ N 2 void main() { int N, count, sum; scanf (“%d”, &N) ; sum = 0; count = 1; while (count <= N) { sum = sum + count  count; count = count + 1; } printf (“Sum = %d\n”, sum) ; return 0; }

35 Maximum of positive Numbers

36 Maximum of positive Numbers void main() { double max = 0.0, next; printf (“Enter positive numbers, end with 0 or a negative number\n”); scanf(“%lf”, &next); while (next > 0) { if (next > max) max = next; scanf(“%lf”, &next); } printf (“The maximum number is %lf\n”, max) ; }

37 Find the sum of digits of a number digit-sum.c

38 Find the sum of digits of a number void main() { intn, sum=0; scanf (“%d”, &n); while (n != 0) { sum = sum + (n % 10); n = n / 10; } printf (“The sum of digits of the number is %d \n”, sum); } digit-sum.c

39 Test if a number is prime or not void main() { int n, i=2; scanf (“%d”, &n); while (i < n) { if (n % i == 0) { printf (“%d is not a prime \n”, n); break; } ++i; } if (i == n) printf (“%d is a prime \n”, n); }

40 More efficient?? void main() { int n, i = 2, flag = 0; double limit; scanf (“%d”, &n); limit = sqrt(n); while (i <= limit) { if (n % i == 0) { printf (“%d is not a prime \n”, n); flag = 1; break; } i = i + 1; } if (flag == 0) printf (“%d is a prime \n”, n); }

41 Some Loop Pitfalls while (sum <= NUM) ; sum = sum+2; for (i=0; i<=NUM; ++i); sum = sum+i; for (i=1; i!=10; i=i+2) sum = sum+i; double x; for (x=0.0; x<2.0; x=x+0.2) printf(“%f\n”, x);

42 Some observations on for Initialization, loop-continuation test, and update can contain arithmetic expressions for ( k = x; k <= 4 * x * y; k += y / x ) Update may be negative (decrement) for (digit = 9; digit >= 0; --digit) If loop continuation test is initially 0 (false)  Body of for structure not performed No statement executed  Program proceeds with statement after for structure

43 Example We can give several expressions separated by commas in place of expr1 and expr3 in a for loop to do multiple assignments for example for (fact=1, i=1; i<=10;++ i) fact = fact * i; for (sum=0, i=1; i<=N; ++i) sum = sum + i * i;

44