Procedural Programming

Similar documents
Fundamentals of Programming & Procedural Programming

Fundamentals of Programming & Procedural Programming

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

C++ PROGRAMMING SKILLS Part 4: Arrays

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

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

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

Fundamentals of Programming & Procedural Programming

Two Dimensional Array - An array with a multiple indexs.

Module 6: Array in C

EC312 Chapter 4: Arrays and Strings

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

Arrays. Week 4. Assylbek Jumagaliyev

C Arrays Pearson Education, Inc. All rights reserved.

Principles of Programming. Chapter 6: Arrays

Chapter 3: Arrays and More C Functionality

Introduction to C Final Review Chapters 1-6 & 13

Computer Programming: C++

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

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

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

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

Two Dimensional Array - An array with a multiple indexs.

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

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

Write a C program using arrays and structure

Procedural programming with C

Arrays and Strings. Arash Rafiey. September 12, 2017

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

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

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

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

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

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Multiple-Subscripted Arrays

Computer Science & Engineering 150A Problem Solving Using Computers

Sorting & Searching. Hours: 10. Marks: 16

Chapter 7 : Arrays (pp )

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

Introduction to FCE1

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

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

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

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

ARRAYS(II Unit Part II)

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Introduction to Computer Science Midterm 3 Fall, Points

Fundamentals of Computer Programming Using C

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

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

Programming for Engineers Arrays

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

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

Chapter 6 Pointers and Arrays

Arrays and Applications

Arrays. Systems Programming Concepts

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

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #04

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

Data Structure & Algorithms Laboratory Manual (CS 392)

Single Dimension Arrays

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

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Functions. Arash Rafiey. September 26, 2017

Introduction. C provides two styles of flow control:

Advanced Computer Programming

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

Lecture 04 FUNCTIONS AND ARRAYS

Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

C: How to Program. Week /Apr/23

CpSc 1111 Lab 4 Formatting and Flow Control

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

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

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

Introduction to Arrays

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.

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

Computer Programming Lecture 14 Arrays (Part 2)

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Universität Duisburg-Essen FCE 1. Experiment 4. Microprogramming

ECE264 Fall 2013 Exam 1, September 24, 2013

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

Review of Important Topics in CS1600. Functions Arrays C-strings

Unit 3 Decision making, Looping and Arrays

BITG 1113: Array (Part 1) LECTURE 8

'C' Programming Language

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

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

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

Programming in OOP/C++

CSCI 2132 Software Development. Lecture 18: Functions

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

Chapter 10. Arrays and Strings

Transcription:

Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Procedural Programming Session Five: Arrays Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing. Joachim Zumbrägel Universität Duisburg-Essen Faculty of Engineering, Department Electrical Engineering and Information Technology Computer Engineering Procedural Programming/Lab5 1

Introduction Sometimes it s rather useful to store same type of data together. In programming, this is done using an array. Arrays are a collection of variables having the same data type, placed contiguously in memory. Declaring an Array Like the other variables, an array needs to be defined. The computer needs to know what kind of an array we need, and how large it should be. We can declare an array as array_type array_name [array_size ]; For example: int temp[7]; Here int specifies the data type of the array variable, just like when used with simple variables, and the word temp is the name of the array. The subscript [7], tells how many variables of the type int will be in array. Any one of these elements may be referred to by giving the array name followed by the position number of the particular element in the square brackets [ ]. First element in an array is always the zero th element. So the first element of the array temp is referred to as temp[0], the second as temp[1 ] and so on. The following figure shows a graphical illustration of what the array looks like: 0 1 2 3 4 5 6 temp Initializing Array Elements To initialize an array we can use the array name along with its reference, followed by an equal sign. For example: temp[0] = 10; temp[1] = 20; An array can also be initialized along with the array declaration by following the declaration with an equal sign and a comma separated list enclosed in the braces of initializers. For example: int temp[7] = 10, 20, 30, 40, 50, 60, 70; Procedural Programming/Lab5 2

The initialization of an array must not be necessarily complete. What means it is allowed to initialize just some of the array elements. For example: int temp[7] = 10, 20, 30; The example above initializes only the first three elements (temp[0], temp[1],temp[2]. All other elements t(emp[3] temp[6]) will be initialized with 0. Hint: If you don t initialize an array which has a local scope (what means it is defined within a function) the elements of the array have random values. When you define an array with a global scope all elements will initialized with 0. Accessing Array Elements by Subscript We can refer to an array's element by its number. This allows us to use a variable, usually called a subscript, to reference the elements in the array. For example: double temp[7] = 10, 20, 30, 40, 50, 60, 70; int i; So now, if we execute i = 3; then temp[i] refers to the element temp[3], which has the value 40. If we now execute i = 1; then temp[i] refers to the element temp[1], which has the value 20. Exercise 5.1: Declare an array studentpercentage of type integer that will store the percentages of students in a class of 25. Exercise 5.2: Assign the value 76.5 to array element nine. Procedural Programming/Lab5 3

Exercise 5.3: Name the fourth element of the array. Exercise 5.4: Refer to the array element 10. Exercise 5.5: Print array elements 3 and 5 with two digits of precision to the right. Exercise 5.6: Assign the value 80.50 to the seventh element of the array. Exercise 5.7: In the following declaration, what values would each array element be initialized to: int array[5] = 1,2,3; Procedural Programming/Lab5 4

Example: The following program computes and prints the total and average of five numbers using arrays: /* example: arrays */ #include <stdio.h> int main() float nums[5]; float total; float average; nums[0] = 30; nums[1] = 25; nums[2] = 42; nums[3] = 86; nums[4] = 23; total = nums[0] + nums[1] + nums[2] + nums[3] + nums[4]; average = total / 5; printf("total = %2.f, Average = %2.f \n", total, average); return 0; Procedural Programming/Lab5 5

Processing an Array In order to process an array, the for loop is an ideal control structure to use with it. The subscript of the array will act as the counter of the for loop. With each iteration, of the loop, the loop body will process the array element which is specified by the subscript. Suppose that you just finished taking classes at a local university and want to average your six class scores. The following program initializes one array for the school name and another for the six classes. The body of the program averages each of the six scores. Example: /* example: Average of five test marks */ #include <stdio.h> int main() char sname[] = University of Duisburg-Essen ; float marks[5] = 88.7, 90.4, 76.0, 100.0, 86.7; float average = 0.0; int ctr; /* Calculating total of the marks */ for (ctr = 0; ctr < 5; ctr++) average += marks[ctr]; /* Calculating the average */ average /= (float)5; printf("at %s, your class average is %.1f.", sname, average); return 0; Procedural Programming/Lab5 6

Exercise 5.8: Print all the elements of the array marks[], one by one, from Exercise 5.1, using a for loop within a function. Exercise 5.9: Write a loop which initializes 10 elements of an integer array counts to zeros. Procedural Programming/Lab5 7

Searching an Array Arrays are one of the main ways through which data is stored in C programs. There can be many places where they are used, ranging from employee payroll program to customer account processing in a bank. Data is usually read into an array from the keyboard or from files. File processing is described in a later session. For now, you should just know how to process the arrays. To search an array, you don t need to know any special types of new command or functions. The if statement and the for loop is basically all you need. To search for a particular value in an array, you need to compare each element in that array using the if statement to check whether they match or not. if they don t, you have to keep searching till they match or till you run out the array elements. Example: /* exercise: Searching the highest value in the array */ #include <stdio.h> #define SIZE 15 int main() // Store some values in the array */ int array[size] = 5,2,7,8,36,4,2,86,11,43,22,12,45,6,85; int highestval, ctr; highestval = array[0]; //Initializes with first array element for (ctr = 1; ctr < SIZE; ctr++) // Stores current value if it is higher than the highest so far if (array[ctr] > highestval) highestval = array[ctr]; printf("the highest number in the list is %d.", highestval); return 0; Procedural Programming/Lab5 8

Explanation: In the given example, to find the highest number in an array, the program compares each element with the first one. If it finds a higher value, it becomes the basis for the rest of the array. This continues till the end of the array is reached and you have the highest value. The #define keyword is a preprocessing directive. So for example, in the above code: #define SIZE 15 int array[size] actually gets swapped for int array[15] when the compiler comes across it. Sorting Arrays Sorting can be defined as the process of placing data in order whether alphabetically or numerically. It is one of the most common and important tasks in computer applications. Practically every organization sorts their data in one way or another. For example, a phone company may sort their phone directories by customer last name in order to make it easy when searching for phone numbers. There are virtually hundreds of different ways to sort an array, but the main goal of these methods is to compare each element of an array to another element and swap them if they are in a wrong order. The bubble sort is one of the easiest of the most commonly used algorithms for sorting arrays; therefore we will use this as an example. Example: /* Using Bubble Sort as a Function */ #include <stdio.h> void bubble_sort(int [], int); int main() int array[100], n, c, d; printf("how many elements do you want to enter?\n"); scanf("%d", &n); printf("enter %d the elements:\n", n); for (c = 0; c < n; c++) Procedural Programming/Lab5 9

scanf("%d", &array[c]); bubble_sort(array, n); printf("sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0; void bubble_sort(int list[], int num) int x, y, temp; //Bubble sort function for(x = 0; x < num; x++) for(y = 0; y < num-x-1; y++) if(list[y] > list[y+1]) temp = list[y]; list[y] = list[y+1]; list[y+1] = temp; Explanation: This algorithm basically works by repetitively going through the list, comparing each pair of adjacent values and swapping them if they are in the incorrect position. The algorithm keeps on repeating till no more swapping is needed, which indicates that the list is sorted. This is done by using a third temporary variable to temporary hold values of those two variables which we want to swap with each other. Procedural Programming/Lab5 10

Multidimensional Arrays It is also possible for arrays to have two or more dimensions. This allows them to imitate multidimensional objects such as tables with rows and columns. Declaring Multidimensional Arrays In order to declare a two dimensional array, specify the array data type and the size of the array and then place the number of rows and the number of columns each in its own square bracket. For example: int student_grade[7][10]; The above statement declares a two dimensional array of integers of size 7 rows x 10 columns. Exercise 5.10: Define a 2 x 5 integer array named as students. Exercise 5.11: Declare a two dimensional array that will hold temperatures for each hour of the day for a whole year. Procedural Programming/Lab5 11

Example: The following program stores temperature for each day of the week for a whole month in a two dimensional array of size 4 x 7: /* example: multidimensional_arrays */ #include <stdio.h> int main() int monthtemps[4][7]; printf("enter the temp for week 1 day 1: "); scanf("%d", &monthtemps[0][0]); printf("enter the temp for week 1 day 2: "); scanf("%d", &monthtemps[0][1]); printf("enter the temp for week 1 day 3: "); scanf("%d", &monthtemps[0][2]); printf("enter the temp for week 1 day 4: "); scanf("%d", &monthtemps[0][3]); printf("enter the temp for week 1 day 5: "); scanf("%d", &monthtemps[0][4]); printf("enter the temp for week 1 day 6: "); scanf("%d", &monthtemps[0][5]); printf("enter the temp for week 1 day 7: "); scanf("%d", &monthtemps[0][6]); printf("enter the temp for week 2 day 1: "); scanf("%d", &monthtemps[1][0]); printf("enter the temp for week 2 day 2: "); scanf("%d", &monthtemps[1][1]); printf("enter the temp for week 2 day 3: "); scanf("%d", &monthtemps[1][2]); printf("enter the temp for week 2 day 4: "); scanf("%d", &monthtemps[1][3]); printf("enter the temp for week 2 day 5: "); scanf("%d", &monthtemps[1][4]); printf("enter the temp for week 2 day 6: "); scanf("%d", &monthtemps[1][5]); printf("enter the temp for week 2 day 7: "); Procedural Programming/Lab5 12

scanf("%d", &monthtemps[1][6]); printf("enter the temp for week 3 day 1: "); scanf("%d", &monthtemps[2][0]); printf("enter the temp for week 3 day 2: "); scanf("%d", &monthtemps[2][1]); printf("enter the temp for week 3 day 3: "); scanf("%d", &monthtemps[2][2]); printf("enter the temp for week 3 day 4: "); scanf("%d", &monthtemps[2][3]); printf("enter the temp for week 3 day 5:"); scanf("%d", &monthtemps[2][4]); printf("enter the temp for week 3 day 6:"); scanf("%d", &monthtemps[2][5]); printf("enter the temp for week 3 day 7:"); scanf("%d", &monthtemps[2][6]); printf("enter the temp for week 4 day 1: "); scanf("%d", &monthtemps[3][0]); printf("enter the temp for week 4 day 2: "); scanf("%d", &monthtemps[3][1]); printf("enter the temp for week 4 day 3: "); scanf("%d", &monthtemps[3][2]); printf("enter the temp for week 4 day 4: "); scanf("%d", &monthtemps[3][3]); printf("enter the temp for week 4 day 5: "); scanf("%d", &monthtemps[3][4]); printf("enter the temp for week 4 day 6: "); scanf("%d", &monthtemps[3][5]); printf("enter the temp for week 4 day 7: "); scanf("%d", &monthtemps[3][6]); return 0; Procedural Programming/Lab5 13

Exercise 5.12: Declare a two dimensional array that contains 15 rows, each of which will store 12 integers. Exercise 5.13: State whether there is any difference between the following two array declarations: a) int arr1[2][3] = 1, 2, 3,4, 5, 6; b) int arr2[2][3] = 1, 2, 3, 4, 5, 6; Procedural Programming/Lab5 14