3. Repetitive Structures (Loops)

Size: px
Start display at page:

Download "3. Repetitive Structures (Loops)"

Transcription

1 3. Repetitive Structures (Loops) We can make a program to repeat sections of statements (iterate) by using the DO loop construct. There are three forms: The DO loop with a counter, The DO-EXIT Construct The DO-WHILE Construct. 3.1 The DO Loop with a Counter In this type of looping, the repetition is controlled by a counter. It has the following general form: DO counter = initial value, limit, step size. Block of statements. For example DO I = 4, 10, 2 PRINT *, I, I**2, I**3 gives: For example DO I = 10, 4, -2 PRINT *, I, I**2, I**3 gives:

2 Ex: Write a program to find the sum of the numbers from PROGRAM SUMMATION INTEGER :: i, sum sum=0 Do i=1,100 sum=sum + i PRINT *, "sum=",sum END PROGRAM SUMMATION 3.2 DO-EXIT Construct In this type of looping, the repetition is controlled by a logical expression (condition). It has the following general form: DO statement sequence_1 IF ( a simple or compound condition ) EXIT statement sequence_2 The loop is repeated until the condition (a logical expression) in IF statement becomes false. If the condition is true, the loop is terminated by EXIT statement. This loop is used when we do not know how many iterations are required. The following program section outputs the even numbers 10, 8,..., 2 and their squares: N=10! initial value DO PRINT *,N,N**2 IF(N<4) EXIT N=N-2! decrement Output:

3 Study the following piece of code DO PRINT *, "Enter the radius of the circle:" READ *, r PRINT *, "Area is ", 3.14*r**2 PRINT *, "Do you want to calculate another area? (Y/N):" READ *, response IF (response == "N") EXIT After Execution : Enter the radius of the circle: 10 Area is Do you want to calculate another area? (Y/N): N 3.3 CYCLE Statement in DO Loop The general form is : DO statement sequence_1 IF ( a simple or compound condition ) CYCLE statement sequence_2 IF ( a simple or compound condition ) EXIT statement sequence_3 When the CYCLE statement is executed control goes back to the top of the loop. When the EXIT statement is executed control goes to the end of the loop and the loop is terminated. Example of the use of DO-CYCLE construct: DO READ *,x IF (x == 0) CYCLE IF(x<0) EXIT F = 1.0/x PRINT *, x, F i = 0 DO i = i + 1 IF (i>=50.and. i<= 59) CYCLE IF (i > 100) EXIT PRINT *, i 18

4 Ex: Write a program to find the mean (excluding zeros) of a list of real values. PROGRAM Mean! !The mean of all non-zero entries is calculated.! INTEGER :: Count REAL :: V, Sum Sum = 0 Count = 0 PRINT *, "Input the values." DO READ *, V IF ( V==0 ) CYCLE IF ( V < 0 ) EXIT Sum = Sum + V Count = Count + 1 PRINT *, "The sum is ", Sum PRINT *, "The mean is ", Sum / REAL(Count) END PROGRAM Mean Ex: Write a program to find the factorial of an integer. PROGRAM Factorial! ! Program to compute the factorial of an integer.! INTEGER :: N, F PRINT *, "Input an integer N" READ *, N F = 1 DO IF (N==0) EXIT F = F*N N=N-1 PRINT *," Factorial = ", F END PROGRAM Factorial 19

5 3.4 DO-WHILE Construct It has the following general form: DO WHILE( a simple or compound condition )... statement sequence... Here statement sequence is executed repeatedly as long as the condition is true. Example of the use of a DO-WHILE construct: N=10 DO WHILE(N>=2) PRINT *,N,N**2 N=N-2 Gives: Ex: Write a program to find the average of 20 numbers (use DO WHILE). PROGRAM SUM_OF_20REALS INTEGER :: I=1 REAL :: x, sum=0.0,av DO WHILE(I<=20) READ *,x sum = sum + x I=I+1 AV=sum/REAL(20) PRINT *,"Average=",AV END PROGRAM SUM_OF_20REALS 21

6 3.5 Named and Nested DO Loops Nested loops (one loop is inside the other) may be given names (labels) and they have the following form: outer loop outer: DO i = 1,10 inner: DO j = 1,10 Inner statements loop. inner outer Ex : Write a program finds the value of Z form the following formula: PROGRAM NESTED INTEGER :: i, j, Z=0 outer: DO i=0,5 inner: DO j=0,4 Z=Z+(i*j) inner outer PRINT *, "Z=",Z END PROGRAM NESTED Ex: Write a program to find the sum of the following series : PROGRAM ExpX INTEGER :: i,j,n,fact REAL :: x, sum PRINT *, "Input a number." READ *, x, n sum = 1 outer: DO i = 1, n fact=1 21

7 inner: DO j=1,i fact=fact*j inner sum=sum +(x**i)/real(fact) outer PRINT *, "sum= ", sum END PROGRAM ExpX Ex: Write a program to find the sum of the following series. PROGRAM SERIES_SUM INTEGER :: i, j=2, r=1, n, f REAL :: x, sum=0 READ *, x, n Outer: DO WHILE (j<=n) i=1 f=1 inner: DO WHILE (i<=j) f=f*i i=i+1 inner sum=sum +(f/x**j)*r j=j+2; r= -1*r outer PRINT *,"sum=", sum END PROGRAM SERIES_SUM H.W. Write a program to find the sum of the odd numbers from H.W. Write a program to find the sum of the following series (10 terms). 22

8 4. Formatted Output in FORTRAN 90 This section gives you the basics rules of formatting output in your FORTRAN programs. The PRINT statement is used to send output to the standard output unit ( usually your monitor, or sometimes your printer ) of your computer system. The general forms of PRINT statement are : PRINT *, output-list (free-format PRINT statement) PRINT '(format)', output-list (formatted PRINT statement) In the formatted form, the " * " is replaced by a certain format. For examples : PRINT '(F5.3)', PRINT '(I4)', INTEGER Output: The I Descriptor The general form of these descriptors are as follows: riw and riw.m I : is for INTEGER w : is the width of field, which indicates that an integer should be printed with w positions. m : indicates that at least m positions (of the w positions) must contain digits. If the number to be printed has fewer than m digits, 0's are filled. r : is the repetition indicator, which gives the number of times the edit descriptor should be repeated. For example, 3I5.3 is equivalent to I5.3, I5.3, I5.3. The sign of a number also needs one position. Thus, if -234 is printed, w must be larger than or equal to 4. The sign of a positive number is not printed. Examples Look at the following example. INTEGER :: a=123, b=-123, c= PRINT '(I5)', a PRINT '(I5.2)', a PRINT '(I5.4)', a PRINT '(I5.5)', a PRINT '(I5)', b PRINT '(I5.2)', b PRINT '(I5.4)', b PRINT '(I5.5)', b * * * * * PRINT '(I5.2)', c * * * * * Consider the following example : 23

9 INTEGER :: a = 3, b = -5, c = 128 PRINT '(3I4.2)', a, b, c The edit descriptor is 3I4.2 and the format is equivalent to (I4.2,I4.2,I4.2) because the repetition indicator is 3. The result is shown below: REAL Output: The F Descriptor The Fw.d descriptor is for REAL output. The general form is: rfw.d F is for REAL w is the width of field, which indicates that a real number should be printed with w positions. d indicates the number of digits after the decimal point. r is the repetition indicator, which gives the number of times the edit descriptor should be repeated. For example, 3F5.3 is equivalent to F5.3, F5.3, F5.3. Examples Look at the following example. REAL :: a= , b= PRINT '(F10.0)', a PRINT '(F10.1)', a PRINT '(F10.2)', a PRINT '(F10.3)', a PRINT '(F10.4)', a PRINT '(F10.5)', a PRINT '(F10.6)', a PRINT '(F10.7)', a * * * * * * * * * * PRINT '(F10.4)', b PRINT '(F10.5)', b PRINT '(F10.6)', b * * * * * * * * * * Consider the following example. REAL :: a = 12.34, b = , c = PRINT '(3F6.2)', a, b, c

10 4.3 REAL Output: The E Descriptor The rew.d descriptor is for REAL output. The printed numbers will be in an exponential form. The general form is: rew.d E is for REAL numbers in exponential forms. w is the width of field, which indicates that a real number should be printed with w positions. To print a number in an exponential form, it is first converted to a normalized form sxxx...xxx 10sxx, where s is the sign of the number and the exponent and x is a digit. For example, , , and are converted to , , and The Ew.d descriptor generates real numbers in the following form: r is the repetition indicator, which gives the number of times the edit descriptor should be repeated. For example, 3E20.7E2 is equivalent to E20.7E2, E20.7E2, E20.7E2. Examples In the following table, the PRINT statements use different E edit descriptors to print the value of The PRINT statements are shown in the left and their corresponding output, all using 12 positions, are shown in the right. REAL :: PI= PRINT '(E12.5)',PI E PRINT '(E12.4)',PI E PRINT '(E12.3)',PI E LOGICAL Output: The L Descriptor The rlw descriptor is for LOGICAL output. Fortran uses T and F to indicate logical values true and false, respectively. The general form of this descriptor is : rlw L is for LOGICAL w is the width of field, which indicates that a logical value should be printed with w positions. The output of a LOGICAL value is either T for.true. or F for.false. The single character value is shown in the right-most position 25

11 and the remaining w-1 positions are filled with spaces. The is shown in the figure below. r is the repetition indicator. Examples Let us look at the following example. There are two LOGICAL variables a and b with values.true. and.false., respectively. In the following table, the WRITE statements are shown in the left and their corresponding output are shown in the right. LOGICAL :: a=.true., b=.false. PRINT '(L1,L2)', a, b T F PRINT '(L3,L4)', a, b T F 4.5 CHARACTER Output: The A Descriptor The ra and raw descriptors are for CHARACTER output. The general form of these descriptors are as follows: ra and raw A is for CHARACTER w is the width of field, which indicates that a character string should be printed with w positions. The output of the character string depends on two factors, namely the length of the character string and the value of w. Here are the rules: If w is larger than the length of the character string, all characters of the string can be printed and spaces will be added. PRINT '(A6)',"12345" The five characters are printed and right-justified. The result is shown below: If w is less than the length of the character string, then the string is truncated and only the left-most positions are printed. PRINT '(A6)', " " Only the first six characters are printed. The result is shown below:

12 Let us look at the following example. CHARACTER(LEN=5) :: a = "12345" CHARACTER :: b = "*" PRINT '(A1, A)', a, b 1 * PRINT '(A2, A)', a, b 1 2 * PRINT '(A3, A)', a, b * PRINT '(A4, A)', a, b * PRINT '(A5, A)', a, b * PRINT '(A6, A)', a, b * PRINT '(A7, A)', a, b * PRINT '(A, A)', a, b * 27

13 5. Procedures (Sub-programs) Procedures are used to fragment large programs into smaller units, each unit can perform a certain task. Procedures help us to understand the large programs. Procedures are of two types: 1. User-defined Functions 2. Subroutines 5.1 User-defined Functions In addition to intrinsic functions, Fortran allows you to design your own functions. A function accepts some inputs from the main program. Every function has a name and independent values of inputs. The inputs are called parameters or arguments. A function may have one or more inputs but returns only one output to the main program. Inputs Function Output (return value) type FUNCTION function-name (arg1, arg2,..., argn)... name = an expression... END FUNCTION name where : type is the type of the function (or type of the return value). name is the Function name arg1, arg2,..., argn (arguments) are inputs to the function. For example a function that returns the sum of two integers can be defined as follows: INTEGER FUNCTION Add(A,B) INTEGER :: A,B Add = A+B END FUNCTION Add The function is called )تستدعى) by its name either through a variable or an expression. 28

14 Fortran 90 provides two basic types of functions : Internal Functions are placed between a CONTAINS statement and the END PROGRAM statement. PROGRAM Summation INTEGER :: I,J,sum READ *,I,J sum = Add(I,J) PRINT *,"The sum is ",sum CONTAINS INTEGER FUNCTION Add(A,B) INTEGER, INTENT(IN) :: A,B Add = A+B END FUNCTION Add END PROGRAM Summation External Functions are placed after the main program (i.e. after the END PROGRAM statement). PROGRAM Summation INTEGER :: I,J, sum, Add READ *,I,J sum = Add(I,J) PRINT *,"The sum is ", sum END PROGRAM Summation INTEGER FUNCTION Add(A,B) INTEGER, INTENT(IN) :: A,B Add = A+B END FUNCTION Add The meaning of INTENT(IN) indicates that the function will only take the value from the formal argument and must not change its content. In this example we will consider the conversion of angles in degrees to radians. The formula for conversion is defined by: PROGRAM Degrees2Radians REAL :: Degrees! input REAL :: Radians! output PRINT *, "Input the angle in degrees" READ *, Degrees Radians = Rad(Degrees) PRINT *,Degrees, "degrees= ", Radians, "Radians." CONTAINS REAL FUNCTION Rad(A) REAL, INTENT(IN):: A REAL, PARAMETER :: Pi = Rad = A * Pi/180. END FUNCTION Rad END PROGRAM Degrees2Radians 29

15 Ex: Write a function finds the sum of two numbers, the main program calls the function to find the sum of four numbers. PROGRAM Summation REAL :: a, b, c, d, s1, s2, s READ *, a, b, c, d s1=sum(a, b) s2=sum(c, d) s=sum(s1,s2) PRINT *, "summation= ", s CONTAINS REAL FUNCTION sum(x, y) REAL, INTENT(IN) :: x, y sum=x + y END FUNCTION sum END PROGRAM summation Ex: Write a function that finds the factorial of an integer, the main program calls the function to compute the combinations from the following formula. PROGRAM Combinations INTEGER :: n, m,f1, f2, f3,fact REAL :: C PRINT *, "Enter the values of n and m :" READ *, n, m f1=fact(n) f2=fact(n-m) f3=fact(m) C=f1/(f2*f3) PRINT *, "Combinations = ", C END PROGRAM Combinations INTEGER FUNCTION fact(k) INTEGER, INTENT(IN) :: k INTEGER:: i, f=1 DO i=2, k f=f*i fact=f END FUNCTION fact 31

16 5.2 Subroutines Subroutines are similar to functions. Subroutines can be defined internally (following a CONTAINS statement) or externally (after the END PROGRAM statement). The major differences between functions and subroutines are as follows: Functions take input and return a single number, character string, logical result, or array to the program that referenced it. Subroutines can return a large amount of output or no data (i.e. they can just perform a task such as printing results or displaying output) to the referencing program. The name of a function is set to the returning value. A subroutine name does not contain a value. Output from a subroutine is returned via the arguments contained in the output list. (i.e. if you want to return three values you must have one argument in the argument list for each output value). Functions are referenced in the main program structure by using their names in an expression. Subroutines are referenced using a CALL statement. Inputs Subroutine Outputs (return values) The basic format of a subroutine description is as follows: SUBROUTINE name (argument-list) [specification part] [execution part] END SUBROUTINE The argument-list is a list of identifiers (variables) for the input and output to the subroutine. Subroutines are referenced (called) in main programs using a CALL statement. CALL name (actual argument-list) The actual argument-list contains the variables, constants, or expressions that are to be used by the subroutine. 31

17 For example, a subroutine that returns area and circumference of a rectangle with sides x and y can defined as follows: Internal Subroutine PROGRAM Rectangle REAL :: X,Y,A,C PRINT *,"Input the sides:" READ *,X,Y CALL Rect(X,Y, A,C) PRINT *,"Area is ", A PRINT *,"Circum. is ", C CONTAINS SUBROUTINE Rect(W,L,Area,Circ) REAL, INTENT(IN) :: W,L REAL, INTENT(OUT) :: Area,Circ Area = W*L Circ = 2*(W+L) END SUBROUTINE Rect END PROGRAM Rectangle External Subroutine PROGRAM Rectangle REAL :: X,Y,A,C PRINT *,"Input the sides:" READ *,X,Y CALL Rect(X,Y,A,C) PRINT *,"Area is ",A PRINT *,"Circum. is ",C END PROGRAM Rectangle SUBROUTINE Rect(W,L,Area,Circ) REAL, INTENT(IN) :: W,L REAL, INTENT(OUT) :: Area,Circ Area = W*L Circ = 2*(W+L) END SUBROUTINE Rect INTENT(IN) - means that the dummy argument is expected to have a value when the procedure is referenced, but that this value is not changed by the procedure. INTENT(OUT) - means that the dummy argument has no value when the procedure is referenced, but that it will give one before the procedure finishes. INTENT(INOUT) - means that the dummy argument has an initial value that will be updated by the procedure. Ex: Write a program to read three positive numbers and use a single internal subroutine to compute the arithmetic, geometric and harmonic means. PROGRAM Mean6 REAL :: x, y, z REAL :: ArithMean, GeoMean, HarmMean READ(*,*) x, y, z CALL Means(x, y, z, ArithMean, GeoMean, HarmMean) PRINT*, "Arithmetic Mean = ", ArithMean PRINT*, "Geometric Mean = ", GeoMean PRINT*, "Harmonic Mean = ", HarmMean 32

18 CONTAINS SUBROUTINE Means(a, b, c, Am, Gm, Hm) REAL, INTENT(IN) :: a, b, c REAL, INTENT(OUT) :: Am, Gm, Hm Am = (a + b + c)/3.0 Gm = (a * b * c)**(1.0/3.0) Hm = 3.0/(1.0/a + 1.0/b + 1.0/c) END SUBROUTINE Means END PROGRAM Mean6 Ex: Write a program uses Heron formula to compute the area of a triangle has side lengths a, b and c. where s = (a+b+c)/2 The following two conditions must be satisfied : (a > 0, b > 0 and c > 0) and ( a+b > c, a+c > b and b+c > a) PROGRAM HeronFormula REAL :: a, b, c, TriangleArea LOGICAL :: x PRINT *, " Enter sides of a triangle " READ *, a, b, c x= TriangleTest(a, b, c) IF (x) THEN TriangleArea = Area(a, b, c) PRINT *, "Triangle area is ", TriangleArea ELSE PRINT *, "Your inputs cannot form a triangle." END IF CONTAINS LOGICAL FUNCTION TriangleTest(a, b, c) REAL, INTENT(IN) :: a, b, c LOGICAL :: test1, test2 test1 = (a > 0).AND.(b > 0).AND.(c > 0) test2 = ((a+b)>c).and. ((a+c)>b).and. ((b+c)>a) TriangleTest = test1.and. test2 END FUNCTION TriangleTest REAL FUNCTION Area(a, b, c) REAL, INTENT(IN) :: a, b, c REAL :: s s = (a + b + c) / 2.0 Area = SQRT(s*(s-a)*(s-b)*(s-c)) END FUNCTION Area END PROGRAM HeronFormula 33

19 Ex: Write a program to convert an octal number to decimal PROGRAM octal2decimal INTEGER :: oct, decimal READ*, oct decimal=octal(oct) PRINT *, "The decimal of ",oct,"is ",decimal CONTAINS INTEGER function octal (z) INTEGER, INTENT(INOUT) :: z INTEGER :: R,m=0,sum=0 DO WHILE (z/=0) R=mod(z,10) sum=sum+(8**m)*r z=z/10 m=m+1 octal=sum END FUNCTION octal END PROGRAM octal2decimal 34

20 6. Arrays and Matrices An array is a group of variables or constants, all of the same type (integer, real,.) which is referred to by a single name. Array elements are stored in an adjacent memory locations. Arrays are of two types: 1. One dimensional array. 2. Multi-dimensional array (matrices). 6.1 One Dimensional Array The masses of a set of 5 objects can be represented by the array variable : Mass(5)! an array of 5 elements of type real Index Mass Element The position of an element in array is called array index or subscript. Mass(1) = Mass(2) = Mass(3) = Mass(4) = Mass(5) = The declaration of one dimensional array is done as illustrated below. OR type, DIMENSION (number of elements in the array) :: name type :: name(number of elements in the array) for example: OR OR OR INTEGER, DIMENSION(10) :: A INTEGER :: A(10) REAL, DIMENSION(20) :: B REAL :: B(20) 35! Array A has 10 integers.! Array B has 20 real elements. CHARACTER, DIMENSION(15) :: C! Array C has 15 characters. CHARACTER :: C(15) LOGICAL, DIMENSION(5) :: D! Array D has 5 logical elements.

21 The index does not have to begin at 1, it can be zero or even negative; this is achieved with the ":" symbol: REAL :: A(0:8), B(-4:4), C(-8:0) All the above arrays have 9 elements. The index of A runs from 0 to 8, the index of B runs from -4 to 4 (including zero), and the index of C runs from -8 to 0. A One Dimensional Array can be initialized as follows: A = (/ 4, -2, 6, 0, 1, 9, 1, -1, 6, 8 /) A(1:4) = 0! the first four elements are 0. A(5:10) = 1! the last six elements are 1. assigns to array A the values: A = (/(I*0.1, I=1,10)/)! using implied loop assigns to array A the values: Array Input/Output Consider an array A declared as: REAL :: A(10) The input and of the array can be done as follows : As a whole array : READ *, A Using DO loop DO I=1, 10 READ *, A(I) Using an implied DO loops: READ *,(A(I),I=1,10) There are various methods for the output of arrays; consider the array: REAL :: A(9) = (/(I*0.1, I = 1, 9)/) The free-format output of the whole array PRINT *, A OR PRINT *, (A(I), I = 1, 9) gives : A formatted output, for example: PRINT '(9(F3.1,1X))', A 36

22 gives : If the multiplier is omitted then the output will be given line by line; i.e. PRINT '(F3.1,1X)', A This is equivalent to the DO loop: DO I = 1, 9 PRINT '(F3.1,1X)', A(I) gives: Array sections can also be referenced, for example: PRINT '(7(F3.1,1X))', A(3:8) PRINT '(5(F3.1,1X))', A(1:9:2) gives: Set an array element to its index or subscript. INTEGER, PARAMETER :: BOUND = 20 INTEGER, DIMENSION(1:BOUND) :: Array INTEGER :: i DO i = 1, BOUND Array(i) = i 37

23 6.3 Two/Multi-dimensional arrays Although it is useful to have data in one-dimensional arrays, it is sometimes useful to arrange data into rows and columns (two dimensional arrays), rows, columns, and ranks (three-dimensional), or even higher dimensionality. In this section we will consider multidimensional arrays. Two dimensional arrays are the most common and the subscripts are just as indicated in most math textbooks. The first subscript represents row number, and the second column number. Consider the matrix A(n,m) : A(1,1) A(1,2)... A(1,m) A(2,1) A(2,2)... A(2,m)... A(n,1) A(n,2)... A(n,m) Multi-dimensional arrays are declared in much the same way as single arrays. In general, for n-dimensional arrays: type :: array_name (num. of rows, num. of columns, num. of ranks,.) A two-dimensional array can be declared as follows: type :: array_name (num. of rows, num. of columns) For example: INTEGER, DIMENSION(3,4) :: B,C! B and C are 3x4 REAL, DIMENSION(0:4,3:12,5) :: A!A is a 5x10x 5 REAL :: A(4,10,5) INTEGER :: B(1:3, 1:5) LOGICAL :: D(-1:4, 0:5) 6.4 Input/Output of Two-Dimensional Array Two-dimensional arrays can be read using: the array name without subscripts, explicit DO loops, and implied DO loops. The array name without subscripts: All the values in A are read in column order A(1,1), A(2,1),.., A(n,1), A(1,2), A(2,2), etc. READ *, A 83

24 Explicit DO loops : nested DO loops are required as follows: For "row-wise" input: the elements of the first row is read, then the second row, then third, etc. until completed. DO i = 1, n DO j = 1, m READ *, A(i, j) For "Column-wise" input : In this case, the elements of the first column is read, then the second column, then third, etc. DO j = 1, m DO i = 1, n READ *, A(i, j) Implied DO loops : For "row-wise" input: READ *, ((A(i,j), j = 1, m), i = 1, n) For "Column-wise" input READ *, ((A(i,j), i = 1, n), j = 1, m) To print the matrix A(m,n), this can be done using a combination of DO loops and implied DO loops as follows: DO I = 1,m The output is : PRINT *, (A(I,J), J=1,n) A(1,1) A(1,2) A(1,3) A(1,n) A(2,1) A(2,2) A(2,3) A(2,n).. A(m,1) A(m,2) A(m,3) A(m,n) For example: to print the matrix 83

25 DO i = 1, 3 PRINT '(1x,4I5)',(A(i,j),j=1,4) The output is : DO i = 1, 3 PRINT '(1x,4I2)',(A(i,j),j=1,4) The output is : Sections of Arrays Accessing a section of an array requires the upper and lower bounds of the section to be specified together with a step (for each dimension). for example: REAL, DIMENSION(8) :: a INTEGER, DIMENSION(5,4) :: b REAL, DIMENSION(6) :: c INTEGER, DIMENSION(4,5) :: d a(3:5)!elements 3, 4, 5 a(1:5:2)!elements 1, 3, 5 b(1:2,2:3)!elements (1,2) (2,2) (1,3) and (2,3) b(3,1:4:2)!elements 1 and 3 of the third row b(2:4,1)!elements 2, 3 and 4 of the first column c(:)!whole array c(:3)!elements 0,1,2,3 c(::2)!elements 0,2 and 4 d(:,4)!all elements of the fourth column. d(::2,:)!all elements of every other row Ex: Write a program to find the average of the even and odd numbers in an array of 50 real numbers. 04

26 PROGRAM AV_ODD_EVEN INTEGER, DIMENSION(50) :: A INTEGER :: i, countodd=0, counteven=0 REAL :: sumodd=0.0, sumeven=0.0,avo, ave READ *, (A(i), i = 1, 50) DO i=1,50 IF (MOD(A(i),2)==0)THEN sumeven=sumeven+a(i) counteven=counteven+1 ELSE sumodd=sumodd+a(i) countodd=countodd+1 END IF ave=sumeven/counteven avo=sumodd/countodd PRINT *, "Number of even numbers = ",counteven PRINT *, "Sum of even numbers = ",sumeven PRINT *, "Average of even numbers = ",ave PRINT *, "Number of odd numbers = ",countodd PRINT *, "Sum of odd numbers = ",sumodd PRINT *, "Average of odd numbers = ",avo END PROGRAM AV_ODD_EVEN Ex: Write a program reads a set of real values and uses the following formulas to compute the mean, variance and standard deviation (use subroutine). PROGRAM Mean_Variance_StdDev INTEGER :: n, i READ *, n REAL, DIMENSION(n) :: data! input array REAL :: Mean, Variance, StdDev! results PRINT *, "Input data:" READ *, (data(i), i = 1, n) CALL M_V_SD (data, n, Mean, Variance, StdDev) PRINT *, "Mean : ", Mean PRINT *, "Variance : ", Variance PRINT *, "Standard Deviation : ", StdDev CONTAINS SUBROUTINE M_V_SD(d, n, M, V, SD) INTEGER, INTENT(IN):: n REAL, DIMENSION(1:n),INTENT(IN) :: d REAL, INTENT(OUT):: M, V, SD REAL :: sum1=0.0, sum2=0.0! compute Mean 04

27 DO i = 1, n sum1 = sum1+d(i) M = sum1/n! compute variance DO i = 1, n sum2=sum2+(d(i)-m)**2 V= sum2/(n-1)! compute standard deviation SD = SQRT(V) END SUBROUTINE M_V_SD END PROGRAM Mean_Variance_StdDev Ex: Write a program that reverses the order of the elements of a given array. PROGRAM Reverse INTEGER, PARAMETER :: SIZE = 30 INTEGER, DIMENSION(1:SIZE) :: a INTEGER :: n,m, Temp, i READ *, n PRINT *, "Input an array:" READ *, (a(i), i = 1, n) m=n DO i=1, n/2 Temp = a(i) a(i) = a(m) a(m) = Temp m=m-1 PRINT *, "The Reversed array:" PRINT *, (a(i), i = 1, n) END PROGRAM Reverse Ex: Write a program reads an array of 100 elements and finds the maximum elements. PROGRAM maximum REAL :: a(100) INTEGER :: i, Max PRINT *, "Input an array:" READ *, (a(i), i = 1, 100) Max=a(1) DO i=2,100 IF (a(i)>max) THEN Max=a(i) END IF PRINT *, "maximum=",max END PROGRAM maximum Ex: Write a program to sort an array of 10 integers in an ascending order. 04

28 PROGRAM SORT REAL :: a(10),temp INTEGER :: i, j PRINT *, "Input the array:" READ *, (a(i), i = 1, 10) outer: DO i=1,9 inner: DO j=i+1,10 IF (a(i)>a(j)) THEN temp=a(i) a(i)=a(j) a(j)=temp END IF inner outer PRINT *, (a(i), i = 1, 10) END PROGRAM SORT Ex: Write a program reads two matrices 10x10 and finds the sum and difference of them. PROGRAM SUM_DIFF REAL, DIMENSION(10,10) :: A, B, C, D INTEGER :: i,j READ *, ((A(i,j), j = 1, 10), i = 1, 10) READ *, ((B(i,j), j = 1, 10), i = 1, 10) Do i=1,10 DO j=1,10 C(i,j)=A(i,j)+B(i,j) D(i,j)=A(i,j)-B(i,j) DO i = 1,10 PRINT *, (C(i,j), j=1,10) DO i = 1,10 PRINT *, (D(i,j), j=1,10) END PROGRAM SUM_DIFF Ex: Write a program to find the product of two matrices A[3][3] and B[3][3]. PROGRAM PRODUCT REAL, DIMENSION(3,3) :: A, B, C, INTEGER :: i,j,k READ *, ((A(i,j), j = 1, 3), i = 1, 3) READ *, ((B(i,j), j = 1, 3), i = 1, 3) 08

29 C(3,3)=0 outer: Do i=1,3 middle: DO j=1:3 inner: DO k=1:3 C(i, j)= C(i, j)+a(i, k)+b(k, j) inner middle outer DO i = 1,3 PRINT *, (C(i, j), j=1,3) END PROGRAM PRODUCT Ex: Write a program reads a matrix A[4][4] of real numbers, and then generates an array of four elements, the first element is the sum of the diagonal elements of the matrix, the second is the sum of the upper triangular elements, the third is the sum of the lower triangular elements, and the forth is the sum of the secondary diagonal elements. PROGRAM ARRAY_GENERATION REAL, DIMENSION(4,4) :: A REAL :: B(1:4)=0 INTEGER :: i,j READ *, ((A(i,j), j = 1, 4), i = 1, 4) DO i=1,4 DO j=1,4 IF(i=j) THEN B(1)=B(1)+A(i,j) ELSEIF (i<j) THEN B(2)=B(2)+A(i,j) ELSE B(3)=B(3)+ A(i,j) B(4)=B(4)+ A(i,4+1-i) PRINT *, (B(i), i=1,4) END PROGRAM ARRAY_GENERATION H.W Write a program reads three arrays of real numbers, and generate an array of three elements each element represents the maximum element of each array. The program calls an external function receives an array and returns the maximum element. 00

SUBROUTINE subroutine-name (arg1, arg2,..., argn)

SUBROUTINE subroutine-name (arg1, arg2,..., argn) FORTRAN Subroutines Syntax Form 1 SUBROUTINE subroutine-name (arg1, arg2,..., argn) [specification part] [execution part] [subprogram part] subroutine-name Form 2 SUBROUTINE subroutine-name () [specification

More information

Edit Descriptors. Decimal form. Fw.d Exponential form Ew.d Ew.dEe Scientific form ESw.d ESw.dEe Engineering form ENw.d ENw.dEe.

Edit Descriptors. Decimal form. Fw.d Exponential form Ew.d Ew.dEe Scientific form ESw.d ESw.dEe Engineering form ENw.d ENw.dEe. Format Edit Descriptors The tedious part of using Fortran format is to master many format edit descriptors. Each edit descriptor tells the system how to handle certain type of values or activity. Each

More information

Algorithms 4. Odd or even Algorithm 5. Greatest among three numbers Algorithm 6. Simple Calculator Algorithm

Algorithms 4. Odd or even Algorithm 5. Greatest among three numbers Algorithm 6. Simple Calculator Algorithm s 4. Odd or even Step 3 : If number divisible by 2 then Print "Number is Even" Step 3.1 : else Print "Number is Odd" Step 4 : Stop 5. Greatest among three numbers Step 2 : Read values of a, b and c Step

More information

Lecture-6 Lubna Ahmed

Lecture-6 Lubna Ahmed Lecture-6 Lubna Ahmed 1 Input/output Input/output List directed input/output Formatted (or user formatted) input/output 2 List directed Input/output Statements List directed I/O are said to be in free

More information

Computers in Engineering COMP 208. Subprograms. Subroutines. Subroutines Michael A. Hawker

Computers in Engineering COMP 208. Subprograms. Subroutines. Subroutines Michael A. Hawker Computers in Engineering COMP 208 Subroutines Michael A. Hawker Subprograms Functions are one type of subprogram in FORTRAN Another type of subprogram FORTRAN allows is called a subroutine There are many

More information

NO CALCULATOR ALLOWED!!

NO CALCULATOR ALLOWED!! CPSC 203 500 EXAM TWO Fall 2005 NO CALCULATOR ALLOWED!! Full Name (Please Print): UIN: Score Possible Points Prog Points Part One 33 pts Part Two 30 pts Part Three 20 pts Part Four 25 pts Total 108 pts

More information

Computers in Engineering. Subroutines Michael A. Hawker

Computers in Engineering. Subroutines Michael A. Hawker Computers in Engineering COMP 208 Subroutines Michael A. Hawker Subprograms Functions are one type of subprogram in FORTRAN Another type of subprogram FORTRAN allows is called a subroutine There are many

More information

Matrix Multiplication

Matrix Multiplication Matrix Multiplication CPS343 Parallel and High Performance Computing Spring 2013 CPS343 (Parallel and HPC) Matrix Multiplication Spring 2013 1 / 32 Outline 1 Matrix operations Importance Dense and sparse

More information

Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013

Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013 Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013 One Dimensional Q1: Write a program that declares two arrays of integers and fills them from the user. Then exchanges their values and display the

More information

Matrix Multiplication

Matrix Multiplication Matrix Multiplication CPS343 Parallel and High Performance Computing Spring 2018 CPS343 (Parallel and HPC) Matrix Multiplication Spring 2018 1 / 32 Outline 1 Matrix operations Importance Dense and sparse

More information

type FUNCTION function-name (arg1, arg2,..., argn)

type FUNCTION function-name (arg1, arg2,..., argn) FORTRAN Functions Syntax Form 1 type FUNCTION function-name (arg1, arg2,..., argn) [specification part] [execution part] [subprogram part] function-name Form 2 type FUNCTION function-name () [specification

More information

Module 16: Data Flow Analysis in Presence of Procedure Calls Lecture 32: Iteration. The Lecture Contains: Iteration Space.

Module 16: Data Flow Analysis in Presence of Procedure Calls Lecture 32: Iteration. The Lecture Contains: Iteration Space. The Lecture Contains: Iteration Space Iteration Vector Normalized Iteration Vector Dependence Distance Direction Vector Loop Carried Dependence Relations Dependence Level Iteration Vector - Triangular

More information

Practical Exercise 1 Question 1: The Hello World Program Write a Fortran 95 program to write out Hello World on the screen.

Practical Exercise 1 Question 1: The Hello World Program Write a Fortran 95 program to write out Hello World on the screen. Practical Exercise Question : The Hello World Program Write a Fortran 95 program to write out Hello World on the screen. Question : Some Division One Results A particular number can be expressed as the

More information

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. Amr Goneid, AUC 1 Arrays Prof. Amr Goneid, AUC 2 1-D Arrays Data Structures The Array Data Type How to Declare

More information

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose

More information

Parallelizing The Matrix Multiplication. 6/10/2013 LONI Parallel Programming Workshop

Parallelizing The Matrix Multiplication. 6/10/2013 LONI Parallel Programming Workshop Parallelizing The Matrix Multiplication 6/10/2013 LONI Parallel Programming Workshop 2013 1 Serial version 6/10/2013 LONI Parallel Programming Workshop 2013 2 X = A md x B dn = C mn d c i,j = a i,k b k,j

More information

SUBPROGRAMS AND MODULES

SUBPROGRAMS AND MODULES SUBPROGRAMS AND MODULES FORTRAN PROGRAMING Zerihun Alemayehu AAiT.CED Program structure Advantages of subprograms Program units can be written and tested independently A program unit that has a well defined

More information

Dept. of CSE, IIT KGP

Dept. of CSE, IIT KGP Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of

More information

Columns A[0] A[0][0] = 20 A[0][1] = 30

Columns A[0] A[0][0] = 20 A[0][1] = 30 UNIT Arrays and Strings Part A (mark questions). What is an array? (or) Define array. An array is a collection of same data type elements All elements are stored in continuous locations Array index always

More information

Classification s of Data Structures

Classification s of Data Structures Linear Data Structures using Sequential organization Classification s of Data Structures Types of Data Structures Arrays Declaration of arrays type arrayname [ arraysize ]; Ex-double balance[10]; Arrays

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using

More information

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

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

Review Functions Subroutines Flow Control Summary

Review Functions Subroutines Flow Control Summary OUTLINE 1 REVIEW 2 FUNCTIONS Why use functions How do they work 3 SUBROUTINES Why use subroutines? How do they work 4 FLOW CONTROL Logical Control Looping 5 SUMMARY OUTLINE 1 REVIEW 2 FUNCTIONS Why use

More information

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition) Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.

More information

Introduction to Arrays

Introduction to Arrays Introduction to Arrays One Dimensional Array. Two Dimensional Array. Inserting Elements in Array. Reading Elements from an Array. Searching in Array. Sorting of an Array. Merging of 2 Arrays. What is an

More information

Types of Data Structures

Types of Data Structures DATA STRUCTURES material prepared by: MUKESH BOHRA Follow me on FB : http://www.facebook.com/mukesh.sirji4u The logical or mathematical model of data is called a data structure. In other words, a data

More information

7. Procedures and Structured Programming

7. Procedures and Structured Programming 7. Procedures and Structured Programming ONE BIG PROGRAM external procedure: separated small and reusable program units to conduct individual subtasks smaller main program Each program unit can be debugged

More information

fifth Solutions to Exercises 85

fifth Solutions to Exercises 85 fifth Solutions to Exercises 85 5 REPETITION While writing a program, it may be necessary to execute a statement or a group of statements repeatedly. Repetition is supported in FORTRAN through two repetition

More information

Declaration and Initialization

Declaration and Initialization 6. Arrays Declaration and Initialization a1 = sqrt(a1) a2 = sqrt(a2) a100 = sqrt(a100) real :: a(100) do i = 1, 100 a(i) = sqrt(a(i)) Declaring arrays real, dimension(100) :: a real :: a(100) real :: a(1:100)!

More information

Lecture 5: Matrices. Dheeraj Kumar Singh 07CS1004 Teacher: Prof. Niloy Ganguly Department of Computer Science and Engineering IIT Kharagpur

Lecture 5: Matrices. Dheeraj Kumar Singh 07CS1004 Teacher: Prof. Niloy Ganguly Department of Computer Science and Engineering IIT Kharagpur Lecture 5: Matrices Dheeraj Kumar Singh 07CS1004 Teacher: Prof. Niloy Ganguly Department of Computer Science and Engineering IIT Kharagpur 29 th July, 2008 Types of Matrices Matrix Addition and Multiplication

More information

GraphBLAS Mathematics - Provisional Release 1.0 -

GraphBLAS Mathematics - Provisional Release 1.0 - GraphBLAS Mathematics - Provisional Release 1.0 - Jeremy Kepner Generated on April 26, 2017 Contents 1 Introduction: Graphs as Matrices........................... 1 1.1 Adjacency Matrix: Undirected Graphs,

More information

Structured programming

Structured programming Exercises 6 Version 1.0, 25 October, 2016 Table of Contents 1. Arrays []................................................................... 1 1.1. Declaring arrays.........................................................

More information

Subroutines, Functions and Modules

Subroutines, Functions and Modules Subroutines, Functions and Modules Subdividing the Problem Most problems are thousands of lines of code. Few people can grasp all of the details. Good design principle: Exhibit the overall structure in

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.

More information

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

More information

Programming & Data Structure Laboratory. Day 2, July 24, 2014

Programming & Data Structure Laboratory. Day 2, July 24, 2014 Programming & Data Structure Laboratory Day 2, July 24, 2014 Loops Pre and post test loops for while do-while switch-case Pre-test loop and post-test loop Condition checking True Loop Body False Loop Body

More information

C for Engineers and Scientists

C for Engineers and Scientists C for Engineers and Scientists An Interpretive Approach Harry H. Cheng University of California, Davis 0.8 0.6 j0(t) j1(t) j2(t) j3(t) 0.4 Bessel functions 0.2 0-0.2-0.4-0.6 1 2 3 4 5 6 7 8 9 10 t Copyright

More information

Visual basic tutorial problems, developed by Dr. Clement,

Visual basic tutorial problems, developed by Dr. Clement, EXCEL Visual Basic Tutorial Problems (Version January 20, 2009) Dr. Prabhakar Clement Arthur H. Feagin Distinguished Chair Professor Department of Civil Engineering, Auburn University Home page: http://www.eng.auburn.edu/users/clemept/

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

'C' Programming Language

'C' Programming Language F.Y. Diploma : Sem. II [DE/EJ/ET/EN/EX] 'C' Programming Language Time: 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1(a) Define pointer. Write syntax

More information

AN INTRODUCTION TO FORTRAN 90 LECTURE 2. Consider the following system of linear equations: a x + a x + a x = b

AN INTRODUCTION TO FORTRAN 90 LECTURE 2. Consider the following system of linear equations: a x + a x + a x = b AN INTRODUCTION TO FORTRAN 90 LECTURE 2 1. Fortran 90. Arrays, functions and subroutines. 2. Scientific plotting. Gnuplot 1 Each coefficient and variable is a scalar. Lengthy and cumbersome! Program Scalar

More information

INTRODUCTION TO FORTRAN PART II

INTRODUCTION TO FORTRAN PART II INTRODUCTION TO FORTRAN PART II Prasenjit Ghosh An example: The Fibonacci Sequence The Fibonacci sequence consists of an infinite set of integer nos. which satisfy the following recurrence relation x n

More information

Allocating Storage for 1-Dimensional Arrays

Allocating Storage for 1-Dimensional Arrays Allocating Storage for 1-Dimensional Arrays Recall that if we know beforehand what size we want an array to be, then we allocate storage in the declaration statement, e.g., real, dimension (100 ) :: temperatures

More information

Computer Programming: C++

Computer Programming: C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming: C++ Experiment #7 Arrays Part II Passing Array to a Function

More information

Lecture 10. Daily Puzzle

Lecture 10. Daily Puzzle Lecture 10 Daily Puzzle Imagine there is a ditch, 10 feet wide, which is far too wide to jump. Using only eight narrow planks, each no more than 9 feet long, construct a bridge across the ditch. Daily

More information

Array Processing { Part II. Multi-Dimensional Arrays. 1. What is a multi-dimensional array?

Array Processing { Part II. Multi-Dimensional Arrays. 1. What is a multi-dimensional array? Array Processing { Part II Multi-Dimensional Arrays 1. What is a multi-dimensional array? A multi-dimensional array is simply a table (2-dimensional) or a group of tables. The following is a 2-dimensional

More information

Program Structure and Format

Program Structure and Format Program Structure and Format PROGRAM program-name IMPLICIT NONE specification part execution part subprogram part END PROGRAM program-name Comments Comments should be used liberally to improve readability.

More information

Our Strategy for Learning Fortran 90

Our Strategy for Learning Fortran 90 Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data

More information

IV/IV B.Tech (Regular) DEGREE EXAMINATION. Design and Analysis of Algorithms (CS/IT 414) Scheme of Evaluation

IV/IV B.Tech (Regular) DEGREE EXAMINATION. Design and Analysis of Algorithms (CS/IT 414) Scheme of Evaluation IV/IV B.Tech (Regular) DEGREE EXAMINATION Design and Analysis of Algorithms (CS/IT 414) Scheme of Evaluation Maximum: 60 Marks 1. Write briefly about the following 1*12= 12 Marks a) Give the characteristics

More information

Control Constructs: Loops - while loops - iterative loops (counting loops)

Control Constructs: Loops - while loops - iterative loops (counting loops) 4. Loops Control Constructs: Loops - while loops - iterative loops (counting loops) While loop do... if (logical_expression) exit... do while (logical_expression)... statement block logical expression.false.

More information

Review More Arrays Modules Final Review

Review More Arrays Modules Final Review OUTLINE 1 REVIEW 2 MORE ARRAYS Using Arrays Why do we need dynamic arrays? Using Dynamic Arrays 3 MODULES Global Variables Interface Blocks Modular Programming 4 FINAL REVIEW THE STORY SO FAR... Create

More information

Math 7 Glossary Terms

Math 7 Glossary Terms Math 7 Glossary Terms Absolute Value Absolute value is the distance, or number of units, a number is from zero. Distance is always a positive value; therefore, absolute value is always a positive value.

More information

MODULE 2: Branching and Looping

MODULE 2: Branching and Looping MODULE 2: Branching and Looping I. Statements in C are of following types: 1. Simple statements: Statements that ends with semicolon 2. Compound statements: are also called as block. Statements written

More information

Numerical Modelling in Fortran: day 2. Paul Tackley, 2017

Numerical Modelling in Fortran: day 2. Paul Tackley, 2017 Numerical Modelling in Fortran: day 2 Paul Tackley, 2017 Goals for today Review main points in online materials you read for homework http://www.cs.mtu.edu/%7eshene/courses/cs201/notes/intro.html More

More information

VARIABLE, OPERATOR AND EXPRESSION [SET 1]

VARIABLE, OPERATOR AND EXPRESSION [SET 1] VARIABLE, OPERATOR AND EXPRESSION Question 1 Write a program to print HELLO WORLD on screen. Write a program to display the following output using a single cout statement. Subject Marks Mathematics 90

More information

Introduction to MATLAB for Engineers, Third Edition

Introduction to MATLAB for Engineers, Third Edition PowerPoint to accompany Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2010. The McGraw-Hill Companies, Inc. This work is

More information

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing

SECTION 5: STRUCTURED PROGRAMMING IN MATLAB. ENGR 112 Introduction to Engineering Computing SECTION 5: STRUCTURED PROGRAMMING IN MATLAB ENGR 112 Introduction to Engineering Computing 2 Conditional Statements if statements if else statements Logical and relational operators switch case statements

More information

FORMULAS to UNDERSTAND & MEMORIZE

FORMULAS to UNDERSTAND & MEMORIZE 1 of 6 FORMULAS to UNDERSTAND & MEMORIZE Now we come to the part where you need to just bear down and memorize. To make the process a bit simpler, I am providing all of the key info that they re going

More information

Data Structures and Algorithms(12)

Data Structures and Algorithms(12) Ming Zhang "Data s and Algorithms" Data s and Algorithms(12) Instructor: Ming Zhang Textbook Authors: Ming Zhang, Tengjiao Wang and Haiyan Zhao Higher Education Press, 2008.6 (the "Eleventh Five-Year"

More information

Fundamentals of Programming Session 13

Fundamentals of Programming Session 13 Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos. UNIT 2 ARRAYS Arrays Structure Page Nos. 2.0 Introduction 23 2.1 Objectives 24 2.2 Arrays and Pointers 24 2.3 Sparse Matrices 25 2.4 Polynomials 28 2.5 Representation of Arrays 30 2.5.1 Row Major Representation

More information

Subroutines and Functions

Subroutines and Functions Subroutines and Functions Procedures: Subroutines and Functions There are two types of procedures: SUBROUTINE: a parameterized named sequence of code which performs a specific task and can be invoked from

More information

PROGRAMMING IN C AND C++:

PROGRAMMING IN C AND C++: PROGRAMMING IN C AND C++: Week 1 1. Introductions 2. Using Dos commands, make a directory: C:\users\YearOfJoining\Sectionx\USERNAME\CS101 3. Getting started with Visual C++. 4. Write a program to print

More information

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

Chapter 3. Fortran Statements

Chapter 3. Fortran Statements Chapter 3 Fortran Statements This chapter describes each of the Fortran statements supported by the PGI Fortran compilers Each description includes a brief summary of the statement, a syntax description,

More information

9. Elementary Algebraic and Transcendental Scalar Functions

9. Elementary Algebraic and Transcendental Scalar Functions Scalar Functions Summary. Introduction 2. Constants 2a. Numeric Constants 2b. Character Constants 2c. Symbol Constants 2d. Nested Constants 3. Scalar Functions 4. Arithmetic Scalar Functions 5. Operators

More information

CMAT Language - Language Reference Manual COMS 4115

CMAT Language - Language Reference Manual COMS 4115 CMAT Language - Language Reference Manual COMS 4115 Language Guru: Michael Berkowitz (meb2235) Project Manager: Frank Cabada (fc2452) System Architect: Marissa Ojeda (mgo2111) Tester: Daniel Rojas (dhr2119)

More information

INDEX. Sl. No. Programs Page No. Procedure 2. 1 To check whether person is eligible for vote or not. 2 To find the given number is even or odd 6-8

INDEX. Sl. No. Programs Page No. Procedure 2. 1 To check whether person is eligible for vote or not. 2 To find the given number is even or odd 6-8 INDEX Sl. No. Programs Page No. Procedure 2 1 To check whether person is eligible for vote or not 3-5 2 To find the given number is even or odd 6-8 3 To find the given year is leap year or not 9-11 4 To

More information

Using Templates to Introduce Time Efficiency Analysis in an Algorithms Course

Using Templates to Introduce Time Efficiency Analysis in an Algorithms Course Using Templates to Introduce Time Efficiency Analysis in an Algorithms Course Irena Pevac Department of Computer Science Central Connecticut State University, New Britain, CT, USA Abstract: We propose

More information

Vector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has.

Vector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has. ASSIGNMENT 0 Introduction to Linear Algebra (Basics of vectors and matrices) Due 3:30 PM, Tuesday, October 10 th. Assignments should be submitted via e-mail to: matlabfun.ucsd@gmail.com You can also submit

More information

Hypercubes. (Chapter Nine)

Hypercubes. (Chapter Nine) Hypercubes (Chapter Nine) Mesh Shortcomings: Due to its simplicity and regular structure, the mesh is attractive, both theoretically and practically. A problem with the mesh is that movement of data is

More information

n Group of statements that are executed repeatedly while some condition remains true

n Group of statements that are executed repeatedly while some condition remains true Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

More information

A Quick Tutorial on MATLAB. Zeeshan Ali

A Quick Tutorial on MATLAB. Zeeshan Ali A Quick Tutorial on MATLAB Zeeshan Ali MATLAB MATLAB is a software package for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It's name

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

Intrinsic Numeric Operations

Intrinsic Numeric Operations Intrinsic Numeric Operations The following operators are valid for numeric expressions: ** exponentiation (e.g., 10**2) evaluated right to left: 2**3**4 is evaluated as 2**(3**4) * and / multiply and divide

More information

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

1 Short Answer (15 Points Each)

1 Short Answer (15 Points Each) Name: Write all of your responses on these exam pages. If you need extra space please use the backs of the pages. 1 Short Answer (15 Points Each) 1. Write the following Java declarations, (a) A double

More information

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array Arrays Array is a collection of similar data types sharing same name or Array is a collection of related data items. Array is a derived data type. Char, float, int etc are fundamental data types used in

More information

Mathematics. 2.1 Introduction: Graphs as Matrices Adjacency Matrix: Undirected Graphs, Directed Graphs, Weighted Graphs CHAPTER 2

Mathematics. 2.1 Introduction: Graphs as Matrices Adjacency Matrix: Undirected Graphs, Directed Graphs, Weighted Graphs CHAPTER 2 CHAPTER Mathematics 8 9 10 11 1 1 1 1 1 1 18 19 0 1.1 Introduction: Graphs as Matrices This chapter describes the mathematics in the GraphBLAS standard. The GraphBLAS define a narrow set of mathematical

More information

Chapter 6. A Brief Introduction to Fortran David A. Padua

Chapter 6. A Brief Introduction to Fortran David A. Padua Chapter 6. A Brief Introduction to Fortran 90 1998 David A. Padua 1 of 15 6.1 Data Types and Kinds Data types Intrisic data types (INTEGER, REAL,LOGICAL) derived data types ( structures or records in other

More information

Computers in Engineering COMP 208 Repetition and Storage Michael A. Hawker. Repetition. A Table of Values 9/20/2007

Computers in Engineering COMP 208 Repetition and Storage Michael A. Hawker. Repetition. A Table of Values 9/20/2007 Computers in Engineering COMP 208 Repetition and Storage Michael A. Hawker Repetition To fully take advantage of the speed of a computer, we must be able to instruct it to do a lot of work The program

More information

Lecture 2. Two-Dimensional Arrays

Lecture 2. Two-Dimensional Arrays Lecture 2 Two-Dimensional Arrays 1 Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 2 1. 2-D Array Basics An

More information

PITSCO Math Individualized Prescriptive Lessons (IPLs)

PITSCO Math Individualized Prescriptive Lessons (IPLs) Orientation Integers 10-10 Orientation I 20-10 Speaking Math Define common math vocabulary. Explore the four basic operations and their solutions. Form equations and expressions. 20-20 Place Value Define

More information

Basic and Intermediate Math Vocabulary Spring 2017 Semester

Basic and Intermediate Math Vocabulary Spring 2017 Semester Digit A symbol for a number (1-9) Whole Number A number without fractions or decimals. Place Value The value of a digit that depends on the position in the number. Even number A natural number that is

More information

The figures below are all prisms. The bases of these prisms are shaded, and the height (altitude) of each prism marked by a dashed line:

The figures below are all prisms. The bases of these prisms are shaded, and the height (altitude) of each prism marked by a dashed line: Prisms Most of the solids you ll see on the Math IIC test are prisms or variations on prisms. A prism is defined as a geometric solid with two congruent bases that lie in parallel planes. You can create

More information

7.1 It is well known that the formula for converting a temperature in Celsius to Fahrenheit is. o F = 9 5 o C (7.10)

7.1 It is well known that the formula for converting a temperature in Celsius to Fahrenheit is. o F = 9 5 o C (7.10) 190 Engineering Software Development in Java 7.15 Exercises The problems in this section cover the basics, including use of keyboard input, looping and branching constructs, simple arrays, and generation

More information

CS 2461: Computer Architecture 1

CS 2461: Computer Architecture 1 Next.. : Computer Architecture 1 Performance Optimization CODE OPTIMIZATION Code optimization for performance A quick look at some techniques that can improve the performance of your code Rewrite code

More information

Prime Time (Factors and Multiples)

Prime Time (Factors and Multiples) CONFIDENCE LEVEL: Prime Time Knowledge Map for 6 th Grade Math Prime Time (Factors and Multiples). A factor is a whole numbers that is multiplied by another whole number to get a product. (Ex: x 5 = ;

More information

Chapter 1 Introduction to MATLAB

Chapter 1 Introduction to MATLAB Chapter 1 Introduction to MATLAB 1.1 What is MATLAB? MATLAB = MATrix LABoratory, the language of technical computing, modeling and simulation, data analysis and processing, visualization and graphics,

More information

Phil 320 Chapter 1: Sets, Functions and Enumerability I. Sets Informally: a set is a collection of objects. The objects are called members or

Phil 320 Chapter 1: Sets, Functions and Enumerability I. Sets Informally: a set is a collection of objects. The objects are called members or Phil 320 Chapter 1: Sets, Functions and Enumerability I. Sets Informally: a set is a collection of objects. The objects are called members or elements of the set. a) Use capital letters to stand for sets

More information

SECTION A TRUE / FALSE QUESTIONS (10 MARKS) (INSTRUCTION: Please answer all 10 questions)

SECTION A TRUE / FALSE QUESTIONS (10 MARKS) (INSTRUCTION: Please answer all 10 questions) SECTION A TRUE / FALSE QUESTIONS ( MARKS) (INSTRUCTION: Please answer all questions) 1) In pre-test loop, the condition is tested first, before executing the body of the loop. ) The while loop can be used

More information

Chapter 3 Problem Solving and the Computer

Chapter 3 Problem Solving and the Computer Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an

More information

Math-2 Lesson 6-3: Area of: Triangles, rectangles, circles and Surface Area of Pyramids

Math-2 Lesson 6-3: Area of: Triangles, rectangles, circles and Surface Area of Pyramids Math- Lesson 6-3: rea of: Triangles, rectangles, circles and Surface rea of Pyramids SM: Lesson 6-3 (rea) For the following geometric shapes, how would you answer the question; how big is it? Describe

More information

Introduction to MATLAB 7 for Engineers

Introduction to MATLAB 7 for Engineers PowerPoint to accompany Introduction to MATLAB 7 for Engineers William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2005. The McGraw-Hill Companies, Inc. Permission required for

More information

BC An Arbitrary Precision Desk-Calculator Language. Lorinda Cherry Robert Morris Bell Laboratories Murray Hill, New Jersey ABSTRACT

BC An Arbitrary Precision Desk-Calculator Language. Lorinda Cherry Robert Morris Bell Laboratories Murray Hill, New Jersey ABSTRACT BC An Arbitrary Precision Desk-Calculator Language Lorinda Cherry Robert Morris Bell Laboratories Murray Hill, New Jersey 07974 ABSTRACT BC is a language and a compiler for doing arbitrary precision arithmetic

More information

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input Loops / Repetition Statements Repetition s allow us to execute a multiple times Often they are referred to as loops C has three kinds of repetition s: the while loop the for loop the do loop The programmer

More information

PROGRAMS. EXCELLENT ACADEMY OF ENGINEERING. Telephone: / NORMAL PROGRAM

PROGRAMS. EXCELLENT ACADEMY OF ENGINEERING. Telephone: / NORMAL PROGRAM PROGRAMS NORMAL PROGRAM 1. Wap to display months in words where month in number is input. 2. Wap to print Fibonacci series till n elements. 3. Wap to reverse 4 digit numbers. 4. Wap to accept a number

More information

Module 5.5: nag sym bnd lin sys Symmetric Banded Systems of Linear Equations. Contents

Module 5.5: nag sym bnd lin sys Symmetric Banded Systems of Linear Equations. Contents Module Contents Module 5.5: nag sym bnd lin sys Symmetric Banded Systems of nag sym bnd lin sys provides a procedure for solving real symmetric or complex Hermitian banded systems of linear equations with

More information

FORTRAN 90: Functions, Modules, and Subroutines. Meteorology 227 Fall 2017

FORTRAN 90: Functions, Modules, and Subroutines. Meteorology 227 Fall 2017 FORTRAN 90: Functions, Modules, and Subroutines Meteorology 227 Fall 2017 Purpose First step in modular program design Cannot always anticipate all of the steps that will be needed to solve a problem Easier

More information

Assignment: 1. (Unit-1 Flowchart and Algorithm)

Assignment: 1. (Unit-1 Flowchart and Algorithm) Assignment: 1 (Unit-1 Flowchart and Algorithm) 1. Explain: Flowchart with its symbols. 2. Explain: Types of flowchart with example. 3. Explain: Algorithm with example. 4. Draw a flowchart to find the area

More information