Programming Arrays. Example 1 Write a program that reads 3 numbers from the user and print them in reverse order. How many variables do we need to store.

Slides:



Advertisements
Similar presentations
The debugger Some programs may compile correctly, yet not produce the desirable results. These programs are valid and correct C programs, yet not the programs.
Advertisements

1 Various Methods of Populating Arrays Randomly generated integers.
Exercise 4 1. Write a program that simulates coin tossing. For each toss of the coin the program should print Heads or Tails. Let the program toss the.
Dr. Sajib Datta  We can also have arrays of arrays, also known as multidimensional arrays.  E.g., A two-dimensional array is an array of several.
Arrays H&K Chapter 8 Instructor – Gokcen Cilingir Cpt S 121 (July 13, 2011) Washington State University.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
Guidelines for working with Microsoft Visual Studio.Net.
LOOP (Part 2) for while do-while 1. TK1913-C Programming2 TK1913-C Programming 2 Loop : for Loop : for Condition is tested first Loop is controlled by.
Multiple-Subscripted Array
Parameter Passing to Functions in C. C Parameter passing Review of by-value/by-reference.
Complementary tutorial - arrays, loops, riddles Prepared by: Valentin Kravtsov.
לולאות 02 יולי יולי יולי 1502 יולי יולי יולי 1502 יולי יולי יולי 15 1 Department of Computer Science-BGU.
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
Computer programming Lecture 5. Lecture 5: Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character arrays.
WEEK 4 Class Activities Lecturer’s slides.
UNIT 14 Functions with Pointer Parameters.
Chapter 6: Control Structures Computer Programming Skills Second Term Department of Computer Science Foundation Year Program Umm Alqura.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
CSE 251 Dr. Charles B. Owen Programming in C1 Pointers, Arrays, Multidimensional Arrays Pointers versus arrays – Lots of similarities How to deal with.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
C Programming Lecture 7 : Control Structures. Control Structures Conditional statement : if, switch Determine a block of statements to execute depending.
Dr. Soha S. Zaghloul2 Let arr be an array of 20 integers. Write a complete program that first fills the array with up to 20 input values. Then, the program.
Functions Exercise 5. Functions a group of declarations and statements that is assigned a name  effectively, a named statement block  usually has a.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
FUNCTION Dong-Chul Kim BioMeCIS UTA 12/7/
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
Introduction to Computer Organization & Systems Topics: C arrays C pointers COMP Spring 2014 C Part IV.
Arrays. Collections We would like to be able to keep lots of information at once Example: Keep all the students in the class Grade each one without writing.
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
Functions. Why use functions? They can break your problem down into smaller sub-tasks (modularity).  easier to solve complex problems They make a program.
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 10 Multidimensional Arrays.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Principle Prog Revision. Question 1 (a) Identify errors in the following program segment and how the errors can be corrected. void main(){ constant int.
Computer Programming for Engineers
DG8. FILE * fopen ( const char * filename, const char * mode ); Mode: r: Open a file for reading. The file must exist. w: Create an empty file for writing.
8. ARRAYS. Aggregate variables Scalar variables –Single value Aggregate variables –Collection of values –Arrays: elements have the same type.
Dr. Sajib Datta Feb 11,  Example of declaring and initializing an array. ◦ double someData[3]; /* declare the array someData that will.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
1 More on Arrays. 2 Review: Passing Arrays to Functions Passing an array: what goes on in the memory? Why isn’t it the same as when passing primitives?
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
Dr. Sajib Datta Sep 10,  #include  void main()  {  int a = 25;  int b = 0;  int c = -35;  if( a || b ) ◦ printf("Test1\n");  else.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
Arrays Name, Index, Address. Arrays – Declaration and Initialization int x; y[0] y[1] y[2]
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
Programming Arrays.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
CS1010 Programming Methodology
Functions Dr. Sajib Datta
Array 9/8/2018.
CS1010 Programming Methodology
Control Structures Lecture 7.
Chapter 13 Control Structures
Looping.
Engineering Programming A
Lec 7.
Lecture 10 Arrays.
Chapter 8 The Loops By: Mr. Baha Hanene.
Computer Programming Fall 2012 תרגול 6 פונקציות
Arrays Chapter 8 Copyright © 2008 W. W. Norton & Company.
Functions with arrays.
Incremental operators
Exercise Arrays.
EECE.2160 ECE Application Programming
Presentation transcript:

Programming Arrays

Example 1 Write a program that reads 3 numbers from the user and print them in reverse order. How many variables do we need to store the input? How could we cope with 100 numbers? 1000? We need a “variable” that can store a series of values

Solution /* get 10 integers from the user and print them in reversed order */ #include #define ARRAY_SIZE 10 int main(void) { int i = 0; int array[ARRAY_SIZE]; printf("please enter %d numbers:\n", ARRAY_SIZE); for (i = 0; i < ARRAY_SIZE; ++i) scanf("%d", &array[i]); printf("numbers in reversed order:\n"); for (i = ARRAY_SIZE - 1; i >= 0; --i) printf("%d ", array[i]); printf("\n"); return 0; }

Example 2 - Part A Write a Function: int how_many(int arr[], int size, int value) {…} Input: arr = array of integers; size = size of arr; value - some integer; Output: Function returns the number of times value appears in arr. For example: arr = Then : how_many (arr, 5, 12 ) 2 how_many (arr, 5, 0 ) 1 how_many (arr, 5, 1 )

Solution - Part A int how_many(int arr[], int size, int value) { int i, count=0; for(i = 0; i < size; i++) if (arr[i] == value) count++; return count; } 5

Example 2 - Part B Write a Function: int most_popular(int arr[], int size) {…} Input: arr = array of integers; size = size of arr; Output: Function returns the most frequent integer in array. For example: arr = Then : most_popular (arr, 5)

Solution - Part B int most_popular(int arr[], int size) { int i, count, max_index, max=0; for (i = 0; i < size; i++) { count = how_many(arr, size, arr[i]); if (count > max) { max = count; max_index = i; } return arr[max_index]; } 7

class Write a program that reads 30 numbers from the user and determines if any number was entered more than once. 8

Example 3 Implement a function that accepts:  Two integer matrices  Number of rows The function returns 1 if the matrices are equal, 0 otherwise. Assume the matrices are of the same size Note that when passing matrices as parameters, the second subscript must be specified and it must be constant 9

Solution int compare_matrices(int mat1[][SIZE], int mat2[][SIZE], int rows) { int i,j; /* for each row */ for(i = 0; i < rows; i++) /* for each column */ for (j=0; j < SIZE; j++) /* compare the values */ if (mat1[i][j] != mat2[i][j]) /* if not equal, return false */ return 0; /* If we got here, matrices are identical */ return 1; } 10

Debug 1: One Equal Element #include #define SIZE 5 int oneEqualElement (int arr1[], int arr2[], int size) { int i; for (i = 0; i <= size; ++i) if (arr1[i] = arr2[i]) printf("found an equal element = %d\n", arr1[i]); return 1; return 0; } int main() { int a1 [] = {1,2,3,4,5}; int a2 [] = {6,7,8,9,10}; int a3 [] = {9,8,7,6,5}; int a4 [] = {4,3,2,1}; printf("equal %d\n",oneEqualElement(a1,a2,SIZE)); // false printf("equal %d\n",oneEqualElement(a1,a3,SIZE)); // true printf("equal %d\n",oneEqualElement(a1,a4,SIZE)); // false return 0; } 11

Debug 2: Approximate PI /*This program approximates pi using the formula: pi^2/6 = 1/1 + 1/4 + 1/9 +...*/ #include int main() { int i, num; double result = 0.0; printf("enter number of terms\n"); scanf("%d", &num); for (i = 1; i <= num; i++); result += 1.0 / (i * i); printf(“Approximated pi = %g\n",sqrt(6*result)); return 0; } 12

Example 4 array vs. primitives as functions arguments #include #define SIZE 3 void f1 (int arr[], int size) { int rr = rand() % size; arr[rr] = 0; } void f2 (int x) { x = x + 1; } int main(void) { int a [] = {1, 2, 3}; int b = 1; srand(23);// Use a seed to initialize a random series f1(a, SIZE); f2(b); printf("a = [%d %d %d], b = %d\n", a[0], a[1], a[2], b); return 0; } Random index in the range 0 – SIZE-1 13

Example 5 Write a Function: void merge (int arr1[], int arr2[], int size1, int size2, int result[]){…} Input:  2 sorted arrays arr1[] and arr2[];  size1 is the number of elements in arr1[];  size2 is the number of elements in arr1[]; Output:  Copy the content of arr1 and arr2 into result[], but such that result[] appears to be sorted. For Example Arr1 = Arr2 = Result =

Solution void merge(int arr1[],int arr2[],int size1,int size2,int result[]) { int idx1, idx2, res_idx; for (idx1 = 0,idx2 = 0, res_idx = 0; idx1 < size1 && idx2 < size2; res_idx++) { if (arr1[idx1] < arr2[idx2]) result[res_idx] = arr1[idx1++]; else result[res_idx] = arr2[idx2++]; } while (idx1 < size1) result[res_idx++] = arr1[idx1++]; while (idx2 < size2) result[res_idx++] = arr2[idx2++]; return; } 15

#include #define SIZE 30 int main() { int i, j;// Counters int twice = 0;// Flag int arr[SIZE];// Stores the input from the user printf("Enter %d numbers:\n", SIZE); for (i = 0; i < SIZE; i++) scanf("%d", &arr[i]); for (i = 0; i < SIZE; i++) for (j = 0; j < i; j++) if (arr[i] == arr[j]) twice = 1; if (twice) printf("A number was entered more than once\n"); return 0; } Class Solution 16

If Time Allows…loops questions 17

Q1 עיינו בקטע הבא וסמנו את כל התשובות הנכונות: int k = 10, sum = 0; int j; for (j = 0; j < k; j = k - 1) sum = sum + 1; After execution the value of k is 10 This code will fail in compilation After execution the value of j is 9 There will be an infinite loop Non of these answers is correct 18

Q2 עיינו בקטע הבא וסמנו את כל התשובות הנכונות: int sum = 0,number; for (number=1; number<=10; number=number+1) number = number - 1; printf(“%d”,sum); This code will fail in compilation 0 will be printed 55 will be printed 45 will be printed Non of these answers is correct 19

Q3 עיינו בקטע הבא וסמנו את כל התשובות הנכונות: int i; for (i = 0; i < 10; i = i + 1) for (i = 0; i < 9; i = i + 1) printf(“*”); 90 ‘*’ will be printed There will be an infinite loop 10 ‘*’ will be printed This code will fail in compilation Non of these answers is correct 20