An Introduction to C and Parallel Programming with Applications. Derrick C. Cerwinsky Craig C. Douglas Mookwon Seo Xiaoban Wu University of Wyoming

Size: px
Start display at page:

Download "An Introduction to C and Parallel Programming with Applications. Derrick C. Cerwinsky Craig C. Douglas Mookwon Seo Xiaoban Wu University of Wyoming"

Transcription

1 An Introduction to C and Parallel Programming with Applications Derrick C. Cerwinsky Craig C. Douglas Mookwon Seo Xiaoban Wu University of Wyoming January 15, 2014

2 ii

3 Contents 1 Introduction First Steps in C Basic Data Types Simple Computations and Output Simple Screen Output Arithmetic Operations Logical Operations Operator Precedence Formatting Code Homework Flow Control The if and if-else Statements The for, while, and do-while statements The switch Statement Homework Arrays and Pointers Vectors How to Declare Vectors How to Assign to and Reference Vectors Strings Matrices How to Declare Matrices How to Assign to and Reference Matrices Arrays Pointers How To Declare Pointers How To Assign to Pointers Pointer Referencing Relations Between Pointers and Arrays Strings Homework iii

4 iv CONTENTS 4 Functions and Header Files Functions Basics of Functions Passing Parameters to a Function Passing an Array to a Function Function Recurision Header Files Homework Input and Output printf and scanf puts and gets fopen and fclose fprintf and fscanf fputs and fgets Homework Complex Data Structures Structs Type definitions Enumerated types Unions Homework Applications Quadrature End Point and Midpoint Rules Trapezoid Rule Simpson s Rule Ordinary Differential Equations Euler s Method Heun s Method Introduction to Parallel Communication Introduction Parlib History and middleware Building and using Parlib Parlib functions OpenMP

5 Chapter 1 Introduction This text is intended as a short introduction to the C programming language for both serial and parallel computers using MPI and OpenMP [7, 11, 12]. In this chapter, we provide simple parts of the C language that will let you write a first set of programs in C. In Chapter 2, flow control in C is described. In Chapter 3, vectors, matrices, general arrays, dynamic memory management, and pointers are described. In Chapter 4, functions and header files are described. In Chapter 7, some sample applications are defined so that you can see how C works for real problems. In Chapter 8, a message passing interface (MPI) for parallel computing on clusters of computers and a library to hide MPI (Parlib) are described [11, 2]. 1.1 First Steps in C The language C [7, 12] is considered a legacy language and is one of the primary languages used for scientific computing. C is a compiled language. There are many choices of compilers, including the Intel compiler, IBM compiler, the Microsoft Visual Studio, Portland Group compiler (PGI), and the compiler used throughout this test, the GNU compiler (gcc) [4]. While any of these compilers can be used to compile C code, it should be noted that different compilers may give different performance with some codes. To talk about the parts of a program, a simple Hello World code is given in Program 1. While this is a very simple code, it is useful for illustrating the basic parts of a program. Program 1 A simple Hello World code in C. #include <stdio.h> int main(int argc, char ** argv){ printf("hello World!\n"); return 0; The first part of any C code is the inclusion of the header files. Header files are the files that contain the basic information for most functions used in a C code. Included files start with command: 1

6 2 CHAPTER 1. INTRODUCTION Table 1.1: Standard integer types in C. The number of bits listed in this table is based on the minimum number of bits used for each integer type. The actual size of each type will depend on the compiler, the hardware, and the OS. short 2 bytes int 4 bytes long 4 bytes long long 8 bytes #include followed by the library name in braces. The include command can also be used for user created libraries used in modular codes. This will be explained in more detail in Chapter 4. The next part of the code is the function main. In C, main is always of type int, and should take two arguments. These arguments are for passing arguments to the program from the command line at runtime. The usage of these arguments will be discussed later. The function main is where the program begins executing. It should be thought of as a starting point. In this program, there is the single command printf, which is used to print text to the screen. Return is used to end the program. In this example, the function returned the number 0 to tell the computer that there were no errors. The code for hello world is saved in a text file, in this case called hello.c, and can be compiled with the GNU compiler using the command: gcc hello.c -o hello This will compile the program and save the executable as hello. The program can be run with:./hello When the program is run, it will print Hello World! and exit. This program is useful for testing that a compiler is working, but not for much else. To write useful code, data structures and variables must be introduced. 1.2 Basic Data Types This section will introduce variables and simple data types. A variable is a object that lets a program store data in a usable form. C requires every variable to be declared before it is used. The three most common variable types are the integer, floating point number, and the character. Other, more complex data types will be introduce in Chapter 6. The integer is the simplest type of number since it has no fractional part and does not require approximation. Integers can be declared as short, int, long, or long long. Table 1.1 lists the minimum number of bytes for each data type. The number of bits is important because it controls the size of the largest number that can be represented with a given data type. Floating point numbers are a finite approximation of the real numbers. A detailed description of how a floating point number is represented will follow later in this text. For now it is enough to know that it is a decimal representation of a number. Unlike integers, a floating point number is almost never exact. Because of this approximation, error is introduced into computations simple because floating point numbers

7 1.2. BASIC DATA TYPES 3 Table 1.2: Standard floating point types in C. The size of each of the data types listed in this table is computed from gcc (SUSE Linux) The actual values will differ by system. float 4 bytes double 8 bytes long double 16 bytes Table 1.3: Standard char in C. char 1 byte ASCII or EBCDIC char 2 bytes Unicode are used. However, this cannot be avoided. The most common type of floating point number is the double. It is sometimes useful to use a float, which is a lower precision representation, but in some applications can improve speed (such as GPU programming). Some compilers also support long double, which can give higher precision. Table 1.2 lists the types as well as the size of each on my computer. The last major data type is the character. A character is declared as a char and can store a single character. Characters are most commonly used in strings, which will be discussed in Chapter 3. Program 2 This is a simple code to print the number of bytes for each of the most common data types. #include <stdio.h> int main(int argc, char ** argv){ printf("char:\t\t%i\n", sizeof(char)); printf("short:\t\t%i\n", sizeof(short)); printf("int:\t\t%i\n", sizeof(int)); printf("long:\t\t%i\n", sizeof(long)); printf("long long:\t%i\n", sizeof(long long)); printf("float:\t\t%i\n", sizeof(float)); printf("double:\t\t%i\n", sizeof(double)); printf("long double:\t%i\n", sizeof(long double)); return 0; It has been stated that the size of each data type depends on the compiler used as well as the hardware. So how does one determine the actual size of each of the data types used? Program 2 demonstrates the use of the sizeof function. This function returns the size in bytes of the data type passed to it. In later sections this function will be very useful. Declaring a variable is simple. Simply state the type followed by the variable name. For example, to declare a variable x of type double, use the line double x;

8 4 CHAPTER 1. INTRODUCTION Table 1.4: A small collection of special characters in C. \n New line \t Tab \ Prints a single quote \" Prints a double quote Setting a value for x is done using the = operator. So setting x to the value of is done with the command x = ; 1.3 Simple Computations and Output The focus of this text is programming for computational mathematics. This section introduces basic arithmetic functions used in computing. Computations are only useful if there is a way to extract the information out of the computer. The simplest method is printing to the screen with the printf function Simple Screen Output The printf function allows output to the standard out, which in most cases is the screen. This is one of the most basic functions in C. Examples of this function can be seen in each of the sample programs presented so far. The first argument of printf is a string. In most cases this is simply text in quotes. For an example, look at Program 1. The one real line of code is: printf("hello World!\n"); The single argument is the string "Hello World!\n". Here, \n is a a special character that means a line return. This forces the next text printed to be on the next line below Hello World. A small collection of special characters can be found in Table 1.4. Printing variables in text is achieved with the %x operator, where x is replaces with a letter indicating the data type. For example, to print a double you would use %g. The variables should then be added as arguments to printf in the order they are used. A simple code to print text that includes a number would be as follows. double x = ; printf("the value of x is %g\n", x); A partial list of options used in printf can be found in Table Arithmetic Operations Assigning values to a variable is done with the equal sign. The value on the right of the equal sign is stored in the variable on the left. So to add two numbers, a and b, and store the sum in c, the command c = a + b;

9 1.4. FORMATTING CODE 5 Table 1.5: Common tokens for printing variables using printf. To include the value of a variable in a string use %x the string where x is one of the following values. Value for x type example d or i Integer 3175 f Floating point number lf Double floating point number e Scientific notation floating point e+3 le Scientific notation double floating point e+3 g Shortest form between f and e lg Shortest form between lf and le of type double would be used. A list of common operators can be found in Table 1.6. Care should be taken when adding numbers which are not of the same data type. C will add the numbers, but the result can sometimes take an unexpected result. This is most evident while dividing integers. For example, 9 / 3 will result in 3, and 10 / 3 will also be 3. However, 10.0 / 3.0 = Logical Operations Logical operators are used to evaluate logical statements. In their simplest form they can be used to compare two or more variables. Logical operators will return 1 if true and 0 if false. A short of common logical operators are given in Table 1.7. These operators will be use extensively in Chapter Operator Precedence Operator precedence is the order in which operations are executed. In C, the operator precedence is very complex and can lead to very interesting (but wrong) results. Table 1.8 gives a detailed list of the operators in C and the precedence of each. When first learning to program, it is a good idea to keep expression somewhat simple. In these cases, the rules follow standard mathematical practices, so most people will have little difficulty with ordering. But as always, if there is doubt as to which operation the computer will execute first, parenthesis should be added to remove ambiguity. 1.4 Formatting Code Formatting code refers to the actual layout of the code in the text file. The format of the code makes no difference in the actual execution of the code. However, a well formatted code is much easier to read and modify. Good formatting practices can slow the programmer down initially, but will greatly assist in debugging. Indentation is one of the easier methods for formatting code, and should be considered the minimum amount of formatting a programmer should use. Indenting is used to group code into readable blocks. Inside loops, if statements, and other conditional blocks of code, the text should be indented to mark of groups of code.

10 6 CHAPTER 1. INTRODUCTION Table 1.6: A short list of arithmetic operations. Operation Description + Addition - Subtraction * Multiplication / Division % Modulus ++ Increments the variable by 1 (exp: i++ is the same as i = i + 1) -- Decrements the variable by 1 += Add assignment (exp: a += b is a = a + b) -= Subtract assignment *= Multiply assignment /= Divide assignment << Left-shift >> Right-shift <<= Left-shift assignment >>= Right-shift assignment Table 1.7: Table of logical comparisons. This is a short list of the most common logical statements use in C. == Logical equal! Logical not!= Logical not equal <, <= Less than, less than or equal to >, >= Greater than, greater than or equal to Logical OR && Logical AND Binary OR & Binary AND ˆ Binary exclusive OR ˆ= Binary exclusive OR equals

11 1.4. FORMATTING CODE 7 Table 1.8: Operator Precedence. Operators with highest precedence are listed first. Operator Meaning. Member Selection (object) -> Member Selection (pointer) [] Array subscript () Function call member initialization ++ Postfix increment -- Postfix decrement sizeof Size of type or object ++ Prefix increment -- Prefix decrement! Logical not - Unary minus + Unary plus & Address-of * Indirection.* Pointer-to-member (objects) ->* pointer-to-member (pointer) * Multiplication / Division % Modulus + Addition - Subtraction << Left shift >> Right shift < Less than > Greater than <= Less than or equal to >= Greater than or equal to == Equality!= Inequality & Bitwise AND ˆ Bitwise exclusive OR Bitwise inclusive OR && Logical AND Logical OR e1?e2:e3 Conditional = Assignment *= Multiplication assignment /= Division assignment %= Modulus assignment += Addition assignment -= Subtraction assignment <<= Left-shift assignment >>= Right-shift assignment &= Bitwise AND assignment = Bitwise OR assignment ˆ= Bitwise exclusive OR assignment

12 8 CHAPTER 1. INTRODUCTION An even more important form of formatting is adding comments to code. Comments are non-compiled notes in the code that added by the programmer to give meaning to code. In C comments are put between /* and */. Anything between these marks will be ignored. These marks can be placed in the middle of a line, or even spanning multiple lines. This is useful for long comments or removing large blocks of code. Although not officially supported in C, there is another form of comment that is very useful. This type of comment is a line comment started by //. Anything after the double slash is considered a comment and is ignored. This type of comment is very useful, but is not supported by all C compilers. Examples of proper comments and indenting can be seen in the programming throughout this text. 1.5 Homework 1. What is the return value if the logical operation is correct? 2. Try to print out the j++, j=j+1 and ++j if you fix the j. What is the difference among these things? Explain it. 3. What is the difference between 10/3 and 10.0/3?

13 Chapter 2 Flow Control Flow control refers to logical statements that direct the order of execution in a program. Examples of flow control include if statements, loops, and switches. 2.1 The if and if-else Statements One of the most important commands in programming is the if statement. The if statement let parts of the code be executed only when particular conditions are met. The conditions are placed in the form of a logical statement that can be tested. For example, a variable can be tested to see if it holds a particular value or is a member of a range. A partial list of logical connectors can be found in Table 1.7. And example of the if statement can be found in Program 4. An if statement can have an else placed at the end of the conditional code block. In the case that the if statement returns false, the else block with execute. Otherwise the code is skipped. An if statement can have multiple conditions connected with either an and (&&) or an or ( ) statement. An and statement requires all conditions to be met. The or only requires one of the statements to be true. A word of warning is required when using the and. As soon as a false statement is found, the program will return a false and move on, without evaluating the remaining conditions. If your code requires the evaluations, errors will arise. A better practice is to evaluate the functions before the if statement. This way, every function will be evaluate and unexpected problems can be avoided. A special case of the if-else statement is called the conditional. The conditional has the form, expression1? expression2 : expression3 where expression1 is a logical condition (the if part), expression2 is executed if expression1 is true, and expression3 is executed if expression1 is false. While a conditional can be used in place of any if-else statement, it is best used only when the expressions are simple. Overuse of conditionals makes code unreadable and almost impossible to debug. Program 3 has a simple example of a conditional. 2.2 The for, while, and do-while statements Loops are an important part of programming. A loop lets a program repeat a section of code until certain conditions are met. The simplest loop is the while command. Like if statement, the while statement takes 9

14 10 CHAPTER 2. FLOW CONTROL Program 3 A simple example of a conditional. #include <stdio.h> // This is a simple program to show how // conditionals are used. // The program will compare two numbers // and print the larger of the two. int main(int argc, char ** argv) { int i = 1, j = 2; // Initialize the numbers to compare int solution; // Declare the solution // Conditional statement solution = (i > j? i : j); // Print the output printf("the largest number is %i\n", solution ); return 0; a single logical input. If the condition is met, the code in the while block is executed. If at the end of the code block the condition is still met, the code will execute again. This will continue until the condition is no longer met. Because of this, care should be taken with the while statement so that an infinite loop is not possible. Another useful command is break. When placed in a loop, break will force the program out of the loop. Program 4 demonstrates the usage of while, if, and break. A do-while loop is a special case of the while loop. In a while loop, the while is placed at the start of the loop, and the condition is checked first. With a do-while loop, the code block is started with the do and ended with the while. Unlike the while loop, the do-while loop is always executed at least once. The last of the loop types that common to use is the for loop. This loop type combines the initialization, stop condition, and step increment in a single command. The while loop in Program 4 could have been written with a for loop with the following command. for ( i = 2; i < n; i++ ) The first argument is the initialization. The second is the stopping criteria. The last argument is the increment size. Each of the arguments of the for loop can be a compound statement. This means that multiple variables can be initialized, or the stepping can be very complex. It is even possible to leave one or more of the arguments out. However, as with the if statement, care should be taken to assure that all the code that is required to run will actually run when it is expected by the program. For an example of a for loop, see Program The switch Statement The switch statement can be very useful in many applications. The switch statement is used to check the value of a variable and direct the program down one of many paths. Logically it can be thought of as a string of if-else statements, but it is actually more versatile than this. switch takes a single argument, and compares the value of the argument to a sequence of cases. When a match is found, the code will execute starting at the matching case. The cases are normally divided by a

15 2.3. THE SWITCH STATEMENT 11 Program 4 This code will find the smallest factor of an integer. This example is illustrate the use of if statements and while loops. #include <stdio.h> int main(int argc, char ** argv){ /* This is a simple code that will return the smallest factor of an integer n. If n is prime, the program will state that n is prime. */ int n; // This is the number to be factored. int i; // Loop variable. This is also to test // if i divides n. n = 59; // Set the value of n for testing. i = 2; // Initialize i while ( i < n ){ // This starts the loop. if ( n % i == 0 ){ printf("the smallest factor of %i is %i\n", n, i); break; // This will exit the while loop. i++; // Increments the value of i. if ( i == n ){ printf("the number %i is prime.\n", n); return 0;

16 12 CHAPTER 2. FLOW CONTROL break since the code will not stop at the next case. This functionality is what makes the switch so useful. Program 5 A simple program to check if the first n integers are divisible by 3. This program gives examples of the for loop and the tt switch statement. #include <stdio.h> int main(int argc, char ** argv){ int i, n, sum, check; // Declare varibals n = 100; // Initialize n sum = 0; // Initialize the sum to 0 for ( i = 1; i <= n; i++) sum += i; // Start for loop // Since the for loop is only a single statement it does // not need to be enclosed in { check = sum % 3; // Find sum mod 3. switch(check){ // Test for 0 mod 3 // This is run if sum mod 3 is 0 case 0: printf("the sum of the numbers between 1 and %i is divisible by 3\n", n); break; // This is run otherwise default: printf("the sum of the numbers between 1 and %i is not divisible by 3\n", n); return 0; A switch can also set a default action. This is used in place of the last case statement. If the switch did not find a matching case, it will run the default option. Note that a default case is not required. 2.4 Homework 1. Today is Jun 14th, 2013 and Friday. What is day of the week is June 14th, 1999? How about December 25th, 2013? Make a program that will compute the day of the week for any date. The input should be in the form Make a program to find all the prime numbers up to a fixed n. 3. Make a program that will factorize a number. Your program should print out all of the factors. For example if 100 is entered, the program should print out Find an approximate value of 3 up to 10 decimal places. 5. Suppose there are two numbers. Then, find a maximaum number and a minimum number. Also, make a program to switch these two numbers.

17 Chapter 3 Arrays and Pointers In this chapter, we demonstrate how to declare and vectors, matrices, arrays, and pointers. By definition, a matrix has n rows and m columns and is described in Section 3.2. A vector is a n 1 matrix and is described in Section 3.1. An array is a d-dimensional matrix, where d > 0, and is described in Section 3.3. Typically d is not a large number and rarely is d as large as 10, with 0 < d < 7 most common. 3.1 Vectors In this section, we describe how to declare a vector (Section 3.1.1), how to assign to and reference a vector (Section 3.1.2), and vectors of characters, called a string (Section 3.1.3) How to Declare Vectors We declare vectors as follows: int a[10]; // vector a with 10 elements double b[20]; // vector b with 20 elements char c[50]; // vector c with 50 elements (string of length 49) You can also declare a vector and initialize it at the same time for a fixed number of elements: // vector a now has 10 initialized elements int a[10]= {3,2,1,7,5,6,4,8,9,10; You can also declare a vector with an undetermined number of elements, but the compiler determines it from the initialization list: // vector a3 with the number of elements (3) to be determined int a3[]= {2,7,56; How to Assign to and Reference Vectors Given the declaration, int n = 100; int a[n]; 13

18 14 CHAPTER 3. ARRAYS AND POINTERS The first element is index 0. If the vector is declared to have n elements, then the n th element is index n 1, i.e., 99 in the example above. The following code fragment accesses the i th element of a and places it in ai: ai = a[i-1]; which is somewhat awkward notation. Consider Program 6: Program 6 Assign to and reference vectors. #include <stdio.h> int main(int argc, char ** argv) { int i; int a[5]; int b, c, sum; // declare an int i, which is a loop counter // declare an int vector a with 5 elements // declare three more ints for(i=0; i<5; i++) // for loop (5 iterations total) a[i]=i*2; // here, we assign a value to // each element of vector a for(i=0; i<5; i++) // for loop with a reference to all elements of a printf("a[%d]=%d\n", i, a[i]); b=a[2]; c=a[4]; // reference a[2], then use b to store the value // reference a[4], then use c to store the value // why there is no a[5]? sum=b+c; printf("the sum of a[2] and a[4] is %d \n", sum); return 0; We compile and link Program 6 using the commands $ gcc -o Program5 Program5.c Running Program 6 $./Program5 gives us the following: a[0]=0 a[1]=2 a[2]=4 a[3]=6 a[4]=8 The sum of a[2] and a[4] is 12

19 3.2. MATRICES Strings Strings are defined as arrays of characters. For examples, we can declare a string as: char a[] = "Hello"; // Use " " for strings, not for a character An alternative is to define the string using individual characters: char a[] = { H, e, l, l, o, \0 ; In the alternative version, notice the end of string character \0. All character strings end with this special character and if a string is declared with an assumed maximum length, the end of string character must be factored into the length (or very bad things happen that can be difficult to debug). In the first declaration the compiler automatically put an end of string in and reserves space for it. Consider Program 7: Running Program 7 gives us the following: Program 7 A string #include <stdio.h> int main(int argc, char** argv){ char mystring[] = "Hello, world!"; printf("%s \n", mystring); // Declaration and value // Print mystring return 0; Hello, world! 3.2 Matrices In this section, we describe how to declare a matrix (Section 3.2.1), and how to assign to and reference a matrix (Section 3.2.2) How to Declare Matrices A matrix in C is technically a column vector and each of its elements is a separate row vector. (C uses an edge vector method of storing matrices.) Hence, the first dimension of a matrix is the number of rows and the second dimension is the number of columns, which is the transpose of the technical definition. We declare matrices as follows: int a[3][4]; double b[7][2]; char c[2][5]; // int matrix a with 3 rows and 4 columns // double matrix b with 7 rows and 2 columns // char matrix c with 2 rows and 5 columns As in the vector definition, c can store only 4 characters per row.

20 16 CHAPTER 3. ARRAYS AND POINTERS How to Assign to and Reference Matrices Given the declaration: int a[3][4]; Like what is shown in Section 3.1.2, the index in c starts from 0, which means the index in the first bracket starts from 0 and the index in the second bracket starts from 0. Think about why there is no a[3][j] or a[i][4]? Consider Program 8, Running Program 8 gives us Table 3.1. Program 8 Multiplication table using the matrix. #include <stdio.h> int main(int argc, char ** argv){ int i, j; int a[9][9]; for(i=0; i<9; i++) for(j=0; j<9; j++) a[i][j]=(i+1)*(j+1); // loop counter // declare matirx a // to store the multiplication table // assign a value to each element for(i=0; i<9; i++) { for(j=0; j<9; j++) { printf("%2d ", a[i][j]); // reference each element printf("\n"); return 0; 3.3 Arrays Arrays in C act to store related data under a single variable name with an index, also known as a subscript. It is easiest to think of an array as simply a list or ordered grouping for variables of the same type. Cited from Wikibooks In fact, we have touched the arrays in Section and Section 3.2.1, the vectors are 1-D arrays, and the matrices are 2-D arrays. Similarly, we can declare N-D arrays as follows: datatype name[]...[]; int a[3][2][4]; double b[3][4][5][6];

21 3.4. POINTERS 17 Table 3.1: The result of Program Anyway, to declare what kind of arrays depends on your needs. 3.4 Pointers A pointer is a value that designates the address (i.e., the location in memory), of some value How To Declare Pointers Pointers are variables that hold a memory location. Pointers can reference any data type, even functions which will be talked about in the next chapter. We declare pointers as follows: int *pr; double *pr1; float *pr2; char *pr3; // int pointer variable named pr // double pointer variable named pr1 // float pointer variable named pr2 // char pointer variable named pr3 The first pr is the name of a pointer variable, and pr stores the address of a value in int in the memory. In order to be different from int pr, we put an asterisk before the name of the variable, so we know that it is a pointer variable. Similarly, pointer variables pr1, pr2, pr3 store the address of a value in datatype double, float, char respectively. In addition to the above, we can also put N asterisks before the name of the pointer variable, and these pointer variables corresponds to the N-D arrays. For example: int **pntr; // This pntr corresponds to a matrix We will talk about this when we learn the malloc in Section In summary, pointer is a variable which stores the address of a value in one datatype How To Assign to Pointers To assign a pointer the address of a variable, the & or address of operator is used. Consider Program 9: Running Program 9 gives us the following.

22 18 CHAPTER 3. ARRAYS AND POINTERS Program 9 How to assign to pointers. #include <stdio.h> int main(int argc, char ** argv){ int i; int *p; p=&i; // declare i as an int // declare p as an int pointer // use the & operator to get the address of i return 0; Pointer Referencing To access a value to which a pointer points, the * operator is used. Since we know that the pointer stores the address of a value in one datatype, so if we want to change the value or if we want to get the value, we should use * operator to reference the pointer. Consider Program 10: Running Program 10 gives us the following: Program 10 Reference the pointer. #include <stdio.h> int main(int argc, char ** argv){ int i=5; // declare i as an int, and initialize i int *p; // declare p as an int pointer p=&i; // use & operator to get the address of i, // and store it into int pointer p printf("the value the pointer p points to is %d \n", *p); // add * before the pointer p to reference the pointer p // so the *p means the value the pointer p points to *p=6; // change the value the pointer p points to printf("the new value the pointer p points to is %d \n", *p); // use the * operator to reference the pointer p return 0; The value the pointer p points to is 5 The new value the pointer p points to is 6

23 3.4. POINTERS Relations Between Pointers and Arrays For the 1-D arrays (vectors), the name of the array is a pointer which stores the address of first element in the array. For example, if we declare int a[10], then a==&a[0] is true. Besides, we can also do some arithmetic to the pointer, like a+1 is also a pointer, which stores the address of a[1]. Similarly, a+i is a pointer which stores the address of a[i]. Consider Program 11: Running Program 11 gives us the following. Program 11 Relations between arrays and pointers. #include <stdio.h> int main(int argc, char ** argv){ int i; int a[5]; // loop counter for(i=0; i<5; i++) if(a+i==&a[i]) // check what we said above printf("the address stored in a+%d is equal to the address of a[%d] \n", i, i); printf("\n"); return 0; The address stored in a+0 is equal to the address of a[0] The address stored in a+1 is equal to the address of a[1] The address stored in a+2 is equal to the address of a[2] The address stored in a+3 is equal to the address of a[3] The address stored in a+4 is equal to the address of a[4] Similarly, there are also some relations between 2-D arrays and pointers. For example, if we declare 2-D array int a[3][4], then the name of this array is a pointer which store the address of the pointer a[0]. And the pointer a[0] stores the address of a[0][0]. Similarly, a+i is a pointer which stores the address of pointer a[i], and the pointer a[i]+j stores the address of a[i][j]. Besides, recall that *(a+i) is equal to a[i], so the pointer *(a+i)+j stores the address of a[i][j]. Now, let s look a function called malloc: void* malloc (size t size); The malloc allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. Consider Program 12 to see how to use malloc to declare a matrix. And the scheme is shown in the Figure 3.1. Running 12 gives us Table Strings Like the 2-D array, we also have 2-D string. For example in the main function, you can find the char **argv, which is a 2-D string. So, argv[i] is a pointer which points to a string. And there are a lot of functions about strings, you can find them in the string.h.

24 20 CHAPTER 3. ARRAYS AND POINTERS Program 12 Use malloc to generate the multiplication table. #include <stdio.h> #include <stdlib.h> int main(int argc, char ** argv){ int **arr; int height=9; int width=9; int i, j; // number of rows // number of columns // loop counter arr = malloc( sizeof( int* ) * height ); // allocate a block of memory // which contains height int * elements. // this has the same effect with int *arr[height]; // which means arr is a pointer // which points to an array named arr and // the array arr contains height elements // and each element arr[i] is a int pointer // which points to each row which // will be allocated below for(i=0; i<height; i++) arr[i] = malloc( sizeof(int) * width ); // allocate a block of memory // which contains width int elements. // and these width elements form each row we mentioned above for(i=0; i<height; i++) for(j=0; j<width; j++) arr[i][j]=(i+1)*(j+1); // initialize each element in the array // *(*(arr+i)+j)=(i+1)*(j+1); works // *(arr[i]+j)=(i+1)*(j+1); works for(i=0; i<height; i++) { for(j=0; j<width; j++) { printf("%2d ",arr[i][j]); // printf("%2d ", *(*(arr+i)+j) ); works // printf("%2d ", *(arr[i]+j) ); works printf("\n"); return 0;

25 3.5. HOMEWORK 21 Figure 3.1: How to generate a matrix using malloc Consider Program 13: Running Program 13 gives us the following. If you run this program like this:./a Hello My Dear Friend Then the result is: There are 5 paramters of this program The 1th parameter of this program is./a The 2th parameter of this program is Hello The 3th parameter of this program is My The 4th parameter of this program is Dear The 5th parameter of this program is Friend The explanation of this program is that sometimes we need to pass some parameters to the main program, and we can do this by typing the parameters behind the main program on the command line. After you press the enter, these parameters are passed into the main function. The argc stores the number of parameters you have input, at the same time the argv stores these parameters in 2-D strings. So the first parameter is stored at the address in the pointer argv[0], and the last parameter is stored at the address in the pointer argv[argc-1]. In the Chapter 5, we show you a program that combines passing the parameters to main and the file I/O operations. Please refer to Program Homework 1. Make a calendar for 2013.

26 22 CHAPTER 3. ARRAYS AND POINTERS Program 13 Srings. #include <stdio.h> #include <stdlib.h> int main(int argc, char ** argv){ printf("there are %d parameters of this program \n", argc); int i; for(i=0;i<argc;i++) printf("the %dth parameter of this program is %s \n",i+1, argv[i]); return 0; 2. Use the malloc function to generate two vectors, initialize them, and compute the inner product of the two vectors. 3. Use the malloc function to generate a matrix and initialize the matrix with some values. Then calculate the sum of all the elements in the matrix and print out the result.

27 Chapter 4 Functions and Header Files Functions and headers are abstractions that encapsulate a concept or algoritm. 4.1 Functions In this section, we introduce basic functions and give some useful concepts. If you are more interested in this chpater, look at the book, George Em Karniadakis and Robert M. Kirby II [6] Basics of Functions A function is a program statement that is a collection of particular operations to reuse it. Functions can be implemented as many different points in a C Program as required. Let s make an example. In mathematics, we note a function like f (x) = x 3 2x 2 + 3x 4. If we calculate 10 + f (1), we use a mathematical logic like following. 1. Input 1 into f (x). 2. Evaluate f (1). So, f (1) = 1 3 2(1) 2 + 3(1) 4 = f (1) = 10 + ( 2) = 8. This an example demonstrates the three major components of a function: input, output, and algorithm. So, we specified the valid range of parameters that can be an input into this function (like domain in the mathematics) and output (like range in the mathematics) from the function. The format of the syntax of function is For example, Type Function name( Type Variable name, Type Variable name,... ) float f (float x). 23

28 24 CHAPTER 4. FUNCTIONS AND HEADER FILES Function 1 This code is an example of function. It will return the value of evaluation for x 3 2x 2 + 3x 4 after some value is inputted. float f(float x) // Function definition { float ly ; // This is local variable. // This is only defined on this function ly = x*x*x - 2*x*x + 3*x - 4; // f(x) = xˆ3-2xˆ2 + 3x -4 return ly; // This is return value This function f inputes one variable of a float type and also outputs one variable of a float type. So, using the above example, we can make function code like the Function 1. In C language, there need two steps to call the function: the function declarations and the function definitions. In the function declarations, it declares the name of functions and the data types of the input and output of the function. For example, float f(float); This should be declared before it is used even though function is defined at any place in the program. The Program 14 is a whole code for this example. Program 14 This code will show you the value of 10 + f (1). #include <stdio.h> float f(float x); int main(int argc, char ** argv){ float x; float y; float z; // Function declaration // This is a variable for the function // This is a result of the function // This is a final result y = f(1); // Call the function to evaluate at the point x=1 z = 10 + y; // Evaluate 10+f(1) printf("the value of 10+f(1) is %f. \n", z); return 0; Passing Parameters to a Function There are two different ways to pass parameters to a function: 1. Pass by Value: This is used when you do not want to change the value of passed parameters. When parameters are passed by value then functions in C create copies of the passed in variables and do required processing on these copied variables.

29 4.1. FUNCTIONS 25 Function 2 This is the function f of Program 14. float f(float x) // Function definition float ly ; // This is local variable. // This is only defined on this function ly = x*x*x - 2*x*x + 3*x - 4; // f(x) = xˆ3-2xˆ2 + 3x -4 return ly; // This is an output of this function 2. Pass by Reference: This is used when you want a function to do the changes in passed parameters and reflect those changes back to the calling function. In this case only addresses of the variables are passed to a function so that function can work directly over the addresses. Program 15 is an example for difference of these two ways. Program 15 This code is to sort the two numbers using two different ways. #include <stdio.h> void sort_pv(int a, int b); void sort_pr(int *a, int *b); int main (int argc, char ** argv){ int x1; int x2; x1 = 100; x2 = 10; // Function declaration (Pass by Value) // Function declaration (Pass by Reference) // This is the number to be sorted // This is the number to be sorted // Set the value of x1 // Set the value of x2 sort_pv(x1,x2); printf("%d is smaller than %d in the concept of pass by value \n", x1,x2); sort_pr(&x1,&x2); printf("%d is smaller than %d in the concept of pass by reference \n", x1,x2); return 0; Since the way of passing by value is just a copy the input values, the values of x1 and x2 are not changed even though these values are sorted in the sort PV function. However, another function, sort PR, makes these values sorted and changes the values of x1 and x2. Therefore, the result is 100 is smaller than 10 in the concept of pass by value 10 is smaller than 100 in the concept of pass by reference

30 26 CHAPTER 4. FUNCTIONS AND HEADER FILES Function 3 This the function sort PV and sort PR of Program 15. void sort_pv( int a, int b) // Function definition (Pass by Value) { int min; // This is a temporary variable to save the minimum if ( a > b ) // Compare of these two input numbers. { // If first element is smaller than second one, // nothing is happened min = b; // Save the smaller number into "min" b = a; a = min; // Switch the number void sort_pr( int *a, int *b) // Function definition (Pass by Reference) { int min; // This is a temporary variable to save the minimum if ( *a > *b ) // Compare of these two input numbers { // If first element is smaller than second one, // nothing is happened min = *b; // Save the smaller number into "min" *b = *a *a = min; // Switch the number

31 4.1. FUNCTIONS Passing an Array to a Function The only way to pass an array to a function is to use a pointer. Also, the function can get only one address from the input file. So, using the pointer in the Chapter 3, let s start with a simple example of adding all elements in a vector. Before making a code, we should consider what we need to input to the function. Of course, the array should be needed. It also needs to have an array size since the function doesn t have any information about the size of array. Based on these information, the Program 16 is provided. Program 16 This code is to add all elements in one vector. This example inllustrates how the array passes into a function. #include <stdio.h> #include <stdlib.h> // To use "malloc", we need this header file double L1_norm(double *a, int size); // Function declaration int main(int argc, char** argv) { double *vec; // Give a pointer to a variable. int size; // Declare for array size int i; // This is the number for "for" loop size = 5; // Setting the size vec = (double *) malloc (size * sizeof( double ) ); // Memory allocate for the array for ( i = 0; i < size; i++ ) vec[i] = i+0.5; // Setting the array printf("the summation of elements in the vector is %lf \n ",L1_norm(vec,size)); Function 4 This is the function L1 norm of Program 16. double L1_norm(double *a, int size) // Function definition { int i; // Local variable for "for" loop double sum = 0; // Save the summation value for( i=0; i<size; i++) sum += a[i]; return sum; // Operation for summation // Return the summation. Since functions can get only one pointer, if you use L1 norm(vec,size)), then the L1 norm function can get the address of vec[0]. So, if we use the concept of passing by reference, we can add all elements in a vector. By the same idea, we can also change from a[i] to *(a+i) in L1 norm function.

32 28 CHAPTER 4. FUNCTIONS AND HEADER FILES Next, let s make the dot product using two n-dimension vectors. As you know, the dot product is n 1 u v = u i v i where u = (u 1, u 2,..., u n ) and v = (v 1, v 2,..., v n ). By the similar algorithm as above, the function needs a size variable as well as two arrays. This code is provided in Program 17. Program 17 This code is for a dot product. This code show you how to pass two arrays to a function. #include <stdio.h> #include <stdlib.h> i=0 int dot(int *v1, int *v2, int dim); int main(int argc, char** argv){ int *vec1; int *vec2; // Function declaration // This is a pointer for 1st array // This is a pointer for 2nd array int dim = 5; // This is the dimension int i ; // This is for "for" loop vec1 = (int *) malloc(dim * sizeof(int) ); vec2 = (int *) malloc(dim * sizeof(int) ); for(i = 0 ; i < dim; i++) { vec1[i] = 5-i; vec2[i] = i+1; // Memory allocate for 1st array // Memory allocate for 2nd array //Genearate the vectors printf("v1 is ( %d, %d, %d, %d, %d ) \n", vec1[0], vec1[1], vec1[2], vec1[3], vec1[4]); printf("v2 is ( %d, %d, %d, %d, %d ) \n", vec2[0], vec2[1], vec2[2], vec2[3], vec2[4]); printf( "< v1, v2 > is %d \n.", dot(vec1, vec2, dim)); Then, how can we pass the double pointers to a function? The multiplication of a matrix and a vector is a good example. Suppose the matrix, M, is a m m matrix and the element denotes a i, j, i th row and j th column. Also, suppose vector is a m dimension vector and the element denotes v i. As you know, the result of the multiplication is a vector. Therefore, the equation of this multiplication is n 1 (Mv) i = a i, j v j Using this information, Program 18 shows us this multiplication. In the Program 18, there is an important thing you should know. The function mat vec is declared by int* mat vec(int **mat, int *vec, int dim);. The output type is int since the result is also j=0

33 4.1. FUNCTIONS 29 Function 5 This is the function dot of Program 17. int dot(int *v1, int *v2, int dim) { int i; int sum=0; // Function definition // Local variable for "for" loop // Local variable to save a summation for (i=0; i<dim; i++) { sum += v1[i]*v2[i]; return sum; // Opearate the dot product // Return the summation array. Therefore, this function also returns pointer for the result. Then, we should get a pointer from the function. That is why Mv is declared by a pointer. This code can change simpler way using the multiplication of two vectors. This is on your exercise. Furthermore, you can also make a code for the multiplication of two matrices using this idea Function Recurision Recursion is when the function calls itself in the function. This looks like a never ending loop, so we need to put some condition to finish this loop. The Program 19 shows how to implement function recursion to calculate the factorial. When the function, factorial(n), is called, the function runs recursively until n=1. So, after running this function, y saves = 120. So, the result is 20.

34 30 CHAPTER 4. FUNCTIONS AND HEADER FILES Program 18 This code is the multiplication with a matrix and a vector. This shows how to apply the double pointer to the function. #include <stdio.h> #include <stdlib.h> int* mat_vec(int **mat, int *vec, int dim); int main(int argc, char ** argv){ int **mat; int *vec; int dim=3; int *Mv; int i,j; mat = ( int ** ) malloc ( dim * sizeof( int * ) ) ; for (i=0; i<dim; i++) mat[i] = ( int * ) malloc ( dim * sizeof( int ) ); vec = ( int * ) malloc ( dim * sizeof( int ) ); //Function declaration // Declare double pointer for matrix // Declare pointer for vector // Declare and set the dimension // This is for the result from // the mat_vec function // This is the number for "for" loop // Allocate the memory for the mat // Allocate the memory for the vec srand(time(null)); printf(" \n The matrix,m, is \n"); for (i=0; i<dim; i++) { for (j=0; j<dim; j++) { mat[i][j] = rand()%10-5; printf(" %d ",mat[i][j]); // Generate different seed printf("\n"); // Setting the matrix printf(" The vector,v, is \n"); for(i=0; i<dim; i++) { vec[i] = rand()%10-5; printf(" %d \n",vec[i]); // Setting the vector printf(" Then, Mv is \n"); Mv = mat_vec(mat, vec, dim) ; // Save the address of result[0] for (j=0; j<dim; j++) // into a pointer of Mv printf(" %d \n", Mv[j]); //printf(" %d \n", *(Mv+j)); // Another version using pointer printf("\n");

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

5 Arrays and Pointers

5 Arrays and Pointers 5 Arrays and Pointers 5.1 One-dimensional arrays Arrays offer a convenient way to store and access blocks of data. Think of arrays as a sequential list that offers indexed access. For example, a list of

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

I PUC - Computer Science. Practical s Syllabus. Contents

I PUC - Computer Science. Practical s Syllabus. Contents I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example Announcements Memory management Assignment 2 posted, due Friday Do two of the three problems Assignment 1 graded see grades on CMS Lecture 7 CS 113 Spring 2008 2 Safe user input If you use scanf(), include

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

How To Write Portable Programs In C

How To Write Portable Programs In C Writing Portable Programs COS 217 1 Goals of Today s Class Writing portable programs in C Sources of heterogeneity Data types, evaluation order, byte order, char set, Reading period and final exam Important

More information

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

An Introduction to Assembly Programming with the ARM 32-bit Processor Family An Introduction to Assembly Programming with the ARM 32-bit Processor Family G. Agosta Politecnico di Milano December 3, 2011 Contents 1 Introduction 1 1.1 Prerequisites............................. 2

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions Phys4051: C Lecture 2 & 3 Functions (Review) Comment Statements Variables & Operators Branching Instructions Comment Statements! Method 1: /* */! Method 2: // /* Single Line */ //Single Line /* This comment

More information

Overview. Lecture 1: an introduction to CUDA. Hardware view. Hardware view. hardware view software view CUDA programming

Overview. Lecture 1: an introduction to CUDA. Hardware view. Hardware view. hardware view software view CUDA programming Overview Lecture 1: an introduction to CUDA Mike Giles mike.giles@maths.ox.ac.uk hardware view software view Oxford University Mathematical Institute Oxford e-research Centre Lecture 1 p. 1 Lecture 1 p.

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

FEEG6002 - Applied Programming 5 - Tutorial Session

FEEG6002 - Applied Programming 5 - Tutorial Session FEEG6002 - Applied Programming 5 - Tutorial Session Sam Sinayoko 2015-10-30 1 / 38 Outline Objectives Two common bugs General comments on style String formatting Questions? Summary 2 / 38 Objectives Revise

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

More information

Tutorial on C Language Programming

Tutorial on C Language Programming Tutorial on C Language Programming Teodor Rus rus@cs.uiowa.edu The University of Iowa, Department of Computer Science Introduction to System Software p.1/64 Tutorial on C programming C program structure:

More information

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Objective-C Tutorial

Objective-C Tutorial Objective-C Tutorial OBJECTIVE-C TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Objective-c tutorial Objective-C is a general-purpose, object-oriented programming

More information

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands C Programming for Embedded Microcontrollers Warwick A. Smith Elektor International Media BV Postbus 11 6114ZG Susteren The Netherlands 3 the Table of Contents Introduction 11 Target Audience 11 What is

More information

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012 7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012 October 17 th, 2012. Rules For all problems, read carefully the input and output session. For all problems, a sequential implementation is given,

More information

DNA Data and Program Representation. Alexandre David 1.2.05 adavid@cs.aau.dk

DNA Data and Program Representation. Alexandre David 1.2.05 adavid@cs.aau.dk DNA Data and Program Representation Alexandre David 1.2.05 adavid@cs.aau.dk Introduction Very important to understand how data is represented. operations limits precision Digital logic built on 2-valued

More information

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T) Unit- I Introduction to c Language: C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating

More information

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012 Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero THEN the Average is Sum divided by Count Conditions

More information

Parallel Computing. Shared memory parallel programming with OpenMP

Parallel Computing. Shared memory parallel programming with OpenMP Parallel Computing Shared memory parallel programming with OpenMP Thorsten Grahs, 27.04.2015 Table of contents Introduction Directives Scope of data Synchronization 27.04.2015 Thorsten Grahs Parallel Computing

More information

Storing Measurement Data

Storing Measurement Data Storing Measurement Data File I/O records or reads data in a file. A typical file I/O operation involves the following process. 1. Create or open a file. Indicate where an existing file resides or where

More information

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer About The Tutorial C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.

More information

As previously noted, a byte can contain a numeric value in the range 0-255. Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

As previously noted, a byte can contain a numeric value in the range 0-255. Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets! Encoding of alphanumeric and special characters As previously noted, a byte can contain a numeric value in the range 0-255. Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets! Alphanumeric

More information

Parallel and Distributed Computing Programming Assignment 1

Parallel and Distributed Computing Programming Assignment 1 Parallel and Distributed Computing Programming Assignment 1 Due Monday, February 7 For programming assignment 1, you should write two C programs. One should provide an estimate of the performance of ping-pong

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

Base Conversion written by Cathy Saxton

Base Conversion written by Cathy Saxton Base Conversion written by Cathy Saxton 1. Base 10 In base 10, the digits, from right to left, specify the 1 s, 10 s, 100 s, 1000 s, etc. These are powers of 10 (10 x ): 10 0 = 1, 10 1 = 10, 10 2 = 100,

More information

Parallelization: Binary Tree Traversal

Parallelization: Binary Tree Traversal By Aaron Weeden and Patrick Royal Shodor Education Foundation, Inc. August 2012 Introduction: According to Moore s law, the number of transistors on a computer chip doubles roughly every two years. First

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Pseudo code Tutorial and Exercises Teacher s Version

Pseudo code Tutorial and Exercises Teacher s Version Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy

More information

The C Programming Language

The C Programming Language Chapter 1 The C Programming Language In this chapter we will learn how to write simple computer programs using the C programming language; perform basic mathematical calculations; manage data stored in

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

CS 241 Data Organization Coding Standards

CS 241 Data Organization Coding Standards CS 241 Data Organization Coding Standards Brooke Chenoweth University of New Mexico Spring 2016 CS-241 Coding Standards All projects and labs must follow the great and hallowed CS-241 coding standards.

More information

Chapter 7: Additional Topics

Chapter 7: Additional Topics Chapter 7: Additional Topics In this chapter we ll briefly cover selected advanced topics in fortran programming. All the topics come in handy to add extra functionality to programs, but the feature you

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Parallel Computing. Parallel shared memory computing with OpenMP

Parallel Computing. Parallel shared memory computing with OpenMP Parallel Computing Parallel shared memory computing with OpenMP Thorsten Grahs, 14.07.2014 Table of contents Introduction Directives Scope of data Synchronization OpenMP vs. MPI OpenMP & MPI 14.07.2014

More information

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables AMATH 352 Lecture 3 MATLAB Tutorial MATLAB (short for MATrix LABoratory) is a very useful piece of software for numerical analysis. It provides an environment for computation and the visualization. Learning

More information

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand: Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

More information

Lecture 2 Notes: Flow of Control

Lecture 2 Notes: Flow of Control 6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

C PROGRAMMING FOR MATHEMATICAL COMPUTING

C PROGRAMMING FOR MATHEMATICAL COMPUTING UNIVERSITY OF CALICUT SCHOOL OF DISTANCE EDUCATION BSc MATHEMATICS (2011 Admission Onwards) VI Semester Elective Course C PROGRAMMING FOR MATHEMATICAL COMPUTING QUESTION BANK Multiple Choice Questions

More information

1 Description of The Simpletron

1 Description of The Simpletron Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

Chapter 4: Computer Codes

Chapter 4: Computer Codes Slide 1/30 Learning Objectives In this chapter you will learn about: Computer data Computer codes: representation of data in binary Most commonly used computer codes Collating sequence 36 Slide 2/30 Data

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 UX Software - 2009 TABLE OF CONTENTS INTRODUCTION... ii What is this book about?... iii How to use this book... iii Time to start...

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

/* File: blkcopy.c. size_t n

/* File: blkcopy.c. size_t n 13.1. BLOCK INPUT/OUTPUT 505 /* File: blkcopy.c The program uses block I/O to copy a file. */ #include main() { signed char buf[100] const void *ptr = (void *) buf FILE *input, *output size_t

More information

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 04 Digital Logic II May, I before starting the today s lecture

More information

WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math

WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math Textbook Correlation WESTMORELAND COUNTY PUBLIC SCHOOLS 2011 2012 Integrated Instructional Pacing Guide and Checklist Computer Math Following Directions Unit FIRST QUARTER AND SECOND QUARTER Logic Unit

More information

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE PROGRAMMING IN C CONTENT AT A GLANCE 1 MODULE 1 Unit 1 : Basics of Programming Unit 2 : Fundamentals Unit 3 : C Operators MODULE 2 unit 1 : Input Output Statements unit 2 : Control Structures unit 3 :

More information

6 3 4 9 = 6 10 + 3 10 + 4 10 + 9 10

6 3 4 9 = 6 10 + 3 10 + 4 10 + 9 10 Lesson The Binary Number System. Why Binary? The number system that you are familiar with, that you use every day, is the decimal number system, also commonly referred to as the base- system. When you

More information

Q&As: Microsoft Excel 2013: Chapter 2

Q&As: Microsoft Excel 2013: Chapter 2 Q&As: Microsoft Excel 2013: Chapter 2 In Step 5, why did the date that was entered change from 4/5/10 to 4/5/2010? When Excel recognizes that you entered a date in mm/dd/yy format, it automatically formats

More information

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu C / C++ and Unix Programming Materials adapted from Dan Hood and Dianna Xu 1 C and Unix Programming Today s goals ú History of C ú Basic types ú printf ú Arithmetic operations, types and casting ú Intro

More information

CUDA Programming. Week 4. Shared memory and register

CUDA Programming. Week 4. Shared memory and register CUDA Programming Week 4. Shared memory and register Outline Shared memory and bank confliction Memory padding Register allocation Example of matrix-matrix multiplication Homework SHARED MEMORY AND BANK

More information

Illustration 1: Diagram of program function and data flow

Illustration 1: Diagram of program function and data flow The contract called for creation of a random access database of plumbing shops within the near perimeter of FIU Engineering school. The database features a rating number from 1-10 to offer a guideline

More information

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint) TN203 Porting a Program to Dynamic C Introduction Dynamic C has a number of improvements and differences compared to many other C compiler systems. This application note gives instructions and suggestions

More information

Data Structures using OOP C++ Lecture 1

Data Structures using OOP C++ Lecture 1 References: 1. E Balagurusamy, Object Oriented Programming with C++, 4 th edition, McGraw-Hill 2008. 2. Robert Lafore, Object-Oriented Programming in C++, 4 th edition, 2002, SAMS publishing. 3. Robert

More information

MATLAB Basics MATLAB numbers and numeric formats

MATLAB Basics MATLAB numbers and numeric formats MATLAB Basics MATLAB numbers and numeric formats All numerical variables are stored in MATLAB in double precision floating-point form. (In fact it is possible to force some variables to be of other types

More information

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison

SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89. by Joseph Collison SYSTEMS OF EQUATIONS AND MATRICES WITH THE TI-89 by Joseph Collison Copyright 2000 by Joseph Collison All rights reserved Reproduction or translation of any part of this work beyond that permitted by Sections

More information

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)

ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology) ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology) Subject Description: This subject deals with discrete structures like set theory, mathematical

More information

PROBLEMS (Cap. 4 - Istruzioni macchina)

PROBLEMS (Cap. 4 - Istruzioni macchina) 98 CHAPTER 2 MACHINE INSTRUCTIONS AND PROGRAMS PROBLEMS (Cap. 4 - Istruzioni macchina) 2.1 Represent the decimal values 5, 2, 14, 10, 26, 19, 51, and 43, as signed, 7-bit numbers in the following binary

More information

SQL Server Array Library 2010-11 László Dobos, Alexander S. Szalay

SQL Server Array Library 2010-11 László Dobos, Alexander S. Szalay SQL Server Array Library 2010-11 László Dobos, Alexander S. Szalay The Johns Hopkins University, Department of Physics and Astronomy Eötvös University, Department of Physics of Complex Systems http://voservices.net/sqlarray,

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

Course Title: Software Development

Course Title: Software Development Course Title: Software Development Unit: Customer Service Content Standard(s) and Depth of 1. Analyze customer software needs and system requirements to design an information technology-based project plan.

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab Social Science Research Lab American University, Washington, D.C. Web. www.american.edu/provost/ctrl/pclabs.cfm Tel. x3862 Email. SSRL@American.edu Course Objective This course provides

More information

Instruction Set Architecture (ISA)

Instruction Set Architecture (ISA) Instruction Set Architecture (ISA) * Instruction set architecture of a machine fills the semantic gap between the user and the machine. * ISA serves as the starting point for the design of a new machine

More information

Dynamic Programming. Lecture 11. 11.1 Overview. 11.2 Introduction

Dynamic Programming. Lecture 11. 11.1 Overview. 11.2 Introduction Lecture 11 Dynamic Programming 11.1 Overview Dynamic Programming is a powerful technique that allows one to solve many different types of problems in time O(n 2 ) or O(n 3 ) for which a naive approach

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

Binary Number System. 16. Binary Numbers. Base 10 digits: 0 1 2 3 4 5 6 7 8 9. Base 2 digits: 0 1

Binary Number System. 16. Binary Numbers. Base 10 digits: 0 1 2 3 4 5 6 7 8 9. Base 2 digits: 0 1 Binary Number System 1 Base 10 digits: 0 1 2 3 4 5 6 7 8 9 Base 2 digits: 0 1 Recall that in base 10, the digits of a number are just coefficients of powers of the base (10): 417 = 4 * 10 2 + 1 * 10 1

More information

Computer Programming Tutorial

Computer Programming Tutorial Computer Programming Tutorial COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com tutorialspoint.com i ABOUT THE TUTORIAL Computer Prgramming Tutorial Computer programming is the act of writing computer

More information

This Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers

This Unit: Floating Point Arithmetic. CIS 371 Computer Organization and Design. Readings. Floating Point (FP) Numbers This Unit: Floating Point Arithmetic CIS 371 Computer Organization and Design Unit 7: Floating Point App App App System software Mem CPU I/O Formats Precision and range IEEE 754 standard Operations Addition

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Computer Science 281 Binary and Hexadecimal Review

Computer Science 281 Binary and Hexadecimal Review Computer Science 281 Binary and Hexadecimal Review 1 The Binary Number System Computers store everything, both instructions and data, by using many, many transistors, each of which can be in one of two

More information

Introduction to Python

Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

More information