Presentation is loading. Please wait.

Presentation is loading. Please wait.

READING AND PRINTING MATRICES (with functions)

Similar presentations


Presentation on theme: "READING AND PRINTING MATRICES (with functions)"— Presentation transcript:

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

2 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"); }}

3 /* 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"); }

4 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]); }

5 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

6 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]

7

8 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.

9 * 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);}

10 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].

11 * 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);}

12

13 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.

14 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.

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

16 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.

17 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.

18 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?

19 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;

20 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

21 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.

22 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; };

23 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.

24 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.

25 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.

26 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

27 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


Download ppt "READING AND PRINTING MATRICES (with functions)"

Similar presentations


Ads by Google