READING AND PRINTING MATRICES (with functions)

Slides:



Advertisements
Similar presentations
Unions The storage referenced by a union variable can hold data of different types subject to the restriction that at any one time, the storage holds data.
Advertisements

Dynamic Memory Allocation
1 ICS103 Programming in C Lecture 16: 2-Dimensional Arrays.
Stack and Heap Memory Stack resident variables include:
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
Arrays- Part 2 Spring 2013Programming and Data Structure1.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Chapter 11 Structure and Union Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
1. 1. Introduction to Array 2. Arrays of Data 3. Array Declaration 4. Array Initialization 5. Operations on Array 6. Multidimensional Arrays 7. Index.
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.
2D Arrays Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Spring 2006.
chap11 Chapter 11 Structure and Union Types.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
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.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
Strings C supports strings using one-dimensional character arrays. A string is defined as a null-terminated character array. In C, a null is 0. You must.
Lesson #7 Arrays‏.
Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining.
Numbers in ‘C’ Two general categories: Integers Floats
Stack and Heap Memory Stack resident variables include:
Lesson #8 Structures Linked Lists Command Line Arguments.
‘C’ Programming Structures and Commands
Computer Science 210 Computer Organization
Functions and Pointers
Programming application CC213
CS1010 Programming Methodology
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
EKT120 : Computer Programming
Variables have a type have an address (in memory) have a value
Array 9/8/2018.
Lecture 7 – Arrays (1) PGT 106 : C PROGRAMMING.
Module 2 Arrays and strings – example programs.
2-D arrays a00 a01 a02 a10 a11 a12 a20 a21 a22 a30 a31 a32
Some examples.
Functions and Pointers
Computer Science 210 Computer Organization
Dynamic memory allocation and Intraprogram Communication
CS1100 Computational Engineering
Programming and Data Structures
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
EKT150 : Computer Programming
CSC215 Lecture Memory Management.
CS111 Computer Programming
EKT120: Computer Programming
A function with one argument
Classes and Objects.
Outline Defining and using Pointers Operations on pointers
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
2-d Arrays.
Structure and Union Types
Dr Tripty Singh Arrays.
WEEK-2.
Submitted By : Veenu Saini Lecturer (IT)
Functions Department of Computer Science-BGU יום שישי 26 אפריל 2019.
Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
ICS103 Programming in C Lecture 12: Arrays I
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Chapter 10 C Structures and Unions
Chapter 11 Structure and Union Types.
Getting Started With Coding
Presentation transcript:

READING AND PRINTING MATRICES (with functions) PROGRAM? READING AND PRINTING MATRICES (with functions)

Functions and 2D Arrays /* PROGRAM # 81 */ /* READING AND PRINTING MATRICES */ #include <stdio.h> #define row 3 #define column 5 /* When using a 2D array as an argument, */ /* We don't need to indicate the 1st dimension */ /* We can mention the 1st dimension if we want */ void GetMatrix(int Mat[ ][column]); void PrintMatrix(int Mat[ ][column]); main( ){ int MatA[row][column]; /* Declare a 2D matrix */ GetMatrix(MatA); /* Call function to input the matrix*/ PrintMatrix(MatA); /* Call function to display the matrix */ }/* To get elements of a matrix from the user */ void GetMatrix(int Mat[ ][column]){ int i, j; puts(""); for(i= 0; i<row; i++) for(j= 0; j<column; j++){ printf("Matrix[%d][%d]: ", i, j); scanf("%d", &Mat[i][j]); }}/* To print a matrix */ void PrintMatrix(int Mat[ ][column]){ for(i= 0; i<row; i++){ for(j= 0; j<column; j++) printf("%5d",Mat[i][j]); printf("\n"); }}

/* To get elements of a matrix from the user */ /* PROGRAM # 84 */ void GetMatrix(int Mat[ ][column]){ int i, j; puts(“”); for(i= 0; i<row; i++) for(j= 0; j<column; j++){ printf("Matrix[%d][%d]: ”, i, j); scanf(“%d”, &Mat[i][j]); } } /* To perform matrix addition */ void AddMatrices(int A[ ][column], int B[ ][column], int C[ ][column]){ for(j= 0; j<column; j++) C[i][j]=A[i][j]+B[i][j]; } /* To print a matrix */ void PrintMatrix(int Mat[ ][column]){ for(i= 0; i<row; i++){ printf("%5d",Mat[i][j]); printf("\n"); }

DYNAMIC ARRAY - EXAMPLE /* PROGRAM # 92 */ /* USE OF MALLOC */ #include<stdio.h> #include<stdlib.h> main( ){ int i, array_size; int *LIST; /* LIST is the name of the array */ /* Get the size of the array */ printf(“Please enter the size of the array: “); scanf("%d", &array_size); /* allocate enough memory to list */ /* LIST= (int *) calloc(array_size, sizeof(int) ); */ LIST= (int *) malloc ( array_size * sizeof(int) ); /* get the elements of the array from the user */ for(i=0; i<array_size; i++) scanf("%d", &LIST[i]); /* print the array */ printf("%d\n", LIST[i]); }

Dynamic Array vs. Static Array Q) How to create a regular array? Must declare the array at the top of program before starting the first C expression Must select a valid name for the array Must decide about the type of the array Must make an educated guess about the max size of the array

Example: int LIST[20]; LIST is an array of 20 integer elements, i.e., LIST[0], LIST[1], …, LIST[19] NOTE: LIST is a pointer to LIST[0], i.e., LIST  &LIST[0]

2D Dynamic Allocation The Software Engineer's Method There are two methods to do dynamic allocation for two dimensional arrays The first one is called the “software engineer's method”. With this method, the dynamic allocation of 2D arrays is easily done. You can simulate a two dimensional array with a single, dynamically allocated one-dimensional array. However, you must now perform subscript calculations manually, accessing the [i][j]th element with [i *ncolumns + j]. Software engineers prefer this method for its elegance and efficiency.

* Dynamic allocation of a 2D array (Software Engineer's Method) * #include <stdio.h> #include <stdlib.h> /* Dynamic allocation of arrays of more than one dimension is easily done. You can simulate a two-dimensional array with a single, dynamically-allocated one-dimensional array. However, you must now perform subscript calculations manually, accessing the [i][j]th element with array[i * ncolumns + j]. Software engineers prefer this method for its elegance and efficiency */ int main (void){ int nrows, ncols, i, j; int *numbers; /* pointer to the first cell ([0]) */ printf ("How many rows and columns?> "); scanf ("%d%d", &nrows, &ncols); numbers = (int *) calloc (nrows*ncols, sizeof(int)); /* allocating the array of integers */ i=1; j=1; numbers[i*ncols+j] = 9; /* initializes one value to 9 */ for (i=0; i<nrows; i=i+1) { for (j=0; j<ncols; j=j+1) printf ("%3d ", numbers[i*ncols+j]); } printf ("\n"); } free (numbers); return (0);}

2D Dynamic Allocation The Computer Scientist's Method The second method is called the traditional or “computer scientist's” method. In this method, dynamic allocation of 2D can be done by using a pointer pointing to an array of pointers and each pointer of that array pointing to an array of values. You are then allocating dynamically arrays of arrays. With that method you can use the real 2D subscripts like array[i][j].

* Dynamic allocation of a 2D array * (Computer Scientist's Method) #include <stdio.h> #include <stdlib.h> /* Dynamic allocation of arrays of more than one dimension can also be done using a pointer pointing to an array of pointer and each pointer of that array pointing to an array of values. With that method you can use the real 2-D subscripts like array[i][j] */ int main (void){ int nrows, ncols, i, j; int **numbers; /* pointer to the first cell ([0][0]) */ printf ("How many rows and columns?> "); scanf ("%d%d", &nrows, &ncols); numbers = (int **) calloc (nrows, sizeof(int *)); /* allocating the array of pointers */ for (i=0; i<ncols; ++i) /* allocating the array of integers */ numbers[i] = (int *) calloc (ncols, sizeof(int)); i=1; j=1; numbers[i][j] = 9; /* initializes one value to 9 */ for (i=0; i<nrows; i=i+1) { for (j=0; j<ncols; j=j+1) { printf ("%3d ", numbers[i][j]); } printf ("\n"); } /* freeing the array */ for (i=0; i<ncols; ++i) free (numbers[i]); free (numbers); return (0);}

Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining to particular objects. Unlike an array, a structure can have individual components that contain data of different types.

Data Structure A single variable of a composite type designed for planets can store a planet’s name, diameter, number of moon, the number of years to complete one solar orbit, and the number of hours to make one rotation on its axis. Each of these data items is stored in a separate component of the structure and can be referenced by using the component name.

Structures (User-defined data types) DATA STRUCTURE- TYPE DEFINITION POINTER TO A STRUCTURE C FUNCTIONS AND STRUCTURE

User-Defined Structure Types A database is a collection of information stored in a computer’s memory or in a disk file. A database is subdivided into records, which normally contain information regarding specific data objects. the structure of the record is determined by the structure of the object’s data type.

Structure Type Definition Before a structure data object can be created or saved, the format of its components must be defined. Although C provides several ways to define structures, we will explore just one approach-defining a new data type for each category of structured objects.

C Data Structure So far, we could not mix a type char and a type int within a single data type. However, sometimes we need to mix different data types. How can we do this? With the use of C Structure A collection of data elements of different types HOW to define a C structure?

Data Structure - Type Definition typedef: type definition Allows the user to define another names for a C data type. Declaration: typedef exsiting_data_type New_name_for_the_same_data_type; e.g. typedef int integer;

General Synatx: struct structure_name{ data_type member1; . data_type memberN; }; struct: C keyword data_type: data type for each element member: variable name structure_name: structure name

Example: As part of a project for our local observatory, we are developing a database of the planets in our solar system. For each planet, we need to represent information like the following: Name: Jupiter Diameter:142,800 km Moon:16 Orbit time:11.9 yr Rotation time:9.925 hr We can define a structure type planet_t to use in declaring a variable in which to store this information. There must be five components in the structure type, one for each data item. we must specify the name of each component and the type of information stored in each component. we choose the name in the same way we choose all identifiers: The names describe the nature of the information represented. The contents of each component determine the appropriate data type. for example, the planet’s name should be stored in a component that is array of characters.

Creating a new type structure allows us to aggregate variables of different types under one logical name. The structure type planet_t has five distinct components. # define STRSIZ 10 struct planet_t { char name [STRSIZ]; int moon; double diameter; double orbi_time; double rotation_time; };

Creating a new type The declaration of new types usually happens before the main program, just after the preprocessor directives so that the new types are known in all the functions of the program. Inside a function though, it is necessary, as for the other usual types to declare variables.

Sample Structure Definition We create a new data type here called struct planet_t. planet_t has 5 members of different type. These members are: name [STRSIZ]; moon; diameter; orbi_time; rotation_time; Any variable of type planet_t will have the same members. HOW TO DECLARE VARIABLES OF TYPE STRUCTURE Same way that we declare any other variable of other data types.

Example! /* USE OF STRUCTURES */ #include <stdio.h> /* Declare and initialize a structure */ struct MyRecord{ char MyFirstName[20]; char MyLastName[30]; char MyEmployeeNumber[10]; char MySIN[9]; char MyTelNumber[12]; int MyAge; double MySalary; }; main( ){ struct MyRecord VAR1; struct MyRecord VAR2; int VAR3; … } NOTE: Name of the structure that we defined here is struct MyRecord.

HOW TO ACCESS MEMBERS OF A STRUCTURE Member of operator OR dot operator Specify the name of the structure followed by a dot followed by the name of the member. e.g. VAR1.MyAge VAR1.MySalary …

Program! Employee’s Last Name Employee Number Employee’s S.I.N Employee’s Tel. Number Employee’s Age Employee’s Salary AnnualSalary Calculate Approx. TAX, TaxRate 0.20